PackageManagerService.java revision 5dde6e334d06e5c2116b2169d7ad67e95238a6f0
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
46import static android.content.pm.PackageParser.isApkFile;
47import static android.os.Process.PACKAGE_INFO_GID;
48import static android.os.Process.SYSTEM_UID;
49import static android.system.OsConstants.O_CREAT;
50import static android.system.OsConstants.O_RDWR;
51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
55import static com.android.internal.util.ArrayUtils.appendInt;
56import static com.android.internal.util.ArrayUtils.removeInt;
57
58import android.util.ArrayMap;
59
60import com.android.internal.R;
61import com.android.internal.app.IMediaContainerService;
62import com.android.internal.app.ResolverActivity;
63import com.android.internal.content.NativeLibraryHelper;
64import com.android.internal.content.PackageHelper;
65import com.android.internal.os.IParcelFileDescriptorFactory;
66import com.android.internal.util.ArrayUtils;
67import com.android.internal.util.FastPrintWriter;
68import com.android.internal.util.FastXmlSerializer;
69import com.android.internal.util.IndentingPrintWriter;
70import com.android.server.EventLogTags;
71import com.android.server.IntentResolver;
72import com.android.server.LocalServices;
73import com.android.server.ServiceThread;
74import com.android.server.SystemConfig;
75import com.android.server.Watchdog;
76import com.android.server.pm.Settings.DatabaseVersion;
77import com.android.server.storage.DeviceStorageMonitorInternal;
78
79import org.xmlpull.v1.XmlSerializer;
80
81import android.app.ActivityManager;
82import android.app.ActivityManagerNative;
83import android.app.IActivityManager;
84import android.app.admin.IDevicePolicyManager;
85import android.app.backup.IBackupManager;
86import android.content.BroadcastReceiver;
87import android.content.ComponentName;
88import android.content.Context;
89import android.content.IIntentReceiver;
90import android.content.Intent;
91import android.content.IntentFilter;
92import android.content.IntentSender;
93import android.content.IntentSender.SendIntentException;
94import android.content.ServiceConnection;
95import android.content.pm.ActivityInfo;
96import android.content.pm.ApplicationInfo;
97import android.content.pm.FeatureInfo;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.KeySet;
108import android.content.pm.ManifestDigest;
109import android.content.pm.PackageCleanItem;
110import android.content.pm.PackageInfo;
111import android.content.pm.PackageInfoLite;
112import android.content.pm.PackageInstaller;
113import android.content.pm.PackageManager;
114import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageParser;
119import android.content.pm.PackageStats;
120import android.content.pm.PackageUserState;
121import android.content.pm.ParceledListSlice;
122import android.content.pm.PermissionGroupInfo;
123import android.content.pm.PermissionInfo;
124import android.content.pm.ProviderInfo;
125import android.content.pm.ResolveInfo;
126import android.content.pm.ServiceInfo;
127import android.content.pm.Signature;
128import android.content.pm.UserInfo;
129import android.content.pm.VerificationParams;
130import android.content.pm.VerifierDeviceIdentity;
131import android.content.pm.VerifierInfo;
132import android.content.res.Resources;
133import android.hardware.display.DisplayManager;
134import android.net.Uri;
135import android.os.Binder;
136import android.os.Build;
137import android.os.Bundle;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.storage.StorageManager;
141import android.os.Debug;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteException;
151import android.os.SELinux;
152import android.os.ServiceManager;
153import android.os.SystemClock;
154import android.os.SystemProperties;
155import android.os.UserHandle;
156import android.os.UserManager;
157import android.security.KeyStore;
158import android.security.SystemKeyStore;
159import android.system.ErrnoException;
160import android.system.Os;
161import android.system.StructStat;
162import android.text.TextUtils;
163import android.util.ArraySet;
164import android.util.AtomicFile;
165import android.util.DisplayMetrics;
166import android.util.EventLog;
167import android.util.ExceptionUtils;
168import android.util.Log;
169import android.util.LogPrinter;
170import android.util.PrintStreamPrinter;
171import android.util.Slog;
172import android.util.SparseArray;
173import android.util.SparseBooleanArray;
174import android.view.Display;
175
176import java.io.BufferedInputStream;
177import java.io.BufferedOutputStream;
178import java.io.File;
179import java.io.FileDescriptor;
180import java.io.FileInputStream;
181import java.io.FileNotFoundException;
182import java.io.FileOutputStream;
183import java.io.FilenameFilter;
184import java.io.IOException;
185import java.io.InputStream;
186import java.io.PrintWriter;
187import java.nio.charset.StandardCharsets;
188import java.security.NoSuchAlgorithmException;
189import java.security.PublicKey;
190import java.security.cert.CertificateEncodingException;
191import java.security.cert.CertificateException;
192import java.text.SimpleDateFormat;
193import java.util.ArrayList;
194import java.util.Arrays;
195import java.util.Collection;
196import java.util.Collections;
197import java.util.Comparator;
198import java.util.Date;
199import java.util.HashMap;
200import java.util.HashSet;
201import java.util.Iterator;
202import java.util.List;
203import java.util.Map;
204import java.util.Objects;
205import java.util.Set;
206import java.util.concurrent.atomic.AtomicBoolean;
207import java.util.concurrent.atomic.AtomicLong;
208
209import dalvik.system.DexFile;
210import dalvik.system.StaleDexCacheError;
211import dalvik.system.VMRuntime;
212
213import libcore.io.IoUtils;
214import libcore.util.EmptyArray;
215
216/**
217 * Keep track of all those .apks everywhere.
218 *
219 * This is very central to the platform's security; please run the unit
220 * tests whenever making modifications here:
221 *
222mmm frameworks/base/tests/AndroidTests
223adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
224adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
225 *
226 * {@hide}
227 */
228public class PackageManagerService extends IPackageManager.Stub {
229    static final String TAG = "PackageManager";
230    static final boolean DEBUG_SETTINGS = false;
231    static final boolean DEBUG_PREFERRED = false;
232    static final boolean DEBUG_UPGRADE = false;
233    private static final boolean DEBUG_INSTALL = false;
234    private static final boolean DEBUG_REMOVE = false;
235    private static final boolean DEBUG_BROADCASTS = false;
236    private static final boolean DEBUG_SHOW_INFO = false;
237    private static final boolean DEBUG_PACKAGE_INFO = false;
238    private static final boolean DEBUG_INTENT_MATCHING = false;
239    private static final boolean DEBUG_PACKAGE_SCANNING = false;
240    private static final boolean DEBUG_VERIFY = false;
241    private static final boolean DEBUG_DEXOPT = false;
242    private static final boolean DEBUG_ABI_SELECTION = false;
243
244    private static final int RADIO_UID = Process.PHONE_UID;
245    private static final int LOG_UID = Process.LOG_UID;
246    private static final int NFC_UID = Process.NFC_UID;
247    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
248    private static final int SHELL_UID = Process.SHELL_UID;
249
250    // Cap the size of permission trees that 3rd party apps can define
251    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
252
253    // Suffix used during package installation when copying/moving
254    // package apks to install directory.
255    private static final String INSTALL_PACKAGE_SUFFIX = "-";
256
257    static final int SCAN_NO_DEX = 1<<1;
258    static final int SCAN_FORCE_DEX = 1<<2;
259    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
260    static final int SCAN_NEW_INSTALL = 1<<4;
261    static final int SCAN_NO_PATHS = 1<<5;
262    static final int SCAN_UPDATE_TIME = 1<<6;
263    static final int SCAN_DEFER_DEX = 1<<7;
264    static final int SCAN_BOOTING = 1<<8;
265    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
266    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
267    static final int SCAN_REPLACING = 1<<11;
268
269    static final int REMOVE_CHATTY = 1<<16;
270
271    /**
272     * Timeout (in milliseconds) after which the watchdog should declare that
273     * our handler thread is wedged.  The usual default for such things is one
274     * minute but we sometimes do very lengthy I/O operations on this thread,
275     * such as installing multi-gigabyte applications, so ours needs to be longer.
276     */
277    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
278
279    /**
280     * Whether verification is enabled by default.
281     */
282    private static final boolean DEFAULT_VERIFY_ENABLE = true;
283
284    /**
285     * The default maximum time to wait for the verification agent to return in
286     * milliseconds.
287     */
288    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
289
290    /**
291     * The default response for package verification timeout.
292     *
293     * This can be either PackageManager.VERIFICATION_ALLOW or
294     * PackageManager.VERIFICATION_REJECT.
295     */
296    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
297
298    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
299
300    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
301            DEFAULT_CONTAINER_PACKAGE,
302            "com.android.defcontainer.DefaultContainerService");
303
304    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
305
306    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
307
308    private static String sPreferredInstructionSet;
309
310    final ServiceThread mHandlerThread;
311
312    private static final String IDMAP_PREFIX = "/data/resource-cache/";
313    private static final String IDMAP_SUFFIX = "@idmap";
314
315    final PackageHandler mHandler;
316
317    /**
318     * Messages for {@link #mHandler} that need to wait for system ready before
319     * being dispatched.
320     */
321    private ArrayList<Message> mPostSystemReadyMessages;
322
323    final int mSdkVersion = Build.VERSION.SDK_INT;
324
325    final Context mContext;
326    final boolean mFactoryTest;
327    final boolean mOnlyCore;
328    final boolean mLazyDexOpt;
329    final DisplayMetrics mMetrics;
330    final int mDefParseFlags;
331    final String[] mSeparateProcesses;
332
333    // This is where all application persistent data goes.
334    final File mAppDataDir;
335
336    // This is where all application persistent data goes for secondary users.
337    final File mUserAppDataDir;
338
339    /** The location for ASEC container files on internal storage. */
340    final String mAsecInternalPath;
341
342    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
343    // LOCK HELD.  Can be called with mInstallLock held.
344    final Installer mInstaller;
345
346    /** Directory where installed third-party apps stored */
347    final File mAppInstallDir;
348
349    /**
350     * Directory to which applications installed internally have their
351     * 32 bit native libraries copied.
352     */
353    private File mAppLib32InstallDir;
354
355    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
356    // apps.
357    final File mDrmAppPrivateInstallDir;
358
359    // ----------------------------------------------------------------
360
361    // Lock for state used when installing and doing other long running
362    // operations.  Methods that must be called with this lock held have
363    // the suffix "LI".
364    final Object mInstallLock = new Object();
365
366    // ----------------------------------------------------------------
367
368    // Keys are String (package name), values are Package.  This also serves
369    // as the lock for the global state.  Methods that must be called with
370    // this lock held have the prefix "LP".
371    final HashMap<String, PackageParser.Package> mPackages =
372            new HashMap<String, PackageParser.Package>();
373
374    // Tracks available target package names -> overlay package paths.
375    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
376        new HashMap<String, HashMap<String, PackageParser.Package>>();
377
378    final Settings mSettings;
379    boolean mRestoredSettings;
380
381    // System configuration read by SystemConfig.
382    final int[] mGlobalGids;
383    final SparseArray<HashSet<String>> mSystemPermissions;
384    final HashMap<String, FeatureInfo> mAvailableFeatures;
385
386    // If mac_permissions.xml was found for seinfo labeling.
387    boolean mFoundPolicyFile;
388
389    // If a recursive restorecon of /data/data/<pkg> is needed.
390    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
391
392    public static final class SharedLibraryEntry {
393        public final String path;
394        public final String apk;
395
396        SharedLibraryEntry(String _path, String _apk) {
397            path = _path;
398            apk = _apk;
399        }
400    }
401
402    // Currently known shared libraries.
403    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
404            new HashMap<String, SharedLibraryEntry>();
405
406    // All available activities, for your resolving pleasure.
407    final ActivityIntentResolver mActivities =
408            new ActivityIntentResolver();
409
410    // All available receivers, for your resolving pleasure.
411    final ActivityIntentResolver mReceivers =
412            new ActivityIntentResolver();
413
414    // All available services, for your resolving pleasure.
415    final ServiceIntentResolver mServices = new ServiceIntentResolver();
416
417    // All available providers, for your resolving pleasure.
418    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
419
420    // Mapping from provider base names (first directory in content URI codePath)
421    // to the provider information.
422    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
423            new HashMap<String, PackageParser.Provider>();
424
425    // Mapping from instrumentation class names to info about them.
426    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
427            new HashMap<ComponentName, PackageParser.Instrumentation>();
428
429    // Mapping from permission names to info about them.
430    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
431            new HashMap<String, PackageParser.PermissionGroup>();
432
433    // Packages whose data we have transfered into another package, thus
434    // should no longer exist.
435    final HashSet<String> mTransferedPackages = new HashSet<String>();
436
437    // Broadcast actions that are only available to the system.
438    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
439
440    /** List of packages waiting for verification. */
441    final SparseArray<PackageVerificationState> mPendingVerification
442            = new SparseArray<PackageVerificationState>();
443
444    /** Set of packages associated with each app op permission. */
445    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
446
447    final PackageInstallerService mInstallerService;
448
449    HashSet<PackageParser.Package> mDeferredDexOpt = null;
450
451    // Cache of users who need badging.
452    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
453
454    /** Token for keys in mPendingVerification. */
455    private int mPendingVerificationToken = 0;
456
457    volatile boolean mSystemReady;
458    volatile boolean mSafeMode;
459    volatile boolean mHasSystemUidErrors;
460
461    ApplicationInfo mAndroidApplication;
462    final ActivityInfo mResolveActivity = new ActivityInfo();
463    final ResolveInfo mResolveInfo = new ResolveInfo();
464    ComponentName mResolveComponentName;
465    PackageParser.Package mPlatformPackage;
466    ComponentName mCustomResolverComponentName;
467
468    boolean mResolverReplaced = false;
469
470    // Set of pending broadcasts for aggregating enable/disable of components.
471    static class PendingPackageBroadcasts {
472        // for each user id, a map of <package name -> components within that package>
473        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
474
475        public PendingPackageBroadcasts() {
476            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
477        }
478
479        public ArrayList<String> get(int userId, String packageName) {
480            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
481            return packages.get(packageName);
482        }
483
484        public void put(int userId, String packageName, ArrayList<String> components) {
485            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
486            packages.put(packageName, components);
487        }
488
489        public void remove(int userId, String packageName) {
490            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
491            if (packages != null) {
492                packages.remove(packageName);
493            }
494        }
495
496        public void remove(int userId) {
497            mUidMap.remove(userId);
498        }
499
500        public int userIdCount() {
501            return mUidMap.size();
502        }
503
504        public int userIdAt(int n) {
505            return mUidMap.keyAt(n);
506        }
507
508        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
509            return mUidMap.get(userId);
510        }
511
512        public int size() {
513            // total number of pending broadcast entries across all userIds
514            int num = 0;
515            for (int i = 0; i< mUidMap.size(); i++) {
516                num += mUidMap.valueAt(i).size();
517            }
518            return num;
519        }
520
521        public void clear() {
522            mUidMap.clear();
523        }
524
525        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
526            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
527            if (map == null) {
528                map = new HashMap<String, ArrayList<String>>();
529                mUidMap.put(userId, map);
530            }
531            return map;
532        }
533    }
534    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
535
536    // Service Connection to remote media container service to copy
537    // package uri's from external media onto secure containers
538    // or internal storage.
539    private IMediaContainerService mContainerService = null;
540
541    static final int SEND_PENDING_BROADCAST = 1;
542    static final int MCS_BOUND = 3;
543    static final int END_COPY = 4;
544    static final int INIT_COPY = 5;
545    static final int MCS_UNBIND = 6;
546    static final int START_CLEANING_PACKAGE = 7;
547    static final int FIND_INSTALL_LOC = 8;
548    static final int POST_INSTALL = 9;
549    static final int MCS_RECONNECT = 10;
550    static final int MCS_GIVE_UP = 11;
551    static final int UPDATED_MEDIA_STATUS = 12;
552    static final int WRITE_SETTINGS = 13;
553    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
554    static final int PACKAGE_VERIFIED = 15;
555    static final int CHECK_PENDING_VERIFICATION = 16;
556
557    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
558
559    // Delay time in millisecs
560    static final int BROADCAST_DELAY = 10 * 1000;
561
562    static UserManagerService sUserManager;
563
564    // Stores a list of users whose package restrictions file needs to be updated
565    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
566
567    final private DefaultContainerConnection mDefContainerConn =
568            new DefaultContainerConnection();
569    class DefaultContainerConnection implements ServiceConnection {
570        public void onServiceConnected(ComponentName name, IBinder service) {
571            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
572            IMediaContainerService imcs =
573                IMediaContainerService.Stub.asInterface(service);
574            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
575        }
576
577        public void onServiceDisconnected(ComponentName name) {
578            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
579        }
580    };
581
582    // Recordkeeping of restore-after-install operations that are currently in flight
583    // between the Package Manager and the Backup Manager
584    class PostInstallData {
585        public InstallArgs args;
586        public PackageInstalledInfo res;
587
588        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
589            args = _a;
590            res = _r;
591        }
592    };
593    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
594    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
595
596    private final String mRequiredVerifierPackage;
597
598    private final PackageUsage mPackageUsage = new PackageUsage();
599
600    private class PackageUsage {
601        private static final int WRITE_INTERVAL
602            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
603
604        private final Object mFileLock = new Object();
605        private final AtomicLong mLastWritten = new AtomicLong(0);
606        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
607
608        private boolean mIsHistoricalPackageUsageAvailable = true;
609
610        boolean isHistoricalPackageUsageAvailable() {
611            return mIsHistoricalPackageUsageAvailable;
612        }
613
614        void write(boolean force) {
615            if (force) {
616                writeInternal();
617                return;
618            }
619            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
620                && !DEBUG_DEXOPT) {
621                return;
622            }
623            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
624                new Thread("PackageUsage_DiskWriter") {
625                    @Override
626                    public void run() {
627                        try {
628                            writeInternal();
629                        } finally {
630                            mBackgroundWriteRunning.set(false);
631                        }
632                    }
633                }.start();
634            }
635        }
636
637        private void writeInternal() {
638            synchronized (mPackages) {
639                synchronized (mFileLock) {
640                    AtomicFile file = getFile();
641                    FileOutputStream f = null;
642                    try {
643                        f = file.startWrite();
644                        BufferedOutputStream out = new BufferedOutputStream(f);
645                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
646                        StringBuilder sb = new StringBuilder();
647                        for (PackageParser.Package pkg : mPackages.values()) {
648                            if (pkg.mLastPackageUsageTimeInMills == 0) {
649                                continue;
650                            }
651                            sb.setLength(0);
652                            sb.append(pkg.packageName);
653                            sb.append(' ');
654                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
655                            sb.append('\n');
656                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
657                        }
658                        out.flush();
659                        file.finishWrite(f);
660                    } catch (IOException e) {
661                        if (f != null) {
662                            file.failWrite(f);
663                        }
664                        Log.e(TAG, "Failed to write package usage times", e);
665                    }
666                }
667            }
668            mLastWritten.set(SystemClock.elapsedRealtime());
669        }
670
671        void readLP() {
672            synchronized (mFileLock) {
673                AtomicFile file = getFile();
674                BufferedInputStream in = null;
675                try {
676                    in = new BufferedInputStream(file.openRead());
677                    StringBuffer sb = new StringBuffer();
678                    while (true) {
679                        String packageName = readToken(in, sb, ' ');
680                        if (packageName == null) {
681                            break;
682                        }
683                        String timeInMillisString = readToken(in, sb, '\n');
684                        if (timeInMillisString == null) {
685                            throw new IOException("Failed to find last usage time for package "
686                                                  + packageName);
687                        }
688                        PackageParser.Package pkg = mPackages.get(packageName);
689                        if (pkg == null) {
690                            continue;
691                        }
692                        long timeInMillis;
693                        try {
694                            timeInMillis = Long.parseLong(timeInMillisString.toString());
695                        } catch (NumberFormatException e) {
696                            throw new IOException("Failed to parse " + timeInMillisString
697                                                  + " as a long.", e);
698                        }
699                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
700                    }
701                } catch (FileNotFoundException expected) {
702                    mIsHistoricalPackageUsageAvailable = false;
703                } catch (IOException e) {
704                    Log.w(TAG, "Failed to read package usage times", e);
705                } finally {
706                    IoUtils.closeQuietly(in);
707                }
708            }
709            mLastWritten.set(SystemClock.elapsedRealtime());
710        }
711
712        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
713                throws IOException {
714            sb.setLength(0);
715            while (true) {
716                int ch = in.read();
717                if (ch == -1) {
718                    if (sb.length() == 0) {
719                        return null;
720                    }
721                    throw new IOException("Unexpected EOF");
722                }
723                if (ch == endOfToken) {
724                    return sb.toString();
725                }
726                sb.append((char)ch);
727            }
728        }
729
730        private AtomicFile getFile() {
731            File dataDir = Environment.getDataDirectory();
732            File systemDir = new File(dataDir, "system");
733            File fname = new File(systemDir, "package-usage.list");
734            return new AtomicFile(fname);
735        }
736    }
737
738    class PackageHandler extends Handler {
739        private boolean mBound = false;
740        final ArrayList<HandlerParams> mPendingInstalls =
741            new ArrayList<HandlerParams>();
742
743        private boolean connectToService() {
744            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
745                    " DefaultContainerService");
746            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
747            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
748            if (mContext.bindServiceAsUser(service, mDefContainerConn,
749                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
750                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
751                mBound = true;
752                return true;
753            }
754            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
755            return false;
756        }
757
758        private void disconnectService() {
759            mContainerService = null;
760            mBound = false;
761            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
762            mContext.unbindService(mDefContainerConn);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
764        }
765
766        PackageHandler(Looper looper) {
767            super(looper);
768        }
769
770        public void handleMessage(Message msg) {
771            try {
772                doHandleMessage(msg);
773            } finally {
774                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
775            }
776        }
777
778        void doHandleMessage(Message msg) {
779            switch (msg.what) {
780                case INIT_COPY: {
781                    HandlerParams params = (HandlerParams) msg.obj;
782                    int idx = mPendingInstalls.size();
783                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
784                    // If a bind was already initiated we dont really
785                    // need to do anything. The pending install
786                    // will be processed later on.
787                    if (!mBound) {
788                        // If this is the only one pending we might
789                        // have to bind to the service again.
790                        if (!connectToService()) {
791                            Slog.e(TAG, "Failed to bind to media container service");
792                            params.serviceError();
793                            return;
794                        } else {
795                            // Once we bind to the service, the first
796                            // pending request will be processed.
797                            mPendingInstalls.add(idx, params);
798                        }
799                    } else {
800                        mPendingInstalls.add(idx, params);
801                        // Already bound to the service. Just make
802                        // sure we trigger off processing the first request.
803                        if (idx == 0) {
804                            mHandler.sendEmptyMessage(MCS_BOUND);
805                        }
806                    }
807                    break;
808                }
809                case MCS_BOUND: {
810                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
811                    if (msg.obj != null) {
812                        mContainerService = (IMediaContainerService) msg.obj;
813                    }
814                    if (mContainerService == null) {
815                        // Something seriously wrong. Bail out
816                        Slog.e(TAG, "Cannot bind to media container service");
817                        for (HandlerParams params : mPendingInstalls) {
818                            // Indicate service bind error
819                            params.serviceError();
820                        }
821                        mPendingInstalls.clear();
822                    } else if (mPendingInstalls.size() > 0) {
823                        HandlerParams params = mPendingInstalls.get(0);
824                        if (params != null) {
825                            if (params.startCopy()) {
826                                // We are done...  look for more work or to
827                                // go idle.
828                                if (DEBUG_SD_INSTALL) Log.i(TAG,
829                                        "Checking for more work or unbind...");
830                                // Delete pending install
831                                if (mPendingInstalls.size() > 0) {
832                                    mPendingInstalls.remove(0);
833                                }
834                                if (mPendingInstalls.size() == 0) {
835                                    if (mBound) {
836                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
837                                                "Posting delayed MCS_UNBIND");
838                                        removeMessages(MCS_UNBIND);
839                                        Message ubmsg = obtainMessage(MCS_UNBIND);
840                                        // Unbind after a little delay, to avoid
841                                        // continual thrashing.
842                                        sendMessageDelayed(ubmsg, 10000);
843                                    }
844                                } else {
845                                    // There are more pending requests in queue.
846                                    // Just post MCS_BOUND message to trigger processing
847                                    // of next pending install.
848                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
849                                            "Posting MCS_BOUND for next work");
850                                    mHandler.sendEmptyMessage(MCS_BOUND);
851                                }
852                            }
853                        }
854                    } else {
855                        // Should never happen ideally.
856                        Slog.w(TAG, "Empty queue");
857                    }
858                    break;
859                }
860                case MCS_RECONNECT: {
861                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
862                    if (mPendingInstalls.size() > 0) {
863                        if (mBound) {
864                            disconnectService();
865                        }
866                        if (!connectToService()) {
867                            Slog.e(TAG, "Failed to bind to media container service");
868                            for (HandlerParams params : mPendingInstalls) {
869                                // Indicate service bind error
870                                params.serviceError();
871                            }
872                            mPendingInstalls.clear();
873                        }
874                    }
875                    break;
876                }
877                case MCS_UNBIND: {
878                    // If there is no actual work left, then time to unbind.
879                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
880
881                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
882                        if (mBound) {
883                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
884
885                            disconnectService();
886                        }
887                    } else if (mPendingInstalls.size() > 0) {
888                        // There are more pending requests in queue.
889                        // Just post MCS_BOUND message to trigger processing
890                        // of next pending install.
891                        mHandler.sendEmptyMessage(MCS_BOUND);
892                    }
893
894                    break;
895                }
896                case MCS_GIVE_UP: {
897                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
898                    mPendingInstalls.remove(0);
899                    break;
900                }
901                case SEND_PENDING_BROADCAST: {
902                    String packages[];
903                    ArrayList<String> components[];
904                    int size = 0;
905                    int uids[];
906                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
907                    synchronized (mPackages) {
908                        if (mPendingBroadcasts == null) {
909                            return;
910                        }
911                        size = mPendingBroadcasts.size();
912                        if (size <= 0) {
913                            // Nothing to be done. Just return
914                            return;
915                        }
916                        packages = new String[size];
917                        components = new ArrayList[size];
918                        uids = new int[size];
919                        int i = 0;  // filling out the above arrays
920
921                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
922                            int packageUserId = mPendingBroadcasts.userIdAt(n);
923                            Iterator<Map.Entry<String, ArrayList<String>>> it
924                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
925                                            .entrySet().iterator();
926                            while (it.hasNext() && i < size) {
927                                Map.Entry<String, ArrayList<String>> ent = it.next();
928                                packages[i] = ent.getKey();
929                                components[i] = ent.getValue();
930                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
931                                uids[i] = (ps != null)
932                                        ? UserHandle.getUid(packageUserId, ps.appId)
933                                        : -1;
934                                i++;
935                            }
936                        }
937                        size = i;
938                        mPendingBroadcasts.clear();
939                    }
940                    // Send broadcasts
941                    for (int i = 0; i < size; i++) {
942                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
943                    }
944                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
945                    break;
946                }
947                case START_CLEANING_PACKAGE: {
948                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
949                    final String packageName = (String)msg.obj;
950                    final int userId = msg.arg1;
951                    final boolean andCode = msg.arg2 != 0;
952                    synchronized (mPackages) {
953                        if (userId == UserHandle.USER_ALL) {
954                            int[] users = sUserManager.getUserIds();
955                            for (int user : users) {
956                                mSettings.addPackageToCleanLPw(
957                                        new PackageCleanItem(user, packageName, andCode));
958                            }
959                        } else {
960                            mSettings.addPackageToCleanLPw(
961                                    new PackageCleanItem(userId, packageName, andCode));
962                        }
963                    }
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
965                    startCleaningPackages();
966                } break;
967                case POST_INSTALL: {
968                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
969                    PostInstallData data = mRunningInstalls.get(msg.arg1);
970                    mRunningInstalls.delete(msg.arg1);
971                    boolean deleteOld = false;
972
973                    if (data != null) {
974                        InstallArgs args = data.args;
975                        PackageInstalledInfo res = data.res;
976
977                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
978                            res.removedInfo.sendBroadcast(false, true, false);
979                            Bundle extras = new Bundle(1);
980                            extras.putInt(Intent.EXTRA_UID, res.uid);
981                            // Determine the set of users who are adding this
982                            // package for the first time vs. those who are seeing
983                            // an update.
984                            int[] firstUsers;
985                            int[] updateUsers = new int[0];
986                            if (res.origUsers == null || res.origUsers.length == 0) {
987                                firstUsers = res.newUsers;
988                            } else {
989                                firstUsers = new int[0];
990                                for (int i=0; i<res.newUsers.length; i++) {
991                                    int user = res.newUsers[i];
992                                    boolean isNew = true;
993                                    for (int j=0; j<res.origUsers.length; j++) {
994                                        if (res.origUsers[j] == user) {
995                                            isNew = false;
996                                            break;
997                                        }
998                                    }
999                                    if (isNew) {
1000                                        int[] newFirst = new int[firstUsers.length+1];
1001                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1002                                                firstUsers.length);
1003                                        newFirst[firstUsers.length] = user;
1004                                        firstUsers = newFirst;
1005                                    } else {
1006                                        int[] newUpdate = new int[updateUsers.length+1];
1007                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1008                                                updateUsers.length);
1009                                        newUpdate[updateUsers.length] = user;
1010                                        updateUsers = newUpdate;
1011                                    }
1012                                }
1013                            }
1014                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1015                                    res.pkg.applicationInfo.packageName,
1016                                    extras, null, null, firstUsers);
1017                            final boolean update = res.removedInfo.removedPackage != null;
1018                            if (update) {
1019                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1020                            }
1021                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1022                                    res.pkg.applicationInfo.packageName,
1023                                    extras, null, null, updateUsers);
1024                            if (update) {
1025                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1026                                        res.pkg.applicationInfo.packageName,
1027                                        extras, null, null, updateUsers);
1028                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1029                                        null, null,
1030                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1031
1032                                // treat asec-hosted packages like removable media on upgrade
1033                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1034                                    if (DEBUG_INSTALL) {
1035                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1036                                                + " is ASEC-hosted -> AVAILABLE");
1037                                    }
1038                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1039                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1040                                    pkgList.add(res.pkg.applicationInfo.packageName);
1041                                    sendResourcesChangedBroadcast(true, true,
1042                                            pkgList,uidArray, null);
1043                                }
1044                            }
1045                            if (res.removedInfo.args != null) {
1046                                // Remove the replaced package's older resources safely now
1047                                deleteOld = true;
1048                            }
1049
1050                            // Log current value of "unknown sources" setting
1051                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1052                                getUnknownSourcesSettings());
1053                        }
1054                        // Force a gc to clear up things
1055                        Runtime.getRuntime().gc();
1056                        // We delete after a gc for applications  on sdcard.
1057                        if (deleteOld) {
1058                            synchronized (mInstallLock) {
1059                                res.removedInfo.args.doPostDeleteLI(true);
1060                            }
1061                        }
1062                        if (args.observer != null) {
1063                            try {
1064                                Bundle extras = extrasForInstallResult(res);
1065                                args.observer.onPackageInstalled(res.name, res.returnCode,
1066                                        res.returnMsg, extras);
1067                            } catch (RemoteException e) {
1068                                Slog.i(TAG, "Observer no longer exists.");
1069                            }
1070                        }
1071                    } else {
1072                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1073                    }
1074                } break;
1075                case UPDATED_MEDIA_STATUS: {
1076                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1077                    boolean reportStatus = msg.arg1 == 1;
1078                    boolean doGc = msg.arg2 == 1;
1079                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1080                    if (doGc) {
1081                        // Force a gc to clear up stale containers.
1082                        Runtime.getRuntime().gc();
1083                    }
1084                    if (msg.obj != null) {
1085                        @SuppressWarnings("unchecked")
1086                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1087                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1088                        // Unload containers
1089                        unloadAllContainers(args);
1090                    }
1091                    if (reportStatus) {
1092                        try {
1093                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1094                            PackageHelper.getMountService().finishMediaUpdate();
1095                        } catch (RemoteException e) {
1096                            Log.e(TAG, "MountService not running?");
1097                        }
1098                    }
1099                } break;
1100                case WRITE_SETTINGS: {
1101                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1102                    synchronized (mPackages) {
1103                        removeMessages(WRITE_SETTINGS);
1104                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1105                        mSettings.writeLPr();
1106                        mDirtyUsers.clear();
1107                    }
1108                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1109                } break;
1110                case WRITE_PACKAGE_RESTRICTIONS: {
1111                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1112                    synchronized (mPackages) {
1113                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1114                        for (int userId : mDirtyUsers) {
1115                            mSettings.writePackageRestrictionsLPr(userId);
1116                        }
1117                        mDirtyUsers.clear();
1118                    }
1119                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1120                } break;
1121                case CHECK_PENDING_VERIFICATION: {
1122                    final int verificationId = msg.arg1;
1123                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1124
1125                    if ((state != null) && !state.timeoutExtended()) {
1126                        final InstallArgs args = state.getInstallArgs();
1127                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1128
1129                        Slog.i(TAG, "Verification timed out for " + originUri);
1130                        mPendingVerification.remove(verificationId);
1131
1132                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1133
1134                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1135                            Slog.i(TAG, "Continuing with installation of " + originUri);
1136                            state.setVerifierResponse(Binder.getCallingUid(),
1137                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1138                            broadcastPackageVerified(verificationId, originUri,
1139                                    PackageManager.VERIFICATION_ALLOW,
1140                                    state.getInstallArgs().getUser());
1141                            try {
1142                                ret = args.copyApk(mContainerService, true);
1143                            } catch (RemoteException e) {
1144                                Slog.e(TAG, "Could not contact the ContainerService");
1145                            }
1146                        } else {
1147                            broadcastPackageVerified(verificationId, originUri,
1148                                    PackageManager.VERIFICATION_REJECT,
1149                                    state.getInstallArgs().getUser());
1150                        }
1151
1152                        processPendingInstall(args, ret);
1153                        mHandler.sendEmptyMessage(MCS_UNBIND);
1154                    }
1155                    break;
1156                }
1157                case PACKAGE_VERIFIED: {
1158                    final int verificationId = msg.arg1;
1159
1160                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1161                    if (state == null) {
1162                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1163                        break;
1164                    }
1165
1166                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1167
1168                    state.setVerifierResponse(response.callerUid, response.code);
1169
1170                    if (state.isVerificationComplete()) {
1171                        mPendingVerification.remove(verificationId);
1172
1173                        final InstallArgs args = state.getInstallArgs();
1174                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1175
1176                        int ret;
1177                        if (state.isInstallAllowed()) {
1178                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1179                            broadcastPackageVerified(verificationId, originUri,
1180                                    response.code, state.getInstallArgs().getUser());
1181                            try {
1182                                ret = args.copyApk(mContainerService, true);
1183                            } catch (RemoteException e) {
1184                                Slog.e(TAG, "Could not contact the ContainerService");
1185                            }
1186                        } else {
1187                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1188                        }
1189
1190                        processPendingInstall(args, ret);
1191
1192                        mHandler.sendEmptyMessage(MCS_UNBIND);
1193                    }
1194
1195                    break;
1196                }
1197            }
1198        }
1199    }
1200
1201    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1202        Bundle extras = null;
1203        switch (res.returnCode) {
1204            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1205                extras = new Bundle();
1206                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1207                        res.origPermission);
1208                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1209                        res.origPackage);
1210                break;
1211            }
1212        }
1213        return extras;
1214    }
1215
1216    void scheduleWriteSettingsLocked() {
1217        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1218            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1219        }
1220    }
1221
1222    void scheduleWritePackageRestrictionsLocked(int userId) {
1223        if (!sUserManager.exists(userId)) return;
1224        mDirtyUsers.add(userId);
1225        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1226            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1227        }
1228    }
1229
1230    public static final PackageManagerService main(Context context, Installer installer,
1231            boolean factoryTest, boolean onlyCore) {
1232        PackageManagerService m = new PackageManagerService(context, installer,
1233                factoryTest, onlyCore);
1234        ServiceManager.addService("package", m);
1235        return m;
1236    }
1237
1238    static String[] splitString(String str, char sep) {
1239        int count = 1;
1240        int i = 0;
1241        while ((i=str.indexOf(sep, i)) >= 0) {
1242            count++;
1243            i++;
1244        }
1245
1246        String[] res = new String[count];
1247        i=0;
1248        count = 0;
1249        int lastI=0;
1250        while ((i=str.indexOf(sep, i)) >= 0) {
1251            res[count] = str.substring(lastI, i);
1252            count++;
1253            i++;
1254            lastI = i;
1255        }
1256        res[count] = str.substring(lastI, str.length());
1257        return res;
1258    }
1259
1260    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1261        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1262                Context.DISPLAY_SERVICE);
1263        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1264    }
1265
1266    public PackageManagerService(Context context, Installer installer,
1267            boolean factoryTest, boolean onlyCore) {
1268        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1269                SystemClock.uptimeMillis());
1270
1271        if (mSdkVersion <= 0) {
1272            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1273        }
1274
1275        mContext = context;
1276        mFactoryTest = factoryTest;
1277        mOnlyCore = onlyCore;
1278        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1279        mMetrics = new DisplayMetrics();
1280        mSettings = new Settings(context);
1281        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1282                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1283        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1284                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1285        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1286                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1287        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293
1294        String separateProcesses = SystemProperties.get("debug.separate_processes");
1295        if (separateProcesses != null && separateProcesses.length() > 0) {
1296            if ("*".equals(separateProcesses)) {
1297                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1298                mSeparateProcesses = null;
1299                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1300            } else {
1301                mDefParseFlags = 0;
1302                mSeparateProcesses = separateProcesses.split(",");
1303                Slog.w(TAG, "Running with debug.separate_processes: "
1304                        + separateProcesses);
1305            }
1306        } else {
1307            mDefParseFlags = 0;
1308            mSeparateProcesses = null;
1309        }
1310
1311        mInstaller = installer;
1312
1313        getDefaultDisplayMetrics(context, mMetrics);
1314
1315        SystemConfig systemConfig = SystemConfig.getInstance();
1316        mGlobalGids = systemConfig.getGlobalGids();
1317        mSystemPermissions = systemConfig.getSystemPermissions();
1318        mAvailableFeatures = systemConfig.getAvailableFeatures();
1319
1320        synchronized (mInstallLock) {
1321        // writer
1322        synchronized (mPackages) {
1323            mHandlerThread = new ServiceThread(TAG,
1324                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1325            mHandlerThread.start();
1326            mHandler = new PackageHandler(mHandlerThread.getLooper());
1327            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1328
1329            File dataDir = Environment.getDataDirectory();
1330            mAppDataDir = new File(dataDir, "data");
1331            mAppInstallDir = new File(dataDir, "app");
1332            mAppLib32InstallDir = new File(dataDir, "app-lib");
1333            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1334            mUserAppDataDir = new File(dataDir, "user");
1335            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1336
1337            sUserManager = new UserManagerService(context, this,
1338                    mInstallLock, mPackages);
1339
1340            // Propagate permission configuration in to package manager.
1341            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1342                    = systemConfig.getPermissions();
1343            for (int i=0; i<permConfig.size(); i++) {
1344                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1345                BasePermission bp = mSettings.mPermissions.get(perm.name);
1346                if (bp == null) {
1347                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1348                    mSettings.mPermissions.put(perm.name, bp);
1349                }
1350                if (perm.gids != null) {
1351                    bp.gids = appendInts(bp.gids, perm.gids);
1352                }
1353            }
1354
1355            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1356            for (int i=0; i<libConfig.size(); i++) {
1357                mSharedLibraries.put(libConfig.keyAt(i),
1358                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1359            }
1360
1361            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1362
1363            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1364                    mSdkVersion, mOnlyCore);
1365
1366            String customResolverActivity = Resources.getSystem().getString(
1367                    R.string.config_customResolverActivity);
1368            if (TextUtils.isEmpty(customResolverActivity)) {
1369                customResolverActivity = null;
1370            } else {
1371                mCustomResolverComponentName = ComponentName.unflattenFromString(
1372                        customResolverActivity);
1373            }
1374
1375            long startTime = SystemClock.uptimeMillis();
1376
1377            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1378                    startTime);
1379
1380            // Set flag to monitor and not change apk file paths when
1381            // scanning install directories.
1382            int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1383
1384            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1385
1386            /**
1387             * Add everything in the in the boot class path to the
1388             * list of process files because dexopt will have been run
1389             * if necessary during zygote startup.
1390             */
1391            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1392            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1393
1394            if (bootClassPath != null) {
1395                String[] bootClassPathElements = splitString(bootClassPath, ':');
1396                for (String element : bootClassPathElements) {
1397                    alreadyDexOpted.add(element);
1398                }
1399            } else {
1400                Slog.w(TAG, "No BOOTCLASSPATH found!");
1401            }
1402
1403            if (systemServerClassPath != null) {
1404                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1405                for (String element : systemServerClassPathElements) {
1406                    alreadyDexOpted.add(element);
1407                }
1408            } else {
1409                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1410            }
1411
1412            boolean didDexOptLibraryOrTool = false;
1413
1414            final List<String> allInstructionSets = getAllInstructionSets();
1415            final String[] dexCodeInstructionSets =
1416                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1417
1418            /**
1419             * Ensure all external libraries have had dexopt run on them.
1420             */
1421            if (mSharedLibraries.size() > 0) {
1422                // NOTE: For now, we're compiling these system "shared libraries"
1423                // (and framework jars) into all available architectures. It's possible
1424                // to compile them only when we come across an app that uses them (there's
1425                // already logic for that in scanPackageLI) but that adds some complexity.
1426                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1427                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1428                        final String lib = libEntry.path;
1429                        if (lib == null) {
1430                            continue;
1431                        }
1432
1433                        try {
1434                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1435                                                                                 dexCodeInstructionSet,
1436                                                                                 false);
1437                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1438                                alreadyDexOpted.add(lib);
1439
1440                                // The list of "shared libraries" we have at this point is
1441                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1442                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1443                                } else {
1444                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1445                                }
1446                                didDexOptLibraryOrTool = true;
1447                            }
1448                        } catch (FileNotFoundException e) {
1449                            Slog.w(TAG, "Library not found: " + lib);
1450                        } catch (IOException e) {
1451                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1452                                    + e.getMessage());
1453                        }
1454                    }
1455                }
1456            }
1457
1458            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1459
1460            // Gross hack for now: we know this file doesn't contain any
1461            // code, so don't dexopt it to avoid the resulting log spew.
1462            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1463
1464            // Gross hack for now: we know this file is only part of
1465            // the boot class path for art, so don't dexopt it to
1466            // avoid the resulting log spew.
1467            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1468
1469            /**
1470             * And there are a number of commands implemented in Java, which
1471             * we currently need to do the dexopt on so that they can be
1472             * run from a non-root shell.
1473             */
1474            String[] frameworkFiles = frameworkDir.list();
1475            if (frameworkFiles != null) {
1476                // TODO: We could compile these only for the most preferred ABI. We should
1477                // first double check that the dex files for these commands are not referenced
1478                // by other system apps.
1479                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1480                    for (int i=0; i<frameworkFiles.length; i++) {
1481                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1482                        String path = libPath.getPath();
1483                        // Skip the file if we already did it.
1484                        if (alreadyDexOpted.contains(path)) {
1485                            continue;
1486                        }
1487                        // Skip the file if it is not a type we want to dexopt.
1488                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1489                            continue;
1490                        }
1491                        try {
1492                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1493                                                                                 dexCodeInstructionSet,
1494                                                                                 false);
1495                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1496                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1497                                didDexOptLibraryOrTool = true;
1498                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1499                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1500                                didDexOptLibraryOrTool = true;
1501                            }
1502                        } catch (FileNotFoundException e) {
1503                            Slog.w(TAG, "Jar not found: " + path);
1504                        } catch (IOException e) {
1505                            Slog.w(TAG, "Exception reading jar: " + path, e);
1506                        }
1507                    }
1508                }
1509            }
1510
1511            // Collect vendor overlay packages.
1512            // (Do this before scanning any apps.)
1513            // For security and version matching reason, only consider
1514            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1515            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1516            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1517                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1518
1519            // Find base frameworks (resource packages without code).
1520            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1521                    | PackageParser.PARSE_IS_SYSTEM_DIR
1522                    | PackageParser.PARSE_IS_PRIVILEGED,
1523                    scanFlags | SCAN_NO_DEX, 0);
1524
1525            // Collected privileged system packages.
1526            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1527            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1528                    | PackageParser.PARSE_IS_SYSTEM_DIR
1529                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1530
1531            // Collect ordinary system packages.
1532            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1533            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1534                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1535
1536            // Collect all vendor packages.
1537            File vendorAppDir = new File("/vendor/app");
1538            try {
1539                vendorAppDir = vendorAppDir.getCanonicalFile();
1540            } catch (IOException e) {
1541                // failed to look up canonical path, continue with original one
1542            }
1543            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1544                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1545
1546            // Collect all OEM packages.
1547            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1548            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1549                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1550
1551            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1552            mInstaller.moveFiles();
1553
1554            // Prune any system packages that no longer exist.
1555            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1556            if (!mOnlyCore) {
1557                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1558                while (psit.hasNext()) {
1559                    PackageSetting ps = psit.next();
1560
1561                    /*
1562                     * If this is not a system app, it can't be a
1563                     * disable system app.
1564                     */
1565                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1566                        continue;
1567                    }
1568
1569                    /*
1570                     * If the package is scanned, it's not erased.
1571                     */
1572                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1573                    if (scannedPkg != null) {
1574                        /*
1575                         * If the system app is both scanned and in the
1576                         * disabled packages list, then it must have been
1577                         * added via OTA. Remove it from the currently
1578                         * scanned package so the previously user-installed
1579                         * application can be scanned.
1580                         */
1581                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1582                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1583                                    + "; removing system app");
1584                            removePackageLI(ps, true);
1585                        }
1586
1587                        continue;
1588                    }
1589
1590                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1591                        psit.remove();
1592                        String msg = "System package " + ps.name
1593                                + " no longer exists; wiping its data";
1594                        reportSettingsProblem(Log.WARN, msg);
1595                        removeDataDirsLI(ps.name);
1596                    } else {
1597                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1598                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1599                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1600                        }
1601                    }
1602                }
1603            }
1604
1605            //look for any incomplete package installations
1606            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1607            //clean up list
1608            for(int i = 0; i < deletePkgsList.size(); i++) {
1609                //clean up here
1610                cleanupInstallFailedPackage(deletePkgsList.get(i));
1611            }
1612            //delete tmp files
1613            deleteTempPackageFiles();
1614
1615            // Remove any shared userIDs that have no associated packages
1616            mSettings.pruneSharedUsersLPw();
1617
1618            if (!mOnlyCore) {
1619                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1620                        SystemClock.uptimeMillis());
1621                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1622
1623                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1624                        scanFlags, 0);
1625
1626                /**
1627                 * Remove disable package settings for any updated system
1628                 * apps that were removed via an OTA. If they're not a
1629                 * previously-updated app, remove them completely.
1630                 * Otherwise, just revoke their system-level permissions.
1631                 */
1632                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1633                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1634                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1635
1636                    String msg;
1637                    if (deletedPkg == null) {
1638                        msg = "Updated system package " + deletedAppName
1639                                + " no longer exists; wiping its data";
1640                        removeDataDirsLI(deletedAppName);
1641                    } else {
1642                        msg = "Updated system app + " + deletedAppName
1643                                + " no longer present; removing system privileges for "
1644                                + deletedAppName;
1645
1646                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1647
1648                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1649                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1650                    }
1651                    reportSettingsProblem(Log.WARN, msg);
1652                }
1653            }
1654
1655            // Now that we know all of the shared libraries, update all clients to have
1656            // the correct library paths.
1657            updateAllSharedLibrariesLPw();
1658
1659            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1660                // NOTE: We ignore potential failures here during a system scan (like
1661                // the rest of the commands above) because there's precious little we
1662                // can do about it. A settings error is reported, though.
1663                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1664                        false /* force dexopt */, false /* defer dexopt */);
1665            }
1666
1667            // Now that we know all the packages we are keeping,
1668            // read and update their last usage times.
1669            mPackageUsage.readLP();
1670
1671            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1672                    SystemClock.uptimeMillis());
1673            Slog.i(TAG, "Time to scan packages: "
1674                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1675                    + " seconds");
1676
1677            // If the platform SDK has changed since the last time we booted,
1678            // we need to re-grant app permission to catch any new ones that
1679            // appear.  This is really a hack, and means that apps can in some
1680            // cases get permissions that the user didn't initially explicitly
1681            // allow...  it would be nice to have some better way to handle
1682            // this situation.
1683            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1684                    != mSdkVersion;
1685            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1686                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1687                    + "; regranting permissions for internal storage");
1688            mSettings.mInternalSdkPlatform = mSdkVersion;
1689
1690            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1691                    | (regrantPermissions
1692                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1693                            : 0));
1694
1695            // If this is the first boot, and it is a normal boot, then
1696            // we need to initialize the default preferred apps.
1697            if (!mRestoredSettings && !onlyCore) {
1698                mSettings.readDefaultPreferredAppsLPw(this, 0);
1699            }
1700
1701            // If this is first boot after an OTA, and a normal boot, then
1702            // we need to clear code cache directories.
1703            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1704                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1705                for (String pkgName : mSettings.mPackages.keySet()) {
1706                    deleteCodeCacheDirsLI(pkgName);
1707                }
1708                mSettings.mFingerprint = Build.FINGERPRINT;
1709            }
1710
1711            // All the changes are done during package scanning.
1712            mSettings.updateInternalDatabaseVersion();
1713
1714            // can downgrade to reader
1715            mSettings.writeLPr();
1716
1717            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1718                    SystemClock.uptimeMillis());
1719
1720
1721            mRequiredVerifierPackage = getRequiredVerifierLPr();
1722        } // synchronized (mPackages)
1723        } // synchronized (mInstallLock)
1724
1725        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1726
1727        // Now after opening every single application zip, make sure they
1728        // are all flushed.  Not really needed, but keeps things nice and
1729        // tidy.
1730        Runtime.getRuntime().gc();
1731    }
1732
1733    @Override
1734    public boolean isFirstBoot() {
1735        return !mRestoredSettings;
1736    }
1737
1738    @Override
1739    public boolean isOnlyCoreApps() {
1740        return mOnlyCore;
1741    }
1742
1743    private String getRequiredVerifierLPr() {
1744        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1745        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1746                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1747
1748        String requiredVerifier = null;
1749
1750        final int N = receivers.size();
1751        for (int i = 0; i < N; i++) {
1752            final ResolveInfo info = receivers.get(i);
1753
1754            if (info.activityInfo == null) {
1755                continue;
1756            }
1757
1758            final String packageName = info.activityInfo.packageName;
1759
1760            final PackageSetting ps = mSettings.mPackages.get(packageName);
1761            if (ps == null) {
1762                continue;
1763            }
1764
1765            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1766            if (!gp.grantedPermissions
1767                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1768                continue;
1769            }
1770
1771            if (requiredVerifier != null) {
1772                throw new RuntimeException("There can be only one required verifier");
1773            }
1774
1775            requiredVerifier = packageName;
1776        }
1777
1778        return requiredVerifier;
1779    }
1780
1781    @Override
1782    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1783            throws RemoteException {
1784        try {
1785            return super.onTransact(code, data, reply, flags);
1786        } catch (RuntimeException e) {
1787            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1788                Slog.wtf(TAG, "Package Manager Crash", e);
1789            }
1790            throw e;
1791        }
1792    }
1793
1794    void cleanupInstallFailedPackage(PackageSetting ps) {
1795        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1796        removeDataDirsLI(ps.name);
1797        if (ps.codePath != null) {
1798            if (ps.codePath.isDirectory()) {
1799                FileUtils.deleteContents(ps.codePath);
1800            }
1801            ps.codePath.delete();
1802        }
1803        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1804            if (ps.resourcePath.isDirectory()) {
1805                FileUtils.deleteContents(ps.resourcePath);
1806            }
1807            ps.resourcePath.delete();
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, 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, 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, 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, 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, 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 PackageParser.generateActivityInfo(mResolveActivity, flags,
2166                        new PackageUserState(), userId);
2167            }
2168        }
2169        return null;
2170    }
2171
2172    @Override
2173    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2174            String resolvedType) {
2175        synchronized (mPackages) {
2176            PackageParser.Activity a = mActivities.mActivities.get(component);
2177            if (a == null) {
2178                return false;
2179            }
2180            for (int i=0; i<a.intents.size(); i++) {
2181                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2182                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2183                    return true;
2184                }
2185            }
2186            return false;
2187        }
2188    }
2189
2190    @Override
2191    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2192        if (!sUserManager.exists(userId)) return null;
2193        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2194        synchronized (mPackages) {
2195            PackageParser.Activity a = mReceivers.mActivities.get(component);
2196            if (DEBUG_PACKAGE_INFO) Log.v(
2197                TAG, "getReceiverInfo " + component + ": " + a);
2198            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2199                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2200                if (ps == null) return null;
2201                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2202                        userId);
2203            }
2204        }
2205        return null;
2206    }
2207
2208    @Override
2209    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2210        if (!sUserManager.exists(userId)) return null;
2211        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2212        synchronized (mPackages) {
2213            PackageParser.Service s = mServices.mServices.get(component);
2214            if (DEBUG_PACKAGE_INFO) Log.v(
2215                TAG, "getServiceInfo " + component + ": " + s);
2216            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2217                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2218                if (ps == null) return null;
2219                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2220                        userId);
2221            }
2222        }
2223        return null;
2224    }
2225
2226    @Override
2227    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2228        if (!sUserManager.exists(userId)) return null;
2229        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2230        synchronized (mPackages) {
2231            PackageParser.Provider p = mProviders.mProviders.get(component);
2232            if (DEBUG_PACKAGE_INFO) Log.v(
2233                TAG, "getProviderInfo " + component + ": " + p);
2234            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2235                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2236                if (ps == null) return null;
2237                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2238                        userId);
2239            }
2240        }
2241        return null;
2242    }
2243
2244    @Override
2245    public String[] getSystemSharedLibraryNames() {
2246        Set<String> libSet;
2247        synchronized (mPackages) {
2248            libSet = mSharedLibraries.keySet();
2249            int size = libSet.size();
2250            if (size > 0) {
2251                String[] libs = new String[size];
2252                libSet.toArray(libs);
2253                return libs;
2254            }
2255        }
2256        return null;
2257    }
2258
2259    @Override
2260    public FeatureInfo[] getSystemAvailableFeatures() {
2261        Collection<FeatureInfo> featSet;
2262        synchronized (mPackages) {
2263            featSet = mAvailableFeatures.values();
2264            int size = featSet.size();
2265            if (size > 0) {
2266                FeatureInfo[] features = new FeatureInfo[size+1];
2267                featSet.toArray(features);
2268                FeatureInfo fi = new FeatureInfo();
2269                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2270                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2271                features[size] = fi;
2272                return features;
2273            }
2274        }
2275        return null;
2276    }
2277
2278    @Override
2279    public boolean hasSystemFeature(String name) {
2280        synchronized (mPackages) {
2281            return mAvailableFeatures.containsKey(name);
2282        }
2283    }
2284
2285    private void checkValidCaller(int uid, int userId) {
2286        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2287            return;
2288
2289        throw new SecurityException("Caller uid=" + uid
2290                + " is not privileged to communicate with user=" + userId);
2291    }
2292
2293    @Override
2294    public int checkPermission(String permName, String pkgName) {
2295        synchronized (mPackages) {
2296            PackageParser.Package p = mPackages.get(pkgName);
2297            if (p != null && p.mExtras != null) {
2298                PackageSetting ps = (PackageSetting)p.mExtras;
2299                if (ps.sharedUser != null) {
2300                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2301                        return PackageManager.PERMISSION_GRANTED;
2302                    }
2303                } else if (ps.grantedPermissions.contains(permName)) {
2304                    return PackageManager.PERMISSION_GRANTED;
2305                }
2306            }
2307        }
2308        return PackageManager.PERMISSION_DENIED;
2309    }
2310
2311    @Override
2312    public int checkUidPermission(String permName, int uid) {
2313        synchronized (mPackages) {
2314            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2315            if (obj != null) {
2316                GrantedPermissions gp = (GrantedPermissions)obj;
2317                if (gp.grantedPermissions.contains(permName)) {
2318                    return PackageManager.PERMISSION_GRANTED;
2319                }
2320            } else {
2321                HashSet<String> perms = mSystemPermissions.get(uid);
2322                if (perms != null && perms.contains(permName)) {
2323                    return PackageManager.PERMISSION_GRANTED;
2324                }
2325            }
2326        }
2327        return PackageManager.PERMISSION_DENIED;
2328    }
2329
2330    /**
2331     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2332     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2333     * @param checkShell TODO(yamasani):
2334     * @param message the message to log on security exception
2335     */
2336    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2337            boolean checkShell, String message) {
2338        if (userId < 0) {
2339            throw new IllegalArgumentException("Invalid userId " + userId);
2340        }
2341        if (checkShell) {
2342            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2343        }
2344        if (userId == UserHandle.getUserId(callingUid)) return;
2345        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2346            if (requireFullPermission) {
2347                mContext.enforceCallingOrSelfPermission(
2348                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2349            } else {
2350                try {
2351                    mContext.enforceCallingOrSelfPermission(
2352                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2353                } catch (SecurityException se) {
2354                    mContext.enforceCallingOrSelfPermission(
2355                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2356                }
2357            }
2358        }
2359    }
2360
2361    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2362        if (callingUid == Process.SHELL_UID) {
2363            if (userHandle >= 0
2364                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2365                throw new SecurityException("Shell does not have permission to access user "
2366                        + userHandle);
2367            } else if (userHandle < 0) {
2368                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2369                        + Debug.getCallers(3));
2370            }
2371        }
2372    }
2373
2374    private BasePermission findPermissionTreeLP(String permName) {
2375        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2376            if (permName.startsWith(bp.name) &&
2377                    permName.length() > bp.name.length() &&
2378                    permName.charAt(bp.name.length()) == '.') {
2379                return bp;
2380            }
2381        }
2382        return null;
2383    }
2384
2385    private BasePermission checkPermissionTreeLP(String permName) {
2386        if (permName != null) {
2387            BasePermission bp = findPermissionTreeLP(permName);
2388            if (bp != null) {
2389                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2390                    return bp;
2391                }
2392                throw new SecurityException("Calling uid "
2393                        + Binder.getCallingUid()
2394                        + " is not allowed to add to permission tree "
2395                        + bp.name + " owned by uid " + bp.uid);
2396            }
2397        }
2398        throw new SecurityException("No permission tree found for " + permName);
2399    }
2400
2401    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2402        if (s1 == null) {
2403            return s2 == null;
2404        }
2405        if (s2 == null) {
2406            return false;
2407        }
2408        if (s1.getClass() != s2.getClass()) {
2409            return false;
2410        }
2411        return s1.equals(s2);
2412    }
2413
2414    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2415        if (pi1.icon != pi2.icon) return false;
2416        if (pi1.logo != pi2.logo) return false;
2417        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2418        if (!compareStrings(pi1.name, pi2.name)) return false;
2419        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2420        // We'll take care of setting this one.
2421        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2422        // These are not currently stored in settings.
2423        //if (!compareStrings(pi1.group, pi2.group)) return false;
2424        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2425        //if (pi1.labelRes != pi2.labelRes) return false;
2426        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2427        return true;
2428    }
2429
2430    int permissionInfoFootprint(PermissionInfo info) {
2431        int size = info.name.length();
2432        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2433        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2434        return size;
2435    }
2436
2437    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2438        int size = 0;
2439        for (BasePermission perm : mSettings.mPermissions.values()) {
2440            if (perm.uid == tree.uid) {
2441                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2442            }
2443        }
2444        return size;
2445    }
2446
2447    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2448        // We calculate the max size of permissions defined by this uid and throw
2449        // if that plus the size of 'info' would exceed our stated maximum.
2450        if (tree.uid != Process.SYSTEM_UID) {
2451            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2452            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2453                throw new SecurityException("Permission tree size cap exceeded");
2454            }
2455        }
2456    }
2457
2458    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2459        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2460            throw new SecurityException("Label must be specified in permission");
2461        }
2462        BasePermission tree = checkPermissionTreeLP(info.name);
2463        BasePermission bp = mSettings.mPermissions.get(info.name);
2464        boolean added = bp == null;
2465        boolean changed = true;
2466        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2467        if (added) {
2468            enforcePermissionCapLocked(info, tree);
2469            bp = new BasePermission(info.name, tree.sourcePackage,
2470                    BasePermission.TYPE_DYNAMIC);
2471        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2472            throw new SecurityException(
2473                    "Not allowed to modify non-dynamic permission "
2474                    + info.name);
2475        } else {
2476            if (bp.protectionLevel == fixedLevel
2477                    && bp.perm.owner.equals(tree.perm.owner)
2478                    && bp.uid == tree.uid
2479                    && comparePermissionInfos(bp.perm.info, info)) {
2480                changed = false;
2481            }
2482        }
2483        bp.protectionLevel = fixedLevel;
2484        info = new PermissionInfo(info);
2485        info.protectionLevel = fixedLevel;
2486        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2487        bp.perm.info.packageName = tree.perm.info.packageName;
2488        bp.uid = tree.uid;
2489        if (added) {
2490            mSettings.mPermissions.put(info.name, bp);
2491        }
2492        if (changed) {
2493            if (!async) {
2494                mSettings.writeLPr();
2495            } else {
2496                scheduleWriteSettingsLocked();
2497            }
2498        }
2499        return added;
2500    }
2501
2502    @Override
2503    public boolean addPermission(PermissionInfo info) {
2504        synchronized (mPackages) {
2505            return addPermissionLocked(info, false);
2506        }
2507    }
2508
2509    @Override
2510    public boolean addPermissionAsync(PermissionInfo info) {
2511        synchronized (mPackages) {
2512            return addPermissionLocked(info, true);
2513        }
2514    }
2515
2516    @Override
2517    public void removePermission(String name) {
2518        synchronized (mPackages) {
2519            checkPermissionTreeLP(name);
2520            BasePermission bp = mSettings.mPermissions.get(name);
2521            if (bp != null) {
2522                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2523                    throw new SecurityException(
2524                            "Not allowed to modify non-dynamic permission "
2525                            + name);
2526                }
2527                mSettings.mPermissions.remove(name);
2528                mSettings.writeLPr();
2529            }
2530        }
2531    }
2532
2533    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2534        int index = pkg.requestedPermissions.indexOf(bp.name);
2535        if (index == -1) {
2536            throw new SecurityException("Package " + pkg.packageName
2537                    + " has not requested permission " + bp.name);
2538        }
2539        boolean isNormal =
2540                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2541                        == PermissionInfo.PROTECTION_NORMAL);
2542        boolean isDangerous =
2543                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2544                        == PermissionInfo.PROTECTION_DANGEROUS);
2545        boolean isDevelopment =
2546                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2547
2548        if (!isNormal && !isDangerous && !isDevelopment) {
2549            throw new SecurityException("Permission " + bp.name
2550                    + " is not a changeable permission type");
2551        }
2552
2553        if (isNormal || isDangerous) {
2554            if (pkg.requestedPermissionsRequired.get(index)) {
2555                throw new SecurityException("Can't change " + bp.name
2556                        + ". It is required by the application");
2557            }
2558        }
2559    }
2560
2561    @Override
2562    public void grantPermission(String packageName, String permissionName) {
2563        mContext.enforceCallingOrSelfPermission(
2564                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2565        synchronized (mPackages) {
2566            final PackageParser.Package pkg = mPackages.get(packageName);
2567            if (pkg == null) {
2568                throw new IllegalArgumentException("Unknown package: " + packageName);
2569            }
2570            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2571            if (bp == null) {
2572                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2573            }
2574
2575            checkGrantRevokePermissions(pkg, bp);
2576
2577            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2578            if (ps == null) {
2579                return;
2580            }
2581            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2582            if (gp.grantedPermissions.add(permissionName)) {
2583                if (ps.haveGids) {
2584                    gp.gids = appendInts(gp.gids, bp.gids);
2585                }
2586                mSettings.writeLPr();
2587            }
2588        }
2589    }
2590
2591    @Override
2592    public void revokePermission(String packageName, String permissionName) {
2593        int changedAppId = -1;
2594
2595        synchronized (mPackages) {
2596            final PackageParser.Package pkg = mPackages.get(packageName);
2597            if (pkg == null) {
2598                throw new IllegalArgumentException("Unknown package: " + packageName);
2599            }
2600            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2601                mContext.enforceCallingOrSelfPermission(
2602                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2603            }
2604            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2605            if (bp == null) {
2606                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2607            }
2608
2609            checkGrantRevokePermissions(pkg, bp);
2610
2611            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2612            if (ps == null) {
2613                return;
2614            }
2615            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2616            if (gp.grantedPermissions.remove(permissionName)) {
2617                gp.grantedPermissions.remove(permissionName);
2618                if (ps.haveGids) {
2619                    gp.gids = removeInts(gp.gids, bp.gids);
2620                }
2621                mSettings.writeLPr();
2622                changedAppId = ps.appId;
2623            }
2624        }
2625
2626        if (changedAppId >= 0) {
2627            // We changed the perm on someone, kill its processes.
2628            IActivityManager am = ActivityManagerNative.getDefault();
2629            if (am != null) {
2630                final int callingUserId = UserHandle.getCallingUserId();
2631                final long ident = Binder.clearCallingIdentity();
2632                try {
2633                    //XXX we should only revoke for the calling user's app permissions,
2634                    // but for now we impact all users.
2635                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2636                    //        "revoke " + permissionName);
2637                    int[] users = sUserManager.getUserIds();
2638                    for (int user : users) {
2639                        am.killUid(UserHandle.getUid(user, changedAppId),
2640                                "revoke " + permissionName);
2641                    }
2642                } catch (RemoteException e) {
2643                } finally {
2644                    Binder.restoreCallingIdentity(ident);
2645                }
2646            }
2647        }
2648    }
2649
2650    @Override
2651    public boolean isProtectedBroadcast(String actionName) {
2652        synchronized (mPackages) {
2653            return mProtectedBroadcasts.contains(actionName);
2654        }
2655    }
2656
2657    @Override
2658    public int checkSignatures(String pkg1, String pkg2) {
2659        synchronized (mPackages) {
2660            final PackageParser.Package p1 = mPackages.get(pkg1);
2661            final PackageParser.Package p2 = mPackages.get(pkg2);
2662            if (p1 == null || p1.mExtras == null
2663                    || p2 == null || p2.mExtras == null) {
2664                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2665            }
2666            return compareSignatures(p1.mSignatures, p2.mSignatures);
2667        }
2668    }
2669
2670    @Override
2671    public int checkUidSignatures(int uid1, int uid2) {
2672        // Map to base uids.
2673        uid1 = UserHandle.getAppId(uid1);
2674        uid2 = UserHandle.getAppId(uid2);
2675        // reader
2676        synchronized (mPackages) {
2677            Signature[] s1;
2678            Signature[] s2;
2679            Object obj = mSettings.getUserIdLPr(uid1);
2680            if (obj != null) {
2681                if (obj instanceof SharedUserSetting) {
2682                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2683                } else if (obj instanceof PackageSetting) {
2684                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2685                } else {
2686                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2687                }
2688            } else {
2689                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2690            }
2691            obj = mSettings.getUserIdLPr(uid2);
2692            if (obj != null) {
2693                if (obj instanceof SharedUserSetting) {
2694                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2695                } else if (obj instanceof PackageSetting) {
2696                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2697                } else {
2698                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2699                }
2700            } else {
2701                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2702            }
2703            return compareSignatures(s1, s2);
2704        }
2705    }
2706
2707    /**
2708     * Compares two sets of signatures. Returns:
2709     * <br />
2710     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2711     * <br />
2712     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2713     * <br />
2714     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2715     * <br />
2716     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2717     * <br />
2718     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2719     */
2720    static int compareSignatures(Signature[] s1, Signature[] s2) {
2721        if (s1 == null) {
2722            return s2 == null
2723                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2724                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2725        }
2726
2727        if (s2 == null) {
2728            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2729        }
2730
2731        if (s1.length != s2.length) {
2732            return PackageManager.SIGNATURE_NO_MATCH;
2733        }
2734
2735        // Since both signature sets are of size 1, we can compare without HashSets.
2736        if (s1.length == 1) {
2737            return s1[0].equals(s2[0]) ?
2738                    PackageManager.SIGNATURE_MATCH :
2739                    PackageManager.SIGNATURE_NO_MATCH;
2740        }
2741
2742        HashSet<Signature> set1 = new HashSet<Signature>();
2743        for (Signature sig : s1) {
2744            set1.add(sig);
2745        }
2746        HashSet<Signature> set2 = new HashSet<Signature>();
2747        for (Signature sig : s2) {
2748            set2.add(sig);
2749        }
2750        // Make sure s2 contains all signatures in s1.
2751        if (set1.equals(set2)) {
2752            return PackageManager.SIGNATURE_MATCH;
2753        }
2754        return PackageManager.SIGNATURE_NO_MATCH;
2755    }
2756
2757    /**
2758     * If the database version for this type of package (internal storage or
2759     * external storage) is less than the version where package signatures
2760     * were updated, return true.
2761     */
2762    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2763        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2764                DatabaseVersion.SIGNATURE_END_ENTITY))
2765                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2766                        DatabaseVersion.SIGNATURE_END_ENTITY));
2767    }
2768
2769    /**
2770     * Used for backward compatibility to make sure any packages with
2771     * certificate chains get upgraded to the new style. {@code existingSigs}
2772     * will be in the old format (since they were stored on disk from before the
2773     * system upgrade) and {@code scannedSigs} will be in the newer format.
2774     */
2775    private int compareSignaturesCompat(PackageSignatures existingSigs,
2776            PackageParser.Package scannedPkg) {
2777        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2778            return PackageManager.SIGNATURE_NO_MATCH;
2779        }
2780
2781        HashSet<Signature> existingSet = new HashSet<Signature>();
2782        for (Signature sig : existingSigs.mSignatures) {
2783            existingSet.add(sig);
2784        }
2785        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2786        for (Signature sig : scannedPkg.mSignatures) {
2787            try {
2788                Signature[] chainSignatures = sig.getChainSignatures();
2789                for (Signature chainSig : chainSignatures) {
2790                    scannedCompatSet.add(chainSig);
2791                }
2792            } catch (CertificateEncodingException e) {
2793                scannedCompatSet.add(sig);
2794            }
2795        }
2796        /*
2797         * Make sure the expanded scanned set contains all signatures in the
2798         * existing one.
2799         */
2800        if (scannedCompatSet.equals(existingSet)) {
2801            // Migrate the old signatures to the new scheme.
2802            existingSigs.assignSignatures(scannedPkg.mSignatures);
2803            // The new KeySets will be re-added later in the scanning process.
2804            synchronized (mPackages) {
2805                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2806            }
2807            return PackageManager.SIGNATURE_MATCH;
2808        }
2809        return PackageManager.SIGNATURE_NO_MATCH;
2810    }
2811
2812    @Override
2813    public String[] getPackagesForUid(int uid) {
2814        uid = UserHandle.getAppId(uid);
2815        // reader
2816        synchronized (mPackages) {
2817            Object obj = mSettings.getUserIdLPr(uid);
2818            if (obj instanceof SharedUserSetting) {
2819                final SharedUserSetting sus = (SharedUserSetting) obj;
2820                final int N = sus.packages.size();
2821                final String[] res = new String[N];
2822                final Iterator<PackageSetting> it = sus.packages.iterator();
2823                int i = 0;
2824                while (it.hasNext()) {
2825                    res[i++] = it.next().name;
2826                }
2827                return res;
2828            } else if (obj instanceof PackageSetting) {
2829                final PackageSetting ps = (PackageSetting) obj;
2830                return new String[] { ps.name };
2831            }
2832        }
2833        return null;
2834    }
2835
2836    @Override
2837    public String getNameForUid(int uid) {
2838        // reader
2839        synchronized (mPackages) {
2840            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2841            if (obj instanceof SharedUserSetting) {
2842                final SharedUserSetting sus = (SharedUserSetting) obj;
2843                return sus.name + ":" + sus.userId;
2844            } else if (obj instanceof PackageSetting) {
2845                final PackageSetting ps = (PackageSetting) obj;
2846                return ps.name;
2847            }
2848        }
2849        return null;
2850    }
2851
2852    @Override
2853    public int getUidForSharedUser(String sharedUserName) {
2854        if(sharedUserName == null) {
2855            return -1;
2856        }
2857        // reader
2858        synchronized (mPackages) {
2859            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2860            if (suid == null) {
2861                return -1;
2862            }
2863            return suid.userId;
2864        }
2865    }
2866
2867    @Override
2868    public int getFlagsForUid(int uid) {
2869        synchronized (mPackages) {
2870            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2871            if (obj instanceof SharedUserSetting) {
2872                final SharedUserSetting sus = (SharedUserSetting) obj;
2873                return sus.pkgFlags;
2874            } else if (obj instanceof PackageSetting) {
2875                final PackageSetting ps = (PackageSetting) obj;
2876                return ps.pkgFlags;
2877            }
2878        }
2879        return 0;
2880    }
2881
2882    @Override
2883    public String[] getAppOpPermissionPackages(String permissionName) {
2884        synchronized (mPackages) {
2885            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2886            if (pkgs == null) {
2887                return null;
2888            }
2889            return pkgs.toArray(new String[pkgs.size()]);
2890        }
2891    }
2892
2893    @Override
2894    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2895            int flags, int userId) {
2896        if (!sUserManager.exists(userId)) return null;
2897        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2898        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2899        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2900    }
2901
2902    @Override
2903    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2904            IntentFilter filter, int match, ComponentName activity) {
2905        final int userId = UserHandle.getCallingUserId();
2906        if (DEBUG_PREFERRED) {
2907            Log.v(TAG, "setLastChosenActivity intent=" + intent
2908                + " resolvedType=" + resolvedType
2909                + " flags=" + flags
2910                + " filter=" + filter
2911                + " match=" + match
2912                + " activity=" + activity);
2913            filter.dump(new PrintStreamPrinter(System.out), "    ");
2914        }
2915        intent.setComponent(null);
2916        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2917        // Find any earlier preferred or last chosen entries and nuke them
2918        findPreferredActivity(intent, resolvedType,
2919                flags, query, 0, false, true, false, userId);
2920        // Add the new activity as the last chosen for this filter
2921        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2922                "Setting last chosen");
2923    }
2924
2925    @Override
2926    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2927        final int userId = UserHandle.getCallingUserId();
2928        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2929        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2930        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2931                false, false, false, userId);
2932    }
2933
2934    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2935            int flags, List<ResolveInfo> query, int userId) {
2936        if (query != null) {
2937            final int N = query.size();
2938            if (N == 1) {
2939                return query.get(0);
2940            } else if (N > 1) {
2941                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2942                // If there is more than one activity with the same priority,
2943                // then let the user decide between them.
2944                ResolveInfo r0 = query.get(0);
2945                ResolveInfo r1 = query.get(1);
2946                if (DEBUG_INTENT_MATCHING || debug) {
2947                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2948                            + r1.activityInfo.name + "=" + r1.priority);
2949                }
2950                // If the first activity has a higher priority, or a different
2951                // default, then it is always desireable to pick it.
2952                if (r0.priority != r1.priority
2953                        || r0.preferredOrder != r1.preferredOrder
2954                        || r0.isDefault != r1.isDefault) {
2955                    return query.get(0);
2956                }
2957                // If we have saved a preference for a preferred activity for
2958                // this Intent, use that.
2959                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2960                        flags, query, r0.priority, true, false, debug, userId);
2961                if (ri != null) {
2962                    return ri;
2963                }
2964                if (userId != 0) {
2965                    ri = new ResolveInfo(mResolveInfo);
2966                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2967                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2968                            ri.activityInfo.applicationInfo);
2969                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2970                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2971                    return ri;
2972                }
2973                return mResolveInfo;
2974            }
2975        }
2976        return null;
2977    }
2978
2979    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2980            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2981        final int N = query.size();
2982        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2983                .get(userId);
2984        // Get the list of persistent preferred activities that handle the intent
2985        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2986        List<PersistentPreferredActivity> pprefs = ppir != null
2987                ? ppir.queryIntent(intent, resolvedType,
2988                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2989                : null;
2990        if (pprefs != null && pprefs.size() > 0) {
2991            final int M = pprefs.size();
2992            for (int i=0; i<M; i++) {
2993                final PersistentPreferredActivity ppa = pprefs.get(i);
2994                if (DEBUG_PREFERRED || debug) {
2995                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2996                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2997                            + "\n  component=" + ppa.mComponent);
2998                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2999                }
3000                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3001                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3002                if (DEBUG_PREFERRED || debug) {
3003                    Slog.v(TAG, "Found persistent preferred activity:");
3004                    if (ai != null) {
3005                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3006                    } else {
3007                        Slog.v(TAG, "  null");
3008                    }
3009                }
3010                if (ai == null) {
3011                    // This previously registered persistent preferred activity
3012                    // component is no longer known. Ignore it and do NOT remove it.
3013                    continue;
3014                }
3015                for (int j=0; j<N; j++) {
3016                    final ResolveInfo ri = query.get(j);
3017                    if (!ri.activityInfo.applicationInfo.packageName
3018                            .equals(ai.applicationInfo.packageName)) {
3019                        continue;
3020                    }
3021                    if (!ri.activityInfo.name.equals(ai.name)) {
3022                        continue;
3023                    }
3024                    //  Found a persistent preference that can handle the intent.
3025                    if (DEBUG_PREFERRED || debug) {
3026                        Slog.v(TAG, "Returning persistent preferred activity: " +
3027                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3028                    }
3029                    return ri;
3030                }
3031            }
3032        }
3033        return null;
3034    }
3035
3036    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3037            List<ResolveInfo> query, int priority, boolean always,
3038            boolean removeMatches, boolean debug, int userId) {
3039        if (!sUserManager.exists(userId)) return null;
3040        // writer
3041        synchronized (mPackages) {
3042            if (intent.getSelector() != null) {
3043                intent = intent.getSelector();
3044            }
3045            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3046
3047            // Try to find a matching persistent preferred activity.
3048            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3049                    debug, userId);
3050
3051            // If a persistent preferred activity matched, use it.
3052            if (pri != null) {
3053                return pri;
3054            }
3055
3056            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3057            // Get the list of preferred activities that handle the intent
3058            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3059            List<PreferredActivity> prefs = pir != null
3060                    ? pir.queryIntent(intent, resolvedType,
3061                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3062                    : null;
3063            if (prefs != null && prefs.size() > 0) {
3064                boolean changed = false;
3065                try {
3066                    // First figure out how good the original match set is.
3067                    // We will only allow preferred activities that came
3068                    // from the same match quality.
3069                    int match = 0;
3070
3071                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3072
3073                    final int N = query.size();
3074                    for (int j=0; j<N; j++) {
3075                        final ResolveInfo ri = query.get(j);
3076                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3077                                + ": 0x" + Integer.toHexString(match));
3078                        if (ri.match > match) {
3079                            match = ri.match;
3080                        }
3081                    }
3082
3083                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3084                            + Integer.toHexString(match));
3085
3086                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3087                    final int M = prefs.size();
3088                    for (int i=0; i<M; i++) {
3089                        final PreferredActivity pa = prefs.get(i);
3090                        if (DEBUG_PREFERRED || debug) {
3091                            Slog.v(TAG, "Checking PreferredActivity ds="
3092                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3093                                    + "\n  component=" + pa.mPref.mComponent);
3094                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3095                        }
3096                        if (pa.mPref.mMatch != match) {
3097                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3098                                    + Integer.toHexString(pa.mPref.mMatch));
3099                            continue;
3100                        }
3101                        // If it's not an "always" type preferred activity and that's what we're
3102                        // looking for, skip it.
3103                        if (always && !pa.mPref.mAlways) {
3104                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3105                            continue;
3106                        }
3107                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3108                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3109                        if (DEBUG_PREFERRED || debug) {
3110                            Slog.v(TAG, "Found preferred activity:");
3111                            if (ai != null) {
3112                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3113                            } else {
3114                                Slog.v(TAG, "  null");
3115                            }
3116                        }
3117                        if (ai == null) {
3118                            // This previously registered preferred activity
3119                            // component is no longer known.  Most likely an update
3120                            // to the app was installed and in the new version this
3121                            // component no longer exists.  Clean it up by removing
3122                            // it from the preferred activities list, and skip it.
3123                            Slog.w(TAG, "Removing dangling preferred activity: "
3124                                    + pa.mPref.mComponent);
3125                            pir.removeFilter(pa);
3126                            changed = true;
3127                            continue;
3128                        }
3129                        for (int j=0; j<N; j++) {
3130                            final ResolveInfo ri = query.get(j);
3131                            if (!ri.activityInfo.applicationInfo.packageName
3132                                    .equals(ai.applicationInfo.packageName)) {
3133                                continue;
3134                            }
3135                            if (!ri.activityInfo.name.equals(ai.name)) {
3136                                continue;
3137                            }
3138
3139                            if (removeMatches) {
3140                                pir.removeFilter(pa);
3141                                changed = true;
3142                                if (DEBUG_PREFERRED) {
3143                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3144                                }
3145                                break;
3146                            }
3147
3148                            // Okay we found a previously set preferred or last chosen app.
3149                            // If the result set is different from when this
3150                            // was created, we need to clear it and re-ask the
3151                            // user their preference, if we're looking for an "always" type entry.
3152                            if (always && !pa.mPref.sameSet(query, priority)) {
3153                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3154                                        + intent + " type " + resolvedType);
3155                                if (DEBUG_PREFERRED) {
3156                                    Slog.v(TAG, "Removing preferred activity since set changed "
3157                                            + pa.mPref.mComponent);
3158                                }
3159                                pir.removeFilter(pa);
3160                                // Re-add the filter as a "last chosen" entry (!always)
3161                                PreferredActivity lastChosen = new PreferredActivity(
3162                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3163                                pir.addFilter(lastChosen);
3164                                changed = true;
3165                                return null;
3166                            }
3167
3168                            // Yay! Either the set matched or we're looking for the last chosen
3169                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3170                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3171                            return ri;
3172                        }
3173                    }
3174                } finally {
3175                    if (changed) {
3176                        if (DEBUG_PREFERRED) {
3177                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3178                        }
3179                        mSettings.writePackageRestrictionsLPr(userId);
3180                    }
3181                }
3182            }
3183        }
3184        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3185        return null;
3186    }
3187
3188    /*
3189     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3190     */
3191    @Override
3192    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3193            int targetUserId) {
3194        mContext.enforceCallingOrSelfPermission(
3195                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3196        List<CrossProfileIntentFilter> matches =
3197                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3198        if (matches != null) {
3199            int size = matches.size();
3200            for (int i = 0; i < size; i++) {
3201                if (matches.get(i).getTargetUserId() == targetUserId) return true;
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, 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                List<CrossProfileIntentFilter> matchingFilters =
3245                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3246                // Check for results that need to skip the current profile.
3247                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3248                        resolvedType, flags, userId);
3249                if (resolveInfo != null) {
3250                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3251                    result.add(resolveInfo);
3252                    return result;
3253                }
3254                // Check for cross profile results.
3255                resolveInfo = queryCrossProfileIntents(
3256                        matchingFilters, intent, resolvedType, flags, userId);
3257
3258                // Check for results in the current profile.
3259                List<ResolveInfo> result = mActivities.queryIntent(
3260                        intent, resolvedType, flags, userId);
3261                if (resolveInfo != null) {
3262                    result.add(resolveInfo);
3263                    Collections.sort(result, mResolvePrioritySorter);
3264                }
3265                return result;
3266            }
3267            final PackageParser.Package pkg = mPackages.get(pkgName);
3268            if (pkg != null) {
3269                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3270                        pkg.activities, userId);
3271            }
3272            return new ArrayList<ResolveInfo>();
3273        }
3274    }
3275
3276    private ResolveInfo querySkipCurrentProfileIntents(
3277            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3278            int flags, int sourceUserId) {
3279        if (matchingFilters != null) {
3280            int size = matchingFilters.size();
3281            for (int i = 0; i < size; i ++) {
3282                CrossProfileIntentFilter filter = matchingFilters.get(i);
3283                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3284                    // Checking if there are activities in the target user that can handle the
3285                    // intent.
3286                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3287                            flags, sourceUserId);
3288                    if (resolveInfo != null) {
3289                        return resolveInfo;
3290                    }
3291                }
3292            }
3293        }
3294        return null;
3295    }
3296
3297    // Return matching ResolveInfo if any for skip current profile intent filters.
3298    private ResolveInfo queryCrossProfileIntents(
3299            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3300            int flags, int sourceUserId) {
3301        if (matchingFilters != null) {
3302            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3303            // match the same intent. For performance reasons, it is better not to
3304            // run queryIntent twice for the same userId
3305            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3306            int size = matchingFilters.size();
3307            for (int i = 0; i < size; i++) {
3308                CrossProfileIntentFilter filter = matchingFilters.get(i);
3309                int targetUserId = filter.getTargetUserId();
3310                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3311                        && !alreadyTriedUserIds.get(targetUserId)) {
3312                    // Checking if there are activities in the target user that can handle the
3313                    // intent.
3314                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3315                            flags, sourceUserId);
3316                    if (resolveInfo != null) return resolveInfo;
3317                    alreadyTriedUserIds.put(targetUserId, true);
3318                }
3319            }
3320        }
3321        return null;
3322    }
3323
3324    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3325            String resolvedType, int flags, int sourceUserId) {
3326        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3327                resolvedType, flags, filter.getTargetUserId());
3328        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3329            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3330        }
3331        return null;
3332    }
3333
3334    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3335            int sourceUserId, int targetUserId) {
3336        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3337        String className;
3338        if (targetUserId == UserHandle.USER_OWNER) {
3339            className = FORWARD_INTENT_TO_USER_OWNER;
3340        } else {
3341            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3342        }
3343        ComponentName forwardingActivityComponentName = new ComponentName(
3344                mAndroidApplication.packageName, className);
3345        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3346                sourceUserId);
3347        if (targetUserId == UserHandle.USER_OWNER) {
3348            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3349            forwardingResolveInfo.noResourceId = true;
3350        }
3351        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3352        forwardingResolveInfo.priority = 0;
3353        forwardingResolveInfo.preferredOrder = 0;
3354        forwardingResolveInfo.match = 0;
3355        forwardingResolveInfo.isDefault = true;
3356        forwardingResolveInfo.filter = filter;
3357        forwardingResolveInfo.targetUserId = targetUserId;
3358        return forwardingResolveInfo;
3359    }
3360
3361    @Override
3362    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3363            Intent[] specifics, String[] specificTypes, Intent intent,
3364            String resolvedType, int flags, int userId) {
3365        if (!sUserManager.exists(userId)) return Collections.emptyList();
3366        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3367                false, "query intent activity options");
3368        final String resultsAction = intent.getAction();
3369
3370        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3371                | PackageManager.GET_RESOLVED_FILTER, userId);
3372
3373        if (DEBUG_INTENT_MATCHING) {
3374            Log.v(TAG, "Query " + intent + ": " + results);
3375        }
3376
3377        int specificsPos = 0;
3378        int N;
3379
3380        // todo: note that the algorithm used here is O(N^2).  This
3381        // isn't a problem in our current environment, but if we start running
3382        // into situations where we have more than 5 or 10 matches then this
3383        // should probably be changed to something smarter...
3384
3385        // First we go through and resolve each of the specific items
3386        // that were supplied, taking care of removing any corresponding
3387        // duplicate items in the generic resolve list.
3388        if (specifics != null) {
3389            for (int i=0; i<specifics.length; i++) {
3390                final Intent sintent = specifics[i];
3391                if (sintent == null) {
3392                    continue;
3393                }
3394
3395                if (DEBUG_INTENT_MATCHING) {
3396                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3397                }
3398
3399                String action = sintent.getAction();
3400                if (resultsAction != null && resultsAction.equals(action)) {
3401                    // If this action was explicitly requested, then don't
3402                    // remove things that have it.
3403                    action = null;
3404                }
3405
3406                ResolveInfo ri = null;
3407                ActivityInfo ai = null;
3408
3409                ComponentName comp = sintent.getComponent();
3410                if (comp == null) {
3411                    ri = resolveIntent(
3412                        sintent,
3413                        specificTypes != null ? specificTypes[i] : null,
3414                            flags, userId);
3415                    if (ri == null) {
3416                        continue;
3417                    }
3418                    if (ri == mResolveInfo) {
3419                        // ACK!  Must do something better with this.
3420                    }
3421                    ai = ri.activityInfo;
3422                    comp = new ComponentName(ai.applicationInfo.packageName,
3423                            ai.name);
3424                } else {
3425                    ai = getActivityInfo(comp, flags, userId);
3426                    if (ai == null) {
3427                        continue;
3428                    }
3429                }
3430
3431                // Look for any generic query activities that are duplicates
3432                // of this specific one, and remove them from the results.
3433                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3434                N = results.size();
3435                int j;
3436                for (j=specificsPos; j<N; j++) {
3437                    ResolveInfo sri = results.get(j);
3438                    if ((sri.activityInfo.name.equals(comp.getClassName())
3439                            && sri.activityInfo.applicationInfo.packageName.equals(
3440                                    comp.getPackageName()))
3441                        || (action != null && sri.filter.matchAction(action))) {
3442                        results.remove(j);
3443                        if (DEBUG_INTENT_MATCHING) Log.v(
3444                            TAG, "Removing duplicate item from " + j
3445                            + " due to specific " + specificsPos);
3446                        if (ri == null) {
3447                            ri = sri;
3448                        }
3449                        j--;
3450                        N--;
3451                    }
3452                }
3453
3454                // Add this specific item to its proper place.
3455                if (ri == null) {
3456                    ri = new ResolveInfo();
3457                    ri.activityInfo = ai;
3458                }
3459                results.add(specificsPos, ri);
3460                ri.specificIndex = i;
3461                specificsPos++;
3462            }
3463        }
3464
3465        // Now we go through the remaining generic results and remove any
3466        // duplicate actions that are found here.
3467        N = results.size();
3468        for (int i=specificsPos; i<N-1; i++) {
3469            final ResolveInfo rii = results.get(i);
3470            if (rii.filter == null) {
3471                continue;
3472            }
3473
3474            // Iterate over all of the actions of this result's intent
3475            // filter...  typically this should be just one.
3476            final Iterator<String> it = rii.filter.actionsIterator();
3477            if (it == null) {
3478                continue;
3479            }
3480            while (it.hasNext()) {
3481                final String action = it.next();
3482                if (resultsAction != null && resultsAction.equals(action)) {
3483                    // If this action was explicitly requested, then don't
3484                    // remove things that have it.
3485                    continue;
3486                }
3487                for (int j=i+1; j<N; j++) {
3488                    final ResolveInfo rij = results.get(j);
3489                    if (rij.filter != null && rij.filter.hasAction(action)) {
3490                        results.remove(j);
3491                        if (DEBUG_INTENT_MATCHING) Log.v(
3492                            TAG, "Removing duplicate item from " + j
3493                            + " due to action " + action + " at " + i);
3494                        j--;
3495                        N--;
3496                    }
3497                }
3498            }
3499
3500            // If the caller didn't request filter information, drop it now
3501            // so we don't have to marshall/unmarshall it.
3502            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3503                rii.filter = null;
3504            }
3505        }
3506
3507        // Filter out the caller activity if so requested.
3508        if (caller != null) {
3509            N = results.size();
3510            for (int i=0; i<N; i++) {
3511                ActivityInfo ainfo = results.get(i).activityInfo;
3512                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3513                        && caller.getClassName().equals(ainfo.name)) {
3514                    results.remove(i);
3515                    break;
3516                }
3517            }
3518        }
3519
3520        // If the caller didn't request filter information,
3521        // drop them now so we don't have to
3522        // marshall/unmarshall it.
3523        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3524            N = results.size();
3525            for (int i=0; i<N; i++) {
3526                results.get(i).filter = null;
3527            }
3528        }
3529
3530        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3531        return results;
3532    }
3533
3534    @Override
3535    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3536            int userId) {
3537        if (!sUserManager.exists(userId)) return Collections.emptyList();
3538        ComponentName comp = intent.getComponent();
3539        if (comp == null) {
3540            if (intent.getSelector() != null) {
3541                intent = intent.getSelector();
3542                comp = intent.getComponent();
3543            }
3544        }
3545        if (comp != null) {
3546            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3547            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3548            if (ai != null) {
3549                ResolveInfo ri = new ResolveInfo();
3550                ri.activityInfo = ai;
3551                list.add(ri);
3552            }
3553            return list;
3554        }
3555
3556        // reader
3557        synchronized (mPackages) {
3558            String pkgName = intent.getPackage();
3559            if (pkgName == null) {
3560                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3561            }
3562            final PackageParser.Package pkg = mPackages.get(pkgName);
3563            if (pkg != null) {
3564                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3565                        userId);
3566            }
3567            return null;
3568        }
3569    }
3570
3571    @Override
3572    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3573        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3574        if (!sUserManager.exists(userId)) return null;
3575        if (query != null) {
3576            if (query.size() >= 1) {
3577                // If there is more than one service with the same priority,
3578                // just arbitrarily pick the first one.
3579                return query.get(0);
3580            }
3581        }
3582        return null;
3583    }
3584
3585    @Override
3586    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3587            int userId) {
3588        if (!sUserManager.exists(userId)) return Collections.emptyList();
3589        ComponentName comp = intent.getComponent();
3590        if (comp == null) {
3591            if (intent.getSelector() != null) {
3592                intent = intent.getSelector();
3593                comp = intent.getComponent();
3594            }
3595        }
3596        if (comp != null) {
3597            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3598            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3599            if (si != null) {
3600                final ResolveInfo ri = new ResolveInfo();
3601                ri.serviceInfo = si;
3602                list.add(ri);
3603            }
3604            return list;
3605        }
3606
3607        // reader
3608        synchronized (mPackages) {
3609            String pkgName = intent.getPackage();
3610            if (pkgName == null) {
3611                return mServices.queryIntent(intent, resolvedType, flags, userId);
3612            }
3613            final PackageParser.Package pkg = mPackages.get(pkgName);
3614            if (pkg != null) {
3615                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3616                        userId);
3617            }
3618            return null;
3619        }
3620    }
3621
3622    @Override
3623    public List<ResolveInfo> queryIntentContentProviders(
3624            Intent intent, String resolvedType, int flags, int userId) {
3625        if (!sUserManager.exists(userId)) return Collections.emptyList();
3626        ComponentName comp = intent.getComponent();
3627        if (comp == null) {
3628            if (intent.getSelector() != null) {
3629                intent = intent.getSelector();
3630                comp = intent.getComponent();
3631            }
3632        }
3633        if (comp != null) {
3634            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3635            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3636            if (pi != null) {
3637                final ResolveInfo ri = new ResolveInfo();
3638                ri.providerInfo = pi;
3639                list.add(ri);
3640            }
3641            return list;
3642        }
3643
3644        // reader
3645        synchronized (mPackages) {
3646            String pkgName = intent.getPackage();
3647            if (pkgName == null) {
3648                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3649            }
3650            final PackageParser.Package pkg = mPackages.get(pkgName);
3651            if (pkg != null) {
3652                return mProviders.queryIntentForPackage(
3653                        intent, resolvedType, flags, pkg.providers, userId);
3654            }
3655            return null;
3656        }
3657    }
3658
3659    @Override
3660    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3661        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3662
3663        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3664
3665        // writer
3666        synchronized (mPackages) {
3667            ArrayList<PackageInfo> list;
3668            if (listUninstalled) {
3669                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3670                for (PackageSetting ps : mSettings.mPackages.values()) {
3671                    PackageInfo pi;
3672                    if (ps.pkg != null) {
3673                        pi = generatePackageInfo(ps.pkg, flags, userId);
3674                    } else {
3675                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3676                    }
3677                    if (pi != null) {
3678                        list.add(pi);
3679                    }
3680                }
3681            } else {
3682                list = new ArrayList<PackageInfo>(mPackages.size());
3683                for (PackageParser.Package p : mPackages.values()) {
3684                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3685                    if (pi != null) {
3686                        list.add(pi);
3687                    }
3688                }
3689            }
3690
3691            return new ParceledListSlice<PackageInfo>(list);
3692        }
3693    }
3694
3695    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3696            String[] permissions, boolean[] tmp, int flags, int userId) {
3697        int numMatch = 0;
3698        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3699        for (int i=0; i<permissions.length; i++) {
3700            if (gp.grantedPermissions.contains(permissions[i])) {
3701                tmp[i] = true;
3702                numMatch++;
3703            } else {
3704                tmp[i] = false;
3705            }
3706        }
3707        if (numMatch == 0) {
3708            return;
3709        }
3710        PackageInfo pi;
3711        if (ps.pkg != null) {
3712            pi = generatePackageInfo(ps.pkg, flags, userId);
3713        } else {
3714            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3715        }
3716        // The above might return null in cases of uninstalled apps or install-state
3717        // skew across users/profiles.
3718        if (pi != null) {
3719            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3720                if (numMatch == permissions.length) {
3721                    pi.requestedPermissions = permissions;
3722                } else {
3723                    pi.requestedPermissions = new String[numMatch];
3724                    numMatch = 0;
3725                    for (int i=0; i<permissions.length; i++) {
3726                        if (tmp[i]) {
3727                            pi.requestedPermissions[numMatch] = permissions[i];
3728                            numMatch++;
3729                        }
3730                    }
3731                }
3732            }
3733            list.add(pi);
3734        }
3735    }
3736
3737    @Override
3738    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3739            String[] permissions, int flags, int userId) {
3740        if (!sUserManager.exists(userId)) return null;
3741        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3742
3743        // writer
3744        synchronized (mPackages) {
3745            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3746            boolean[] tmpBools = new boolean[permissions.length];
3747            if (listUninstalled) {
3748                for (PackageSetting ps : mSettings.mPackages.values()) {
3749                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3750                }
3751            } else {
3752                for (PackageParser.Package pkg : mPackages.values()) {
3753                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3754                    if (ps != null) {
3755                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3756                                userId);
3757                    }
3758                }
3759            }
3760
3761            return new ParceledListSlice<PackageInfo>(list);
3762        }
3763    }
3764
3765    @Override
3766    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3767        if (!sUserManager.exists(userId)) return null;
3768        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3769
3770        // writer
3771        synchronized (mPackages) {
3772            ArrayList<ApplicationInfo> list;
3773            if (listUninstalled) {
3774                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3775                for (PackageSetting ps : mSettings.mPackages.values()) {
3776                    ApplicationInfo ai;
3777                    if (ps.pkg != null) {
3778                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3779                                ps.readUserState(userId), userId);
3780                    } else {
3781                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3782                    }
3783                    if (ai != null) {
3784                        list.add(ai);
3785                    }
3786                }
3787            } else {
3788                list = new ArrayList<ApplicationInfo>(mPackages.size());
3789                for (PackageParser.Package p : mPackages.values()) {
3790                    if (p.mExtras != null) {
3791                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3792                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3793                        if (ai != null) {
3794                            list.add(ai);
3795                        }
3796                    }
3797                }
3798            }
3799
3800            return new ParceledListSlice<ApplicationInfo>(list);
3801        }
3802    }
3803
3804    public List<ApplicationInfo> getPersistentApplications(int flags) {
3805        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3806
3807        // reader
3808        synchronized (mPackages) {
3809            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3810            final int userId = UserHandle.getCallingUserId();
3811            while (i.hasNext()) {
3812                final PackageParser.Package p = i.next();
3813                if (p.applicationInfo != null
3814                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3815                        && (!mSafeMode || isSystemApp(p))) {
3816                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3817                    if (ps != null) {
3818                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3819                                ps.readUserState(userId), userId);
3820                        if (ai != null) {
3821                            finalList.add(ai);
3822                        }
3823                    }
3824                }
3825            }
3826        }
3827
3828        return finalList;
3829    }
3830
3831    @Override
3832    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3833        if (!sUserManager.exists(userId)) return null;
3834        // reader
3835        synchronized (mPackages) {
3836            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3837            PackageSetting ps = provider != null
3838                    ? mSettings.mPackages.get(provider.owner.packageName)
3839                    : null;
3840            return ps != null
3841                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3842                    && (!mSafeMode || (provider.info.applicationInfo.flags
3843                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3844                    ? PackageParser.generateProviderInfo(provider, flags,
3845                            ps.readUserState(userId), userId)
3846                    : null;
3847        }
3848    }
3849
3850    /**
3851     * @deprecated
3852     */
3853    @Deprecated
3854    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3855        // reader
3856        synchronized (mPackages) {
3857            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3858                    .entrySet().iterator();
3859            final int userId = UserHandle.getCallingUserId();
3860            while (i.hasNext()) {
3861                Map.Entry<String, PackageParser.Provider> entry = i.next();
3862                PackageParser.Provider p = entry.getValue();
3863                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3864
3865                if (ps != null && p.syncable
3866                        && (!mSafeMode || (p.info.applicationInfo.flags
3867                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3868                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3869                            ps.readUserState(userId), userId);
3870                    if (info != null) {
3871                        outNames.add(entry.getKey());
3872                        outInfo.add(info);
3873                    }
3874                }
3875            }
3876        }
3877    }
3878
3879    @Override
3880    public List<ProviderInfo> queryContentProviders(String processName,
3881            int uid, int flags) {
3882        ArrayList<ProviderInfo> finalList = null;
3883        // reader
3884        synchronized (mPackages) {
3885            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3886            final int userId = processName != null ?
3887                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3888            while (i.hasNext()) {
3889                final PackageParser.Provider p = i.next();
3890                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3891                if (ps != null && p.info.authority != null
3892                        && (processName == null
3893                                || (p.info.processName.equals(processName)
3894                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3895                        && mSettings.isEnabledLPr(p.info, flags, userId)
3896                        && (!mSafeMode
3897                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3898                    if (finalList == null) {
3899                        finalList = new ArrayList<ProviderInfo>(3);
3900                    }
3901                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3902                            ps.readUserState(userId), userId);
3903                    if (info != null) {
3904                        finalList.add(info);
3905                    }
3906                }
3907            }
3908        }
3909
3910        if (finalList != null) {
3911            Collections.sort(finalList, mProviderInitOrderSorter);
3912        }
3913
3914        return finalList;
3915    }
3916
3917    @Override
3918    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3919            int flags) {
3920        // reader
3921        synchronized (mPackages) {
3922            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3923            return PackageParser.generateInstrumentationInfo(i, flags);
3924        }
3925    }
3926
3927    @Override
3928    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3929            int flags) {
3930        ArrayList<InstrumentationInfo> finalList =
3931            new ArrayList<InstrumentationInfo>();
3932
3933        // reader
3934        synchronized (mPackages) {
3935            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3936            while (i.hasNext()) {
3937                final PackageParser.Instrumentation p = i.next();
3938                if (targetPackage == null
3939                        || targetPackage.equals(p.info.targetPackage)) {
3940                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3941                            flags);
3942                    if (ii != null) {
3943                        finalList.add(ii);
3944                    }
3945                }
3946            }
3947        }
3948
3949        return finalList;
3950    }
3951
3952    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3953        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3954        if (overlays == null) {
3955            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3956            return;
3957        }
3958        for (PackageParser.Package opkg : overlays.values()) {
3959            // Not much to do if idmap fails: we already logged the error
3960            // and we certainly don't want to abort installation of pkg simply
3961            // because an overlay didn't fit properly. For these reasons,
3962            // ignore the return value of createIdmapForPackagePairLI.
3963            createIdmapForPackagePairLI(pkg, opkg);
3964        }
3965    }
3966
3967    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3968            PackageParser.Package opkg) {
3969        if (!opkg.mTrustedOverlay) {
3970            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
3971                    opkg.baseCodePath + ": overlay not trusted");
3972            return false;
3973        }
3974        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3975        if (overlaySet == null) {
3976            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
3977                    opkg.baseCodePath + " but target package has no known overlays");
3978            return false;
3979        }
3980        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3981        // TODO: generate idmap for split APKs
3982        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
3983            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
3984                    + opkg.baseCodePath);
3985            return false;
3986        }
3987        PackageParser.Package[] overlayArray =
3988            overlaySet.values().toArray(new PackageParser.Package[0]);
3989        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3990            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3991                return p1.mOverlayPriority - p2.mOverlayPriority;
3992            }
3993        };
3994        Arrays.sort(overlayArray, cmp);
3995
3996        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3997        int i = 0;
3998        for (PackageParser.Package p : overlayArray) {
3999            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4000        }
4001        return true;
4002    }
4003
4004    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4005        final File[] files = dir.listFiles();
4006        if (ArrayUtils.isEmpty(files)) {
4007            Log.d(TAG, "No files in app dir " + dir);
4008            return;
4009        }
4010
4011        if (DEBUG_PACKAGE_SCANNING) {
4012            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4013                    + " flags=0x" + Integer.toHexString(parseFlags));
4014        }
4015
4016        for (File file : files) {
4017            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4018                    && !PackageInstallerService.isStageName(file.getName());
4019            if (!isPackage) {
4020                // Ignore entries which are not packages
4021                continue;
4022            }
4023            try {
4024                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4025                        scanFlags, currentTime, null);
4026            } catch (PackageManagerException e) {
4027                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4028
4029                // Delete invalid userdata apps
4030                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4031                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4032                    Slog.w(TAG, "Deleting invalid package at " + file);
4033                    if (file.isDirectory()) {
4034                        FileUtils.deleteContents(file);
4035                    }
4036                    file.delete();
4037                }
4038            }
4039        }
4040    }
4041
4042    private static File getSettingsProblemFile() {
4043        File dataDir = Environment.getDataDirectory();
4044        File systemDir = new File(dataDir, "system");
4045        File fname = new File(systemDir, "uiderrors.txt");
4046        return fname;
4047    }
4048
4049    static void reportSettingsProblem(int priority, String msg) {
4050        try {
4051            File fname = getSettingsProblemFile();
4052            FileOutputStream out = new FileOutputStream(fname, true);
4053            PrintWriter pw = new FastPrintWriter(out);
4054            SimpleDateFormat formatter = new SimpleDateFormat();
4055            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4056            pw.println(dateString + ": " + msg);
4057            pw.close();
4058            FileUtils.setPermissions(
4059                    fname.toString(),
4060                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4061                    -1, -1);
4062        } catch (java.io.IOException e) {
4063        }
4064        Slog.println(priority, TAG, msg);
4065    }
4066
4067    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4068            PackageParser.Package pkg, File srcFile, int parseFlags)
4069            throws PackageManagerException {
4070        if (ps != null
4071                && ps.codePath.equals(srcFile)
4072                && ps.timeStamp == srcFile.lastModified()
4073                && !isCompatSignatureUpdateNeeded(pkg)) {
4074            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4075            if (ps.signatures.mSignatures != null
4076                    && ps.signatures.mSignatures.length != 0
4077                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4078                // Optimization: reuse the existing cached certificates
4079                // if the package appears to be unchanged.
4080                pkg.mSignatures = ps.signatures.mSignatures;
4081                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4082                synchronized (mPackages) {
4083                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4084                }
4085                return;
4086            }
4087
4088            Slog.w(TAG, "PackageSetting for " + ps.name
4089                    + " is missing signatures.  Collecting certs again to recover them.");
4090        } else {
4091            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4092        }
4093
4094        try {
4095            pp.collectCertificates(pkg, parseFlags);
4096            pp.collectManifestDigest(pkg);
4097        } catch (PackageParserException e) {
4098            throw PackageManagerException.from(e);
4099        }
4100    }
4101
4102    /*
4103     *  Scan a package and return the newly parsed package.
4104     *  Returns null in case of errors and the error code is stored in mLastScanError
4105     */
4106    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4107            long currentTime, UserHandle user) throws PackageManagerException {
4108        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4109        parseFlags |= mDefParseFlags;
4110        PackageParser pp = new PackageParser();
4111        pp.setSeparateProcesses(mSeparateProcesses);
4112        pp.setOnlyCoreApps(mOnlyCore);
4113        pp.setDisplayMetrics(mMetrics);
4114
4115        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4116            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4117        }
4118
4119        final PackageParser.Package pkg;
4120        try {
4121            pkg = pp.parsePackage(scanFile, parseFlags);
4122        } catch (PackageParserException e) {
4123            throw PackageManagerException.from(e);
4124        }
4125
4126        PackageSetting ps = null;
4127        PackageSetting updatedPkg;
4128        // reader
4129        synchronized (mPackages) {
4130            // Look to see if we already know about this package.
4131            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4132            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4133                // This package has been renamed to its original name.  Let's
4134                // use that.
4135                ps = mSettings.peekPackageLPr(oldName);
4136            }
4137            // If there was no original package, see one for the real package name.
4138            if (ps == null) {
4139                ps = mSettings.peekPackageLPr(pkg.packageName);
4140            }
4141            // Check to see if this package could be hiding/updating a system
4142            // package.  Must look for it either under the original or real
4143            // package name depending on our state.
4144            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4145            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4146        }
4147        boolean updatedPkgBetter = false;
4148        // First check if this is a system package that may involve an update
4149        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4150            if (ps != null && !ps.codePath.equals(scanFile)) {
4151                // The path has changed from what was last scanned...  check the
4152                // version of the new path against what we have stored to determine
4153                // what to do.
4154                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4155                if (pkg.mVersionCode < ps.versionCode) {
4156                    // The system package has been updated and the code path does not match
4157                    // Ignore entry. Skip it.
4158                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4159                            + " ignored: updated version " + ps.versionCode
4160                            + " better than this " + pkg.mVersionCode);
4161                    if (!updatedPkg.codePath.equals(scanFile)) {
4162                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4163                                + ps.name + " changing from " + updatedPkg.codePathString
4164                                + " to " + scanFile);
4165                        updatedPkg.codePath = scanFile;
4166                        updatedPkg.codePathString = scanFile.toString();
4167                        // This is the point at which we know that the system-disk APK
4168                        // for this package has moved during a reboot (e.g. due to an OTA),
4169                        // so we need to reevaluate it for privilege policy.
4170                        if (locationIsPrivileged(scanFile)) {
4171                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4172                        }
4173                    }
4174                    updatedPkg.pkg = pkg;
4175                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4176                } else {
4177                    // The current app on the system partition is better than
4178                    // what we have updated to on the data partition; switch
4179                    // back to the system partition version.
4180                    // At this point, its safely assumed that package installation for
4181                    // apps in system partition will go through. If not there won't be a working
4182                    // version of the app
4183                    // writer
4184                    synchronized (mPackages) {
4185                        // Just remove the loaded entries from package lists.
4186                        mPackages.remove(ps.name);
4187                    }
4188                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4189                            + "reverting from " + ps.codePathString
4190                            + ": new version " + pkg.mVersionCode
4191                            + " better than installed " + ps.versionCode);
4192
4193                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4194                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4195                            getAppDexInstructionSets(ps));
4196                    synchronized (mInstallLock) {
4197                        args.cleanUpResourcesLI();
4198                    }
4199                    synchronized (mPackages) {
4200                        mSettings.enableSystemPackageLPw(ps.name);
4201                    }
4202                    updatedPkgBetter = true;
4203                }
4204            }
4205        }
4206
4207        if (updatedPkg != null) {
4208            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4209            // initially
4210            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4211
4212            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4213            // flag set initially
4214            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4215                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4216            }
4217        }
4218
4219        // Verify certificates against what was last scanned
4220        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4221
4222        /*
4223         * A new system app appeared, but we already had a non-system one of the
4224         * same name installed earlier.
4225         */
4226        boolean shouldHideSystemApp = false;
4227        if (updatedPkg == null && ps != null
4228                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4229            /*
4230             * Check to make sure the signatures match first. If they don't,
4231             * wipe the installed application and its data.
4232             */
4233            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4234                    != PackageManager.SIGNATURE_MATCH) {
4235                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4236                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4237                ps = null;
4238            } else {
4239                /*
4240                 * If the newly-added system app is an older version than the
4241                 * already installed version, hide it. It will be scanned later
4242                 * and re-added like an update.
4243                 */
4244                if (pkg.mVersionCode < ps.versionCode) {
4245                    shouldHideSystemApp = true;
4246                } else {
4247                    /*
4248                     * The newly found system app is a newer version that the
4249                     * one previously installed. Simply remove the
4250                     * already-installed application and replace it with our own
4251                     * while keeping the application data.
4252                     */
4253                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4254                            + ps.codePathString + ": new version " + pkg.mVersionCode
4255                            + " better than installed " + ps.versionCode);
4256                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4257                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4258                            getAppDexInstructionSets(ps));
4259                    synchronized (mInstallLock) {
4260                        args.cleanUpResourcesLI();
4261                    }
4262                }
4263            }
4264        }
4265
4266        // The apk is forward locked (not public) if its code and resources
4267        // are kept in different files. (except for app in either system or
4268        // vendor path).
4269        // TODO grab this value from PackageSettings
4270        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4271            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4272                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4273            }
4274        }
4275
4276        // TODO: extend to support forward-locked splits
4277        String resourcePath = null;
4278        String baseResourcePath = null;
4279        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4280            if (ps != null && ps.resourcePathString != null) {
4281                resourcePath = ps.resourcePathString;
4282                baseResourcePath = ps.resourcePathString;
4283            } else {
4284                // Should not happen at all. Just log an error.
4285                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4286            }
4287        } else {
4288            resourcePath = pkg.codePath;
4289            baseResourcePath = pkg.baseCodePath;
4290        }
4291
4292        // Set application objects path explicitly.
4293        pkg.applicationInfo.setCodePath(pkg.codePath);
4294        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4295        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4296        pkg.applicationInfo.setResourcePath(resourcePath);
4297        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4298        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4299
4300        // Note that we invoke the following method only if we are about to unpack an application
4301        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4302                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4303
4304        /*
4305         * If the system app should be overridden by a previously installed
4306         * data, hide the system app now and let the /data/app scan pick it up
4307         * again.
4308         */
4309        if (shouldHideSystemApp) {
4310            synchronized (mPackages) {
4311                /*
4312                 * We have to grant systems permissions before we hide, because
4313                 * grantPermissions will assume the package update is trying to
4314                 * expand its permissions.
4315                 */
4316                grantPermissionsLPw(pkg, true, pkg.packageName);
4317                mSettings.disableSystemPackageLPw(pkg.packageName);
4318            }
4319        }
4320
4321        return scannedPkg;
4322    }
4323
4324    private static String fixProcessName(String defProcessName,
4325            String processName, int uid) {
4326        if (processName == null) {
4327            return defProcessName;
4328        }
4329        return processName;
4330    }
4331
4332    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4333            throws PackageManagerException {
4334        if (pkgSetting.signatures.mSignatures != null) {
4335            // Already existing package. Make sure signatures match
4336            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4337                    == PackageManager.SIGNATURE_MATCH;
4338            if (!match) {
4339                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4340                        == PackageManager.SIGNATURE_MATCH;
4341            }
4342            if (!match) {
4343                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4344                        + pkg.packageName + " signatures do not match the "
4345                        + "previously installed version; ignoring!");
4346            }
4347        }
4348
4349        // Check for shared user signatures
4350        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4351            // Already existing package. Make sure signatures match
4352            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4353                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4354            if (!match) {
4355                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4356                        == PackageManager.SIGNATURE_MATCH;
4357            }
4358            if (!match) {
4359                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4360                        "Package " + pkg.packageName
4361                        + " has no signatures that match those in shared user "
4362                        + pkgSetting.sharedUser.name + "; ignoring!");
4363            }
4364        }
4365    }
4366
4367    /**
4368     * Enforces that only the system UID or root's UID can call a method exposed
4369     * via Binder.
4370     *
4371     * @param message used as message if SecurityException is thrown
4372     * @throws SecurityException if the caller is not system or root
4373     */
4374    private static final void enforceSystemOrRoot(String message) {
4375        final int uid = Binder.getCallingUid();
4376        if (uid != Process.SYSTEM_UID && uid != 0) {
4377            throw new SecurityException(message);
4378        }
4379    }
4380
4381    @Override
4382    public void performBootDexOpt() {
4383        enforceSystemOrRoot("Only the system can request dexopt be performed");
4384
4385        final HashSet<PackageParser.Package> pkgs;
4386        synchronized (mPackages) {
4387            pkgs = mDeferredDexOpt;
4388            mDeferredDexOpt = null;
4389        }
4390
4391        if (pkgs != null) {
4392            // Filter out packages that aren't recently used.
4393            //
4394            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4395            // should do a full dexopt.
4396            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4397                // TODO: add a property to control this?
4398                long dexOptLRUThresholdInMinutes;
4399                if (mLazyDexOpt) {
4400                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4401                } else {
4402                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4403                }
4404                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4405
4406                int total = pkgs.size();
4407                int skipped = 0;
4408                long now = System.currentTimeMillis();
4409                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4410                    PackageParser.Package pkg = i.next();
4411                    long then = pkg.mLastPackageUsageTimeInMills;
4412                    if (then + dexOptLRUThresholdInMills < now) {
4413                        if (DEBUG_DEXOPT) {
4414                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4415                                  ((then == 0) ? "never" : new Date(then)));
4416                        }
4417                        i.remove();
4418                        skipped++;
4419                    }
4420                }
4421                if (DEBUG_DEXOPT) {
4422                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4423                }
4424            }
4425
4426            int i = 0;
4427            for (PackageParser.Package pkg : pkgs) {
4428                i++;
4429                if (DEBUG_DEXOPT) {
4430                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4431                          + ": " + pkg.packageName);
4432                }
4433                if (!isFirstBoot()) {
4434                    try {
4435                        ActivityManagerNative.getDefault().showBootMessage(
4436                                mContext.getResources().getString(
4437                                        R.string.android_upgrading_apk,
4438                                        i, pkgs.size()), true);
4439                    } catch (RemoteException e) {
4440                    }
4441                }
4442                PackageParser.Package p = pkg;
4443                synchronized (mInstallLock) {
4444                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4445                            true /* include dependencies */);
4446                }
4447            }
4448        }
4449    }
4450
4451    @Override
4452    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4453        return performDexOpt(packageName, instructionSet, false);
4454    }
4455
4456    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4457        if (info.primaryCpuAbi == null) {
4458            return getPreferredInstructionSet();
4459        }
4460
4461        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4462    }
4463
4464    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4465        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4466        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4467        if (!dexopt && !updateUsage) {
4468            // We aren't going to dexopt or update usage, so bail early.
4469            return false;
4470        }
4471        PackageParser.Package p;
4472        final String targetInstructionSet;
4473        synchronized (mPackages) {
4474            p = mPackages.get(packageName);
4475            if (p == null) {
4476                return false;
4477            }
4478            if (updateUsage) {
4479                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4480            }
4481            mPackageUsage.write(false);
4482            if (!dexopt) {
4483                // We aren't going to dexopt, so bail early.
4484                return false;
4485            }
4486
4487            targetInstructionSet = instructionSet != null ? instructionSet :
4488                    getPrimaryInstructionSet(p.applicationInfo);
4489            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4490                return false;
4491            }
4492        }
4493
4494        synchronized (mInstallLock) {
4495            final String[] instructionSets = new String[] { targetInstructionSet };
4496            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4497                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4498        }
4499    }
4500
4501    public HashSet<String> getPackagesThatNeedDexOpt() {
4502        HashSet<String> pkgs = null;
4503        synchronized (mPackages) {
4504            for (PackageParser.Package p : mPackages.values()) {
4505                if (DEBUG_DEXOPT) {
4506                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4507                }
4508                if (!p.mDexOptPerformed.isEmpty()) {
4509                    continue;
4510                }
4511                if (pkgs == null) {
4512                    pkgs = new HashSet<String>();
4513                }
4514                pkgs.add(p.packageName);
4515            }
4516        }
4517        return pkgs;
4518    }
4519
4520    public void shutdown() {
4521        mPackageUsage.write(true);
4522    }
4523
4524    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4525             boolean forceDex, boolean defer, HashSet<String> done) {
4526        for (int i=0; i<libs.size(); i++) {
4527            PackageParser.Package libPkg;
4528            String libName;
4529            synchronized (mPackages) {
4530                libName = libs.get(i);
4531                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4532                if (lib != null && lib.apk != null) {
4533                    libPkg = mPackages.get(lib.apk);
4534                } else {
4535                    libPkg = null;
4536                }
4537            }
4538            if (libPkg != null && !done.contains(libName)) {
4539                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4540            }
4541        }
4542    }
4543
4544    static final int DEX_OPT_SKIPPED = 0;
4545    static final int DEX_OPT_PERFORMED = 1;
4546    static final int DEX_OPT_DEFERRED = 2;
4547    static final int DEX_OPT_FAILED = -1;
4548
4549    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4550            boolean forceDex, boolean defer, HashSet<String> done) {
4551        final String[] instructionSets = targetInstructionSets != null ?
4552                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4553
4554        if (done != null) {
4555            done.add(pkg.packageName);
4556            if (pkg.usesLibraries != null) {
4557                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4558            }
4559            if (pkg.usesOptionalLibraries != null) {
4560                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4561            }
4562        }
4563
4564        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4565            return DEX_OPT_SKIPPED;
4566        }
4567
4568        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4569
4570        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4571        boolean performedDexOpt = false;
4572        // There are three basic cases here:
4573        // 1.) we need to dexopt, either because we are forced or it is needed
4574        // 2.) we are defering a needed dexopt
4575        // 3.) we are skipping an unneeded dexopt
4576        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4577        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4578            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4579                continue;
4580            }
4581
4582            for (String path : paths) {
4583                try {
4584                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4585                    // patckage or the one we find does not match the image checksum (i.e. it was
4586                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4587                    // odex file and it matches the checksum of the image but not its base address,
4588                    // meaning we need to move it.
4589                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4590                            pkg.packageName, dexCodeInstructionSet, defer);
4591                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4592                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4593                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4594                                + " vmSafeMode=" + vmSafeMode);
4595                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4596                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4597                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4598
4599                        if (ret < 0) {
4600                            // Don't bother running dexopt again if we failed, it will probably
4601                            // just result in an error again. Also, don't bother dexopting for other
4602                            // paths & ISAs.
4603                            return DEX_OPT_FAILED;
4604                        }
4605
4606                        performedDexOpt = true;
4607                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4608                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4609                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4610                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4611                                pkg.packageName, dexCodeInstructionSet);
4612
4613                        if (ret < 0) {
4614                            // Don't bother running patchoat again if we failed, it will probably
4615                            // just result in an error again. Also, don't bother dexopting for other
4616                            // paths & ISAs.
4617                            return DEX_OPT_FAILED;
4618                        }
4619
4620                        performedDexOpt = true;
4621                    }
4622
4623                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4624                    // paths and instruction sets. We'll deal with them all together when we process
4625                    // our list of deferred dexopts.
4626                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4627                        if (mDeferredDexOpt == null) {
4628                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4629                        }
4630                        mDeferredDexOpt.add(pkg);
4631                        return DEX_OPT_DEFERRED;
4632                    }
4633                } catch (FileNotFoundException e) {
4634                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4635                    return DEX_OPT_FAILED;
4636                } catch (IOException e) {
4637                    Slog.w(TAG, "IOException reading apk: " + path, e);
4638                    return DEX_OPT_FAILED;
4639                } catch (StaleDexCacheError e) {
4640                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4641                    return DEX_OPT_FAILED;
4642                } catch (Exception e) {
4643                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4644                    return DEX_OPT_FAILED;
4645                }
4646            }
4647
4648            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4649            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4650            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4651            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4652            // it.
4653            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4654        }
4655
4656        // If we've gotten here, we're sure that no error occurred and that we haven't
4657        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4658        // we've skipped all of them because they are up to date. In both cases this
4659        // package doesn't need dexopt any longer.
4660        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4661    }
4662
4663    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4664        if (info.primaryCpuAbi != null) {
4665            if (info.secondaryCpuAbi != null) {
4666                return new String[] {
4667                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4668                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4669            } else {
4670                return new String[] {
4671                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4672            }
4673        }
4674
4675        return new String[] { getPreferredInstructionSet() };
4676    }
4677
4678    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4679        if (ps.primaryCpuAbiString != null) {
4680            if (ps.secondaryCpuAbiString != null) {
4681                return new String[] {
4682                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4683                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4684            } else {
4685                return new String[] {
4686                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4687            }
4688        }
4689
4690        return new String[] { getPreferredInstructionSet() };
4691    }
4692
4693    private static String getPreferredInstructionSet() {
4694        if (sPreferredInstructionSet == null) {
4695            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4696        }
4697
4698        return sPreferredInstructionSet;
4699    }
4700
4701    private static List<String> getAllInstructionSets() {
4702        final String[] allAbis = Build.SUPPORTED_ABIS;
4703        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4704
4705        for (String abi : allAbis) {
4706            final String instructionSet = VMRuntime.getInstructionSet(abi);
4707            if (!allInstructionSets.contains(instructionSet)) {
4708                allInstructionSets.add(instructionSet);
4709            }
4710        }
4711
4712        return allInstructionSets;
4713    }
4714
4715    /**
4716     * Returns the instruction set that should be used to compile dex code. In the presence of
4717     * a native bridge this might be different than the one shared libraries use.
4718     */
4719    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4720        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4721        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4722    }
4723
4724    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4725        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4726        for (String instructionSet : instructionSets) {
4727            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4728        }
4729        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4730    }
4731
4732    @Override
4733    public void forceDexOpt(String packageName) {
4734        enforceSystemOrRoot("forceDexOpt");
4735
4736        PackageParser.Package pkg;
4737        synchronized (mPackages) {
4738            pkg = mPackages.get(packageName);
4739            if (pkg == null) {
4740                throw new IllegalArgumentException("Missing package: " + packageName);
4741            }
4742        }
4743
4744        synchronized (mInstallLock) {
4745            final String[] instructionSets = new String[] {
4746                    getPrimaryInstructionSet(pkg.applicationInfo) };
4747            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4748            if (res != DEX_OPT_PERFORMED) {
4749                throw new IllegalStateException("Failed to dexopt: " + res);
4750            }
4751        }
4752    }
4753
4754    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4755                                boolean forceDex, boolean defer, boolean inclDependencies) {
4756        HashSet<String> done;
4757        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4758            done = new HashSet<String>();
4759            done.add(pkg.packageName);
4760        } else {
4761            done = null;
4762        }
4763        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4764    }
4765
4766    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4767        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4768            Slog.w(TAG, "Unable to update from " + oldPkg.name
4769                    + " to " + newPkg.packageName
4770                    + ": old package not in system partition");
4771            return false;
4772        } else if (mPackages.get(oldPkg.name) != null) {
4773            Slog.w(TAG, "Unable to update from " + oldPkg.name
4774                    + " to " + newPkg.packageName
4775                    + ": old package still exists");
4776            return false;
4777        }
4778        return true;
4779    }
4780
4781    File getDataPathForUser(int userId) {
4782        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4783    }
4784
4785    private File getDataPathForPackage(String packageName, int userId) {
4786        /*
4787         * Until we fully support multiple users, return the directory we
4788         * previously would have. The PackageManagerTests will need to be
4789         * revised when this is changed back..
4790         */
4791        if (userId == 0) {
4792            return new File(mAppDataDir, packageName);
4793        } else {
4794            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4795                + File.separator + packageName);
4796        }
4797    }
4798
4799    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4800        int[] users = sUserManager.getUserIds();
4801        int res = mInstaller.install(packageName, uid, uid, seinfo);
4802        if (res < 0) {
4803            return res;
4804        }
4805        for (int user : users) {
4806            if (user != 0) {
4807                res = mInstaller.createUserData(packageName,
4808                        UserHandle.getUid(user, uid), user, seinfo);
4809                if (res < 0) {
4810                    return res;
4811                }
4812            }
4813        }
4814        return res;
4815    }
4816
4817    private int removeDataDirsLI(String packageName) {
4818        int[] users = sUserManager.getUserIds();
4819        int res = 0;
4820        for (int user : users) {
4821            int resInner = mInstaller.remove(packageName, user);
4822            if (resInner < 0) {
4823                res = resInner;
4824            }
4825        }
4826
4827        return res;
4828    }
4829
4830    private int deleteCodeCacheDirsLI(String packageName) {
4831        int[] users = sUserManager.getUserIds();
4832        int res = 0;
4833        for (int user : users) {
4834            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4835            if (resInner < 0) {
4836                res = resInner;
4837            }
4838        }
4839        return res;
4840    }
4841
4842    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4843            PackageParser.Package changingLib) {
4844        if (file.path != null) {
4845            usesLibraryFiles.add(file.path);
4846            return;
4847        }
4848        PackageParser.Package p = mPackages.get(file.apk);
4849        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4850            // If we are doing this while in the middle of updating a library apk,
4851            // then we need to make sure to use that new apk for determining the
4852            // dependencies here.  (We haven't yet finished committing the new apk
4853            // to the package manager state.)
4854            if (p == null || p.packageName.equals(changingLib.packageName)) {
4855                p = changingLib;
4856            }
4857        }
4858        if (p != null) {
4859            usesLibraryFiles.addAll(p.getAllCodePaths());
4860        }
4861    }
4862
4863    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4864            PackageParser.Package changingLib) throws PackageManagerException {
4865        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4866            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4867            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4868            for (int i=0; i<N; i++) {
4869                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4870                if (file == null) {
4871                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4872                            "Package " + pkg.packageName + " requires unavailable shared library "
4873                            + pkg.usesLibraries.get(i) + "; failing!");
4874                }
4875                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4876            }
4877            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4878            for (int i=0; i<N; i++) {
4879                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4880                if (file == null) {
4881                    Slog.w(TAG, "Package " + pkg.packageName
4882                            + " desires unavailable shared library "
4883                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4884                } else {
4885                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4886                }
4887            }
4888            N = usesLibraryFiles.size();
4889            if (N > 0) {
4890                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4891            } else {
4892                pkg.usesLibraryFiles = null;
4893            }
4894        }
4895    }
4896
4897    private static boolean hasString(List<String> list, List<String> which) {
4898        if (list == null) {
4899            return false;
4900        }
4901        for (int i=list.size()-1; i>=0; i--) {
4902            for (int j=which.size()-1; j>=0; j--) {
4903                if (which.get(j).equals(list.get(i))) {
4904                    return true;
4905                }
4906            }
4907        }
4908        return false;
4909    }
4910
4911    private void updateAllSharedLibrariesLPw() {
4912        for (PackageParser.Package pkg : mPackages.values()) {
4913            try {
4914                updateSharedLibrariesLPw(pkg, null);
4915            } catch (PackageManagerException e) {
4916                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4917            }
4918        }
4919    }
4920
4921    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4922            PackageParser.Package changingPkg) {
4923        ArrayList<PackageParser.Package> res = null;
4924        for (PackageParser.Package pkg : mPackages.values()) {
4925            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4926                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4927                if (res == null) {
4928                    res = new ArrayList<PackageParser.Package>();
4929                }
4930                res.add(pkg);
4931                try {
4932                    updateSharedLibrariesLPw(pkg, changingPkg);
4933                } catch (PackageManagerException e) {
4934                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4935                }
4936            }
4937        }
4938        return res;
4939    }
4940
4941    /**
4942     * Derive the value of the {@code cpuAbiOverride} based on the provided
4943     * value and an optional stored value from the package settings.
4944     */
4945    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
4946        String cpuAbiOverride = null;
4947
4948        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
4949            cpuAbiOverride = null;
4950        } else if (abiOverride != null) {
4951            cpuAbiOverride = abiOverride;
4952        } else if (settings != null) {
4953            cpuAbiOverride = settings.cpuAbiOverrideString;
4954        }
4955
4956        return cpuAbiOverride;
4957    }
4958
4959    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4960            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4961        boolean success = false;
4962        try {
4963            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
4964                    currentTime, user);
4965            success = true;
4966            return res;
4967        } finally {
4968            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4969                removeDataDirsLI(pkg.packageName);
4970            }
4971        }
4972    }
4973
4974    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
4975            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4976        final File scanFile = new File(pkg.codePath);
4977        if (pkg.applicationInfo.getCodePath() == null ||
4978                pkg.applicationInfo.getResourcePath() == null) {
4979            // Bail out. The resource and code paths haven't been set.
4980            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4981                    "Code and resource paths haven't been set correctly");
4982        }
4983
4984        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4985            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4986        }
4987
4988        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4989            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4990        }
4991
4992        if (mCustomResolverComponentName != null &&
4993                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4994            setUpCustomResolverActivity(pkg);
4995        }
4996
4997        if (pkg.packageName.equals("android")) {
4998            synchronized (mPackages) {
4999                if (mAndroidApplication != null) {
5000                    Slog.w(TAG, "*************************************************");
5001                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5002                    Slog.w(TAG, " file=" + scanFile);
5003                    Slog.w(TAG, "*************************************************");
5004                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5005                            "Core android package being redefined.  Skipping.");
5006                }
5007
5008                // Set up information for our fall-back user intent resolution activity.
5009                mPlatformPackage = pkg;
5010                pkg.mVersionCode = mSdkVersion;
5011                mAndroidApplication = pkg.applicationInfo;
5012
5013                if (!mResolverReplaced) {
5014                    mResolveActivity.applicationInfo = mAndroidApplication;
5015                    mResolveActivity.name = ResolverActivity.class.getName();
5016                    mResolveActivity.packageName = mAndroidApplication.packageName;
5017                    mResolveActivity.processName = "system:ui";
5018                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5019                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5020                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5021                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5022                    mResolveActivity.exported = true;
5023                    mResolveActivity.enabled = true;
5024                    mResolveInfo.activityInfo = mResolveActivity;
5025                    mResolveInfo.priority = 0;
5026                    mResolveInfo.preferredOrder = 0;
5027                    mResolveInfo.match = 0;
5028                    mResolveComponentName = new ComponentName(
5029                            mAndroidApplication.packageName, mResolveActivity.name);
5030                }
5031            }
5032        }
5033
5034        if (DEBUG_PACKAGE_SCANNING) {
5035            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5036                Log.d(TAG, "Scanning package " + pkg.packageName);
5037        }
5038
5039        if (mPackages.containsKey(pkg.packageName)
5040                || mSharedLibraries.containsKey(pkg.packageName)) {
5041            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5042                    "Application package " + pkg.packageName
5043                    + " already installed.  Skipping duplicate.");
5044        }
5045
5046        // Initialize package source and resource directories
5047        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5048        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5049
5050        SharedUserSetting suid = null;
5051        PackageSetting pkgSetting = null;
5052
5053        if (!isSystemApp(pkg)) {
5054            // Only system apps can use these features.
5055            pkg.mOriginalPackages = null;
5056            pkg.mRealPackage = null;
5057            pkg.mAdoptPermissions = null;
5058        }
5059
5060        // writer
5061        synchronized (mPackages) {
5062            if (pkg.mSharedUserId != null) {
5063                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5064                if (suid == null) {
5065                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5066                            "Creating application package " + pkg.packageName
5067                            + " for shared user failed");
5068                }
5069                if (DEBUG_PACKAGE_SCANNING) {
5070                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5071                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5072                                + "): packages=" + suid.packages);
5073                }
5074            }
5075
5076            // Check if we are renaming from an original package name.
5077            PackageSetting origPackage = null;
5078            String realName = null;
5079            if (pkg.mOriginalPackages != null) {
5080                // This package may need to be renamed to a previously
5081                // installed name.  Let's check on that...
5082                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5083                if (pkg.mOriginalPackages.contains(renamed)) {
5084                    // This package had originally been installed as the
5085                    // original name, and we have already taken care of
5086                    // transitioning to the new one.  Just update the new
5087                    // one to continue using the old name.
5088                    realName = pkg.mRealPackage;
5089                    if (!pkg.packageName.equals(renamed)) {
5090                        // Callers into this function may have already taken
5091                        // care of renaming the package; only do it here if
5092                        // it is not already done.
5093                        pkg.setPackageName(renamed);
5094                    }
5095
5096                } else {
5097                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5098                        if ((origPackage = mSettings.peekPackageLPr(
5099                                pkg.mOriginalPackages.get(i))) != null) {
5100                            // We do have the package already installed under its
5101                            // original name...  should we use it?
5102                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5103                                // New package is not compatible with original.
5104                                origPackage = null;
5105                                continue;
5106                            } else if (origPackage.sharedUser != null) {
5107                                // Make sure uid is compatible between packages.
5108                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5109                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5110                                            + " to " + pkg.packageName + ": old uid "
5111                                            + origPackage.sharedUser.name
5112                                            + " differs from " + pkg.mSharedUserId);
5113                                    origPackage = null;
5114                                    continue;
5115                                }
5116                            } else {
5117                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5118                                        + pkg.packageName + " to old name " + origPackage.name);
5119                            }
5120                            break;
5121                        }
5122                    }
5123                }
5124            }
5125
5126            if (mTransferedPackages.contains(pkg.packageName)) {
5127                Slog.w(TAG, "Package " + pkg.packageName
5128                        + " was transferred to another, but its .apk remains");
5129            }
5130
5131            // Just create the setting, don't add it yet. For already existing packages
5132            // the PkgSetting exists already and doesn't have to be created.
5133            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5134                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5135                    pkg.applicationInfo.primaryCpuAbi,
5136                    pkg.applicationInfo.secondaryCpuAbi,
5137                    pkg.applicationInfo.flags, user, false);
5138            if (pkgSetting == null) {
5139                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5140                        "Creating application package " + pkg.packageName + " failed");
5141            }
5142
5143            if (pkgSetting.origPackage != null) {
5144                // If we are first transitioning from an original package,
5145                // fix up the new package's name now.  We need to do this after
5146                // looking up the package under its new name, so getPackageLP
5147                // can take care of fiddling things correctly.
5148                pkg.setPackageName(origPackage.name);
5149
5150                // File a report about this.
5151                String msg = "New package " + pkgSetting.realName
5152                        + " renamed to replace old package " + pkgSetting.name;
5153                reportSettingsProblem(Log.WARN, msg);
5154
5155                // Make a note of it.
5156                mTransferedPackages.add(origPackage.name);
5157
5158                // No longer need to retain this.
5159                pkgSetting.origPackage = null;
5160            }
5161
5162            if (realName != null) {
5163                // Make a note of it.
5164                mTransferedPackages.add(pkg.packageName);
5165            }
5166
5167            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5168                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5169            }
5170
5171            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5172                // Check all shared libraries and map to their actual file path.
5173                // We only do this here for apps not on a system dir, because those
5174                // are the only ones that can fail an install due to this.  We
5175                // will take care of the system apps by updating all of their
5176                // library paths after the scan is done.
5177                updateSharedLibrariesLPw(pkg, null);
5178            }
5179
5180            if (mFoundPolicyFile) {
5181                SELinuxMMAC.assignSeinfoValue(pkg);
5182            }
5183
5184            pkg.applicationInfo.uid = pkgSetting.appId;
5185            pkg.mExtras = pkgSetting;
5186            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5187                try {
5188                    verifySignaturesLP(pkgSetting, pkg);
5189                } catch (PackageManagerException e) {
5190                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5191                        throw e;
5192                    }
5193                    // The signature has changed, but this package is in the system
5194                    // image...  let's recover!
5195                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5196                    // However...  if this package is part of a shared user, but it
5197                    // doesn't match the signature of the shared user, let's fail.
5198                    // What this means is that you can't change the signatures
5199                    // associated with an overall shared user, which doesn't seem all
5200                    // that unreasonable.
5201                    if (pkgSetting.sharedUser != null) {
5202                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5203                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5204                            throw new PackageManagerException(
5205                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5206                                            "Signature mismatch for shared user : "
5207                                            + pkgSetting.sharedUser);
5208                        }
5209                    }
5210                    // File a report about this.
5211                    String msg = "System package " + pkg.packageName
5212                        + " signature changed; retaining data.";
5213                    reportSettingsProblem(Log.WARN, msg);
5214                }
5215            } else {
5216                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5217                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5218                            + pkg.packageName + " upgrade keys do not match the "
5219                            + "previously installed version");
5220                } else {
5221                    // signatures may have changed as result of upgrade
5222                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5223                }
5224            }
5225            // Verify that this new package doesn't have any content providers
5226            // that conflict with existing packages.  Only do this if the
5227            // package isn't already installed, since we don't want to break
5228            // things that are installed.
5229            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5230                final int N = pkg.providers.size();
5231                int i;
5232                for (i=0; i<N; i++) {
5233                    PackageParser.Provider p = pkg.providers.get(i);
5234                    if (p.info.authority != null) {
5235                        String names[] = p.info.authority.split(";");
5236                        for (int j = 0; j < names.length; j++) {
5237                            if (mProvidersByAuthority.containsKey(names[j])) {
5238                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5239                                final String otherPackageName =
5240                                        ((other != null && other.getComponentName() != null) ?
5241                                                other.getComponentName().getPackageName() : "?");
5242                                throw new PackageManagerException(
5243                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5244                                                "Can't install because provider name " + names[j]
5245                                                + " (in package " + pkg.applicationInfo.packageName
5246                                                + ") is already used by " + otherPackageName);
5247                            }
5248                        }
5249                    }
5250                }
5251            }
5252
5253            if (pkg.mAdoptPermissions != null) {
5254                // This package wants to adopt ownership of permissions from
5255                // another package.
5256                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5257                    final String origName = pkg.mAdoptPermissions.get(i);
5258                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5259                    if (orig != null) {
5260                        if (verifyPackageUpdateLPr(orig, pkg)) {
5261                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5262                                    + pkg.packageName);
5263                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5264                        }
5265                    }
5266                }
5267            }
5268        }
5269
5270        final String pkgName = pkg.packageName;
5271
5272        final long scanFileTime = scanFile.lastModified();
5273        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5274        pkg.applicationInfo.processName = fixProcessName(
5275                pkg.applicationInfo.packageName,
5276                pkg.applicationInfo.processName,
5277                pkg.applicationInfo.uid);
5278
5279        File dataPath;
5280        if (mPlatformPackage == pkg) {
5281            // The system package is special.
5282            dataPath = new File(Environment.getDataDirectory(), "system");
5283
5284            pkg.applicationInfo.dataDir = dataPath.getPath();
5285
5286        } else {
5287            // This is a normal package, need to make its data directory.
5288            dataPath = getDataPathForPackage(pkg.packageName, 0);
5289
5290            boolean uidError = false;
5291            if (dataPath.exists()) {
5292                int currentUid = 0;
5293                try {
5294                    StructStat stat = Os.stat(dataPath.getPath());
5295                    currentUid = stat.st_uid;
5296                } catch (ErrnoException e) {
5297                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5298                }
5299
5300                // If we have mismatched owners for the data path, we have a problem.
5301                if (currentUid != pkg.applicationInfo.uid) {
5302                    boolean recovered = false;
5303                    if (currentUid == 0) {
5304                        // The directory somehow became owned by root.  Wow.
5305                        // This is probably because the system was stopped while
5306                        // installd was in the middle of messing with its libs
5307                        // directory.  Ask installd to fix that.
5308                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5309                                pkg.applicationInfo.uid);
5310                        if (ret >= 0) {
5311                            recovered = true;
5312                            String msg = "Package " + pkg.packageName
5313                                    + " unexpectedly changed to uid 0; recovered to " +
5314                                    + pkg.applicationInfo.uid;
5315                            reportSettingsProblem(Log.WARN, msg);
5316                        }
5317                    }
5318                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5319                            || (scanFlags&SCAN_BOOTING) != 0)) {
5320                        // If this is a system app, we can at least delete its
5321                        // current data so the application will still work.
5322                        int ret = removeDataDirsLI(pkgName);
5323                        if (ret >= 0) {
5324                            // TODO: Kill the processes first
5325                            // Old data gone!
5326                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5327                                    ? "System package " : "Third party package ";
5328                            String msg = prefix + pkg.packageName
5329                                    + " has changed from uid: "
5330                                    + currentUid + " to "
5331                                    + pkg.applicationInfo.uid + "; old data erased";
5332                            reportSettingsProblem(Log.WARN, msg);
5333                            recovered = true;
5334
5335                            // And now re-install the app.
5336                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5337                                                   pkg.applicationInfo.seinfo);
5338                            if (ret == -1) {
5339                                // Ack should not happen!
5340                                msg = prefix + pkg.packageName
5341                                        + " could not have data directory re-created after delete.";
5342                                reportSettingsProblem(Log.WARN, msg);
5343                                throw new PackageManagerException(
5344                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5345                            }
5346                        }
5347                        if (!recovered) {
5348                            mHasSystemUidErrors = true;
5349                        }
5350                    } else if (!recovered) {
5351                        // If we allow this install to proceed, we will be broken.
5352                        // Abort, abort!
5353                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5354                                "scanPackageLI");
5355                    }
5356                    if (!recovered) {
5357                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5358                            + pkg.applicationInfo.uid + "/fs_"
5359                            + currentUid;
5360                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5361                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5362                        String msg = "Package " + pkg.packageName
5363                                + " has mismatched uid: "
5364                                + currentUid + " on disk, "
5365                                + pkg.applicationInfo.uid + " in settings";
5366                        // writer
5367                        synchronized (mPackages) {
5368                            mSettings.mReadMessages.append(msg);
5369                            mSettings.mReadMessages.append('\n');
5370                            uidError = true;
5371                            if (!pkgSetting.uidError) {
5372                                reportSettingsProblem(Log.ERROR, msg);
5373                            }
5374                        }
5375                    }
5376                }
5377                pkg.applicationInfo.dataDir = dataPath.getPath();
5378                if (mShouldRestoreconData) {
5379                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5380                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5381                                pkg.applicationInfo.uid);
5382                }
5383            } else {
5384                if (DEBUG_PACKAGE_SCANNING) {
5385                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5386                        Log.v(TAG, "Want this data dir: " + dataPath);
5387                }
5388                //invoke installer to do the actual installation
5389                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5390                                           pkg.applicationInfo.seinfo);
5391                if (ret < 0) {
5392                    // Error from installer
5393                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5394                            "Unable to create data dirs [errorCode=" + ret + "]");
5395                }
5396
5397                if (dataPath.exists()) {
5398                    pkg.applicationInfo.dataDir = dataPath.getPath();
5399                } else {
5400                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5401                    pkg.applicationInfo.dataDir = null;
5402                }
5403            }
5404
5405            pkgSetting.uidError = uidError;
5406        }
5407
5408        final String path = scanFile.getPath();
5409        final String codePath = pkg.applicationInfo.getCodePath();
5410        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5411        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5412            setBundledAppAbisAndRoots(pkg, pkgSetting);
5413
5414            // If we haven't found any native libraries for the app, check if it has
5415            // renderscript code. We'll need to force the app to 32 bit if it has
5416            // renderscript bitcode.
5417            if (pkg.applicationInfo.primaryCpuAbi == null
5418                    && pkg.applicationInfo.secondaryCpuAbi == null
5419                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5420                NativeLibraryHelper.Handle handle = null;
5421                try {
5422                    handle = NativeLibraryHelper.Handle.create(scanFile);
5423                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5424                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5425                    }
5426                } catch (IOException ioe) {
5427                    Slog.w(TAG, "Error scanning system app : " + ioe);
5428                } finally {
5429                    IoUtils.closeQuietly(handle);
5430                }
5431            }
5432
5433            setNativeLibraryPaths(pkg);
5434        } else {
5435            // TODO: We can probably be smarter about this stuff. For installed apps,
5436            // we can calculate this information at install time once and for all. For
5437            // system apps, we can probably assume that this information doesn't change
5438            // after the first boot scan. As things stand, we do lots of unnecessary work.
5439
5440            // Give ourselves some initial paths; we'll come back for another
5441            // pass once we've determined ABI below.
5442            setNativeLibraryPaths(pkg);
5443
5444            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5445            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5446            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5447
5448            NativeLibraryHelper.Handle handle = null;
5449            try {
5450                handle = NativeLibraryHelper.Handle.create(scanFile);
5451                // TODO(multiArch): This can be null for apps that didn't go through the
5452                // usual installation process. We can calculate it again, like we
5453                // do during install time.
5454                //
5455                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5456                // unnecessary.
5457                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5458
5459                // Null out the abis so that they can be recalculated.
5460                pkg.applicationInfo.primaryCpuAbi = null;
5461                pkg.applicationInfo.secondaryCpuAbi = null;
5462                if (isMultiArch(pkg.applicationInfo)) {
5463                    // Warn if we've set an abiOverride for multi-lib packages..
5464                    // By definition, we need to copy both 32 and 64 bit libraries for
5465                    // such packages.
5466                    if (pkg.cpuAbiOverride != null
5467                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5468                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5469                    }
5470
5471                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5472                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5473                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5474                        if (isAsec) {
5475                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5476                        } else {
5477                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5478                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5479                                    useIsaSpecificSubdirs);
5480                        }
5481                    }
5482
5483                    maybeThrowExceptionForMultiArchCopy(
5484                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5485
5486                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5487                        if (isAsec) {
5488                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5489                        } else {
5490                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5491                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5492                                    useIsaSpecificSubdirs);
5493                        }
5494                    }
5495
5496                    maybeThrowExceptionForMultiArchCopy(
5497                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5498
5499                    if (abi64 >= 0) {
5500                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5501                    }
5502
5503                    if (abi32 >= 0) {
5504                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5505                        if (abi64 >= 0) {
5506                            pkg.applicationInfo.secondaryCpuAbi = abi;
5507                        } else {
5508                            pkg.applicationInfo.primaryCpuAbi = abi;
5509                        }
5510                    }
5511                } else {
5512                    String[] abiList = (cpuAbiOverride != null) ?
5513                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5514
5515                    // Enable gross and lame hacks for apps that are built with old
5516                    // SDK tools. We must scan their APKs for renderscript bitcode and
5517                    // not launch them if it's present. Don't bother checking on devices
5518                    // that don't have 64 bit support.
5519                    boolean needsRenderScriptOverride = false;
5520                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5521                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5522                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5523                        needsRenderScriptOverride = true;
5524                    }
5525
5526                    final int copyRet;
5527                    if (isAsec) {
5528                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5529                    } else {
5530                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5531                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5532                    }
5533
5534                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5535                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5536                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5537                    }
5538
5539                    if (copyRet >= 0) {
5540                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5541                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5542                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5543                    } else if (needsRenderScriptOverride) {
5544                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5545                    }
5546                }
5547            } catch (IOException ioe) {
5548                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5549            } finally {
5550                IoUtils.closeQuietly(handle);
5551            }
5552
5553            // Now that we've calculated the ABIs and determined if it's an internal app,
5554            // we will go ahead and populate the nativeLibraryPath.
5555            setNativeLibraryPaths(pkg);
5556
5557            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5558            final int[] userIds = sUserManager.getUserIds();
5559            synchronized (mInstallLock) {
5560                // Create a native library symlink only if we have native libraries
5561                // and if the native libraries are 32 bit libraries. We do not provide
5562                // this symlink for 64 bit libraries.
5563                if (pkg.applicationInfo.primaryCpuAbi != null &&
5564                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5565                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5566                    for (int userId : userIds) {
5567                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5568                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5569                                    "Failed linking native library dir (user=" + userId + ")");
5570                        }
5571                    }
5572                }
5573            }
5574        }
5575
5576        // This is a special case for the "system" package, where the ABI is
5577        // dictated by the zygote configuration (and init.rc). We should keep track
5578        // of this ABI so that we can deal with "normal" applications that run under
5579        // the same UID correctly.
5580        if (mPlatformPackage == pkg) {
5581            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5582                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5583        }
5584
5585        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5586        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5587        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5588        // Copy the derived override back to the parsed package, so that we can
5589        // update the package settings accordingly.
5590        pkg.cpuAbiOverride = cpuAbiOverride;
5591
5592        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5593                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5594                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5595
5596        // Push the derived path down into PackageSettings so we know what to
5597        // clean up at uninstall time.
5598        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5599
5600        if (DEBUG_ABI_SELECTION) {
5601            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5602                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5603                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5604        }
5605
5606        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5607            // We don't do this here during boot because we can do it all
5608            // at once after scanning all existing packages.
5609            //
5610            // We also do this *before* we perform dexopt on this package, so that
5611            // we can avoid redundant dexopts, and also to make sure we've got the
5612            // code and package path correct.
5613            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5614                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5615        }
5616
5617        if ((scanFlags & SCAN_NO_DEX) == 0) {
5618            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5619                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5620                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5621            }
5622        }
5623
5624        if (mFactoryTest && pkg.requestedPermissions.contains(
5625                android.Manifest.permission.FACTORY_TEST)) {
5626            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5627        }
5628
5629        ArrayList<PackageParser.Package> clientLibPkgs = null;
5630
5631        // writer
5632        synchronized (mPackages) {
5633            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5634                // Only system apps can add new shared libraries.
5635                if (pkg.libraryNames != null) {
5636                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5637                        String name = pkg.libraryNames.get(i);
5638                        boolean allowed = false;
5639                        if (isUpdatedSystemApp(pkg)) {
5640                            // New library entries can only be added through the
5641                            // system image.  This is important to get rid of a lot
5642                            // of nasty edge cases: for example if we allowed a non-
5643                            // system update of the app to add a library, then uninstalling
5644                            // the update would make the library go away, and assumptions
5645                            // we made such as through app install filtering would now
5646                            // have allowed apps on the device which aren't compatible
5647                            // with it.  Better to just have the restriction here, be
5648                            // conservative, and create many fewer cases that can negatively
5649                            // impact the user experience.
5650                            final PackageSetting sysPs = mSettings
5651                                    .getDisabledSystemPkgLPr(pkg.packageName);
5652                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5653                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5654                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5655                                        allowed = true;
5656                                        allowed = true;
5657                                        break;
5658                                    }
5659                                }
5660                            }
5661                        } else {
5662                            allowed = true;
5663                        }
5664                        if (allowed) {
5665                            if (!mSharedLibraries.containsKey(name)) {
5666                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5667                            } else if (!name.equals(pkg.packageName)) {
5668                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5669                                        + name + " already exists; skipping");
5670                            }
5671                        } else {
5672                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5673                                    + name + " that is not declared on system image; skipping");
5674                        }
5675                    }
5676                    if ((scanFlags&SCAN_BOOTING) == 0) {
5677                        // If we are not booting, we need to update any applications
5678                        // that are clients of our shared library.  If we are booting,
5679                        // this will all be done once the scan is complete.
5680                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5681                    }
5682                }
5683            }
5684        }
5685
5686        // We also need to dexopt any apps that are dependent on this library.  Note that
5687        // if these fail, we should abort the install since installing the library will
5688        // result in some apps being broken.
5689        if (clientLibPkgs != null) {
5690            if ((scanFlags & SCAN_NO_DEX) == 0) {
5691                for (int i = 0; i < clientLibPkgs.size(); i++) {
5692                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5693                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5694                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5695                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5696                                "scanPackageLI failed to dexopt clientLibPkgs");
5697                    }
5698                }
5699            }
5700        }
5701
5702        // Request the ActivityManager to kill the process(only for existing packages)
5703        // so that we do not end up in a confused state while the user is still using the older
5704        // version of the application while the new one gets installed.
5705        if ((scanFlags & SCAN_REPLACING) != 0) {
5706            killApplication(pkg.applicationInfo.packageName,
5707                        pkg.applicationInfo.uid, "update pkg");
5708        }
5709
5710        // Also need to kill any apps that are dependent on the library.
5711        if (clientLibPkgs != null) {
5712            for (int i=0; i<clientLibPkgs.size(); i++) {
5713                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5714                killApplication(clientPkg.applicationInfo.packageName,
5715                        clientPkg.applicationInfo.uid, "update lib");
5716            }
5717        }
5718
5719        // writer
5720        synchronized (mPackages) {
5721            // We don't expect installation to fail beyond this point
5722
5723            // Add the new setting to mSettings
5724            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5725            // Add the new setting to mPackages
5726            mPackages.put(pkg.applicationInfo.packageName, pkg);
5727            // Make sure we don't accidentally delete its data.
5728            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5729            while (iter.hasNext()) {
5730                PackageCleanItem item = iter.next();
5731                if (pkgName.equals(item.packageName)) {
5732                    iter.remove();
5733                }
5734            }
5735
5736            // Take care of first install / last update times.
5737            if (currentTime != 0) {
5738                if (pkgSetting.firstInstallTime == 0) {
5739                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5740                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5741                    pkgSetting.lastUpdateTime = currentTime;
5742                }
5743            } else if (pkgSetting.firstInstallTime == 0) {
5744                // We need *something*.  Take time time stamp of the file.
5745                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5746            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5747                if (scanFileTime != pkgSetting.timeStamp) {
5748                    // A package on the system image has changed; consider this
5749                    // to be an update.
5750                    pkgSetting.lastUpdateTime = scanFileTime;
5751                }
5752            }
5753
5754            // Add the package's KeySets to the global KeySetManagerService
5755            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5756            try {
5757                // Old KeySetData no longer valid.
5758                ksms.removeAppKeySetDataLPw(pkg.packageName);
5759                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5760                if (pkg.mKeySetMapping != null) {
5761                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5762                            pkg.mKeySetMapping.entrySet()) {
5763                        if (entry.getValue() != null) {
5764                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5765                                                          entry.getValue(), entry.getKey());
5766                        }
5767                    }
5768                    if (pkg.mUpgradeKeySets != null) {
5769                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5770                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5771                        }
5772                    }
5773                }
5774            } catch (NullPointerException e) {
5775                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5776            } catch (IllegalArgumentException e) {
5777                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5778            }
5779
5780            int N = pkg.providers.size();
5781            StringBuilder r = null;
5782            int i;
5783            for (i=0; i<N; i++) {
5784                PackageParser.Provider p = pkg.providers.get(i);
5785                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5786                        p.info.processName, pkg.applicationInfo.uid);
5787                mProviders.addProvider(p);
5788                p.syncable = p.info.isSyncable;
5789                if (p.info.authority != null) {
5790                    String names[] = p.info.authority.split(";");
5791                    p.info.authority = null;
5792                    for (int j = 0; j < names.length; j++) {
5793                        if (j == 1 && p.syncable) {
5794                            // We only want the first authority for a provider to possibly be
5795                            // syncable, so if we already added this provider using a different
5796                            // authority clear the syncable flag. We copy the provider before
5797                            // changing it because the mProviders object contains a reference
5798                            // to a provider that we don't want to change.
5799                            // Only do this for the second authority since the resulting provider
5800                            // object can be the same for all future authorities for this provider.
5801                            p = new PackageParser.Provider(p);
5802                            p.syncable = false;
5803                        }
5804                        if (!mProvidersByAuthority.containsKey(names[j])) {
5805                            mProvidersByAuthority.put(names[j], p);
5806                            if (p.info.authority == null) {
5807                                p.info.authority = names[j];
5808                            } else {
5809                                p.info.authority = p.info.authority + ";" + names[j];
5810                            }
5811                            if (DEBUG_PACKAGE_SCANNING) {
5812                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5813                                    Log.d(TAG, "Registered content provider: " + names[j]
5814                                            + ", className = " + p.info.name + ", isSyncable = "
5815                                            + p.info.isSyncable);
5816                            }
5817                        } else {
5818                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5819                            Slog.w(TAG, "Skipping provider name " + names[j] +
5820                                    " (in package " + pkg.applicationInfo.packageName +
5821                                    "): name already used by "
5822                                    + ((other != null && other.getComponentName() != null)
5823                                            ? other.getComponentName().getPackageName() : "?"));
5824                        }
5825                    }
5826                }
5827                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5828                    if (r == null) {
5829                        r = new StringBuilder(256);
5830                    } else {
5831                        r.append(' ');
5832                    }
5833                    r.append(p.info.name);
5834                }
5835            }
5836            if (r != null) {
5837                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5838            }
5839
5840            N = pkg.services.size();
5841            r = null;
5842            for (i=0; i<N; i++) {
5843                PackageParser.Service s = pkg.services.get(i);
5844                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5845                        s.info.processName, pkg.applicationInfo.uid);
5846                mServices.addService(s);
5847                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5848                    if (r == null) {
5849                        r = new StringBuilder(256);
5850                    } else {
5851                        r.append(' ');
5852                    }
5853                    r.append(s.info.name);
5854                }
5855            }
5856            if (r != null) {
5857                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5858            }
5859
5860            N = pkg.receivers.size();
5861            r = null;
5862            for (i=0; i<N; i++) {
5863                PackageParser.Activity a = pkg.receivers.get(i);
5864                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5865                        a.info.processName, pkg.applicationInfo.uid);
5866                mReceivers.addActivity(a, "receiver");
5867                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5868                    if (r == null) {
5869                        r = new StringBuilder(256);
5870                    } else {
5871                        r.append(' ');
5872                    }
5873                    r.append(a.info.name);
5874                }
5875            }
5876            if (r != null) {
5877                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5878            }
5879
5880            N = pkg.activities.size();
5881            r = null;
5882            for (i=0; i<N; i++) {
5883                PackageParser.Activity a = pkg.activities.get(i);
5884                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5885                        a.info.processName, pkg.applicationInfo.uid);
5886                mActivities.addActivity(a, "activity");
5887                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5888                    if (r == null) {
5889                        r = new StringBuilder(256);
5890                    } else {
5891                        r.append(' ');
5892                    }
5893                    r.append(a.info.name);
5894                }
5895            }
5896            if (r != null) {
5897                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5898            }
5899
5900            N = pkg.permissionGroups.size();
5901            r = null;
5902            for (i=0; i<N; i++) {
5903                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5904                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5905                if (cur == null) {
5906                    mPermissionGroups.put(pg.info.name, pg);
5907                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5908                        if (r == null) {
5909                            r = new StringBuilder(256);
5910                        } else {
5911                            r.append(' ');
5912                        }
5913                        r.append(pg.info.name);
5914                    }
5915                } else {
5916                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5917                            + pg.info.packageName + " ignored: original from "
5918                            + cur.info.packageName);
5919                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5920                        if (r == null) {
5921                            r = new StringBuilder(256);
5922                        } else {
5923                            r.append(' ');
5924                        }
5925                        r.append("DUP:");
5926                        r.append(pg.info.name);
5927                    }
5928                }
5929            }
5930            if (r != null) {
5931                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5932            }
5933
5934            N = pkg.permissions.size();
5935            r = null;
5936            for (i=0; i<N; i++) {
5937                PackageParser.Permission p = pkg.permissions.get(i);
5938                HashMap<String, BasePermission> permissionMap =
5939                        p.tree ? mSettings.mPermissionTrees
5940                        : mSettings.mPermissions;
5941                p.group = mPermissionGroups.get(p.info.group);
5942                if (p.info.group == null || p.group != null) {
5943                    BasePermission bp = permissionMap.get(p.info.name);
5944
5945                    // Allow system apps to redefine non-system permissions
5946                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
5947                        final boolean currentOwnerIsSystem = (bp.perm != null
5948                                && isSystemApp(bp.perm.owner));
5949                        if (isSystemApp(p.owner) && !currentOwnerIsSystem) {
5950                            String msg = "New decl " + p.owner + " of permission  "
5951                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
5952                            reportSettingsProblem(Log.WARN, msg);
5953                            bp = null;
5954                        }
5955                    }
5956
5957                    if (bp == null) {
5958                        bp = new BasePermission(p.info.name, p.info.packageName,
5959                                BasePermission.TYPE_NORMAL);
5960                        permissionMap.put(p.info.name, bp);
5961                    }
5962
5963                    if (bp.perm == null) {
5964                        if (bp.sourcePackage == null
5965                                || bp.sourcePackage.equals(p.info.packageName)) {
5966                            BasePermission tree = findPermissionTreeLP(p.info.name);
5967                            if (tree == null
5968                                    || tree.sourcePackage.equals(p.info.packageName)) {
5969                                bp.packageSetting = pkgSetting;
5970                                bp.perm = p;
5971                                bp.uid = pkg.applicationInfo.uid;
5972                                bp.sourcePackage = p.info.packageName;
5973                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5974                                    if (r == null) {
5975                                        r = new StringBuilder(256);
5976                                    } else {
5977                                        r.append(' ');
5978                                    }
5979                                    r.append(p.info.name);
5980                                }
5981                            } else {
5982                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5983                                        + p.info.packageName + " ignored: base tree "
5984                                        + tree.name + " is from package "
5985                                        + tree.sourcePackage);
5986                            }
5987                        } else {
5988                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5989                                    + p.info.packageName + " ignored: original from "
5990                                    + bp.sourcePackage);
5991                        }
5992                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5993                        if (r == null) {
5994                            r = new StringBuilder(256);
5995                        } else {
5996                            r.append(' ');
5997                        }
5998                        r.append("DUP:");
5999                        r.append(p.info.name);
6000                    }
6001                    if (bp.perm == p) {
6002                        bp.protectionLevel = p.info.protectionLevel;
6003                    }
6004                } else {
6005                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6006                            + p.info.packageName + " ignored: no group "
6007                            + p.group);
6008                }
6009            }
6010            if (r != null) {
6011                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6012            }
6013
6014            N = pkg.instrumentation.size();
6015            r = null;
6016            for (i=0; i<N; i++) {
6017                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6018                a.info.packageName = pkg.applicationInfo.packageName;
6019                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6020                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6021                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6022                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6023                a.info.dataDir = pkg.applicationInfo.dataDir;
6024
6025                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6026                // need other information about the application, like the ABI and what not ?
6027                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6028                mInstrumentation.put(a.getComponentName(), a);
6029                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6030                    if (r == null) {
6031                        r = new StringBuilder(256);
6032                    } else {
6033                        r.append(' ');
6034                    }
6035                    r.append(a.info.name);
6036                }
6037            }
6038            if (r != null) {
6039                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6040            }
6041
6042            if (pkg.protectedBroadcasts != null) {
6043                N = pkg.protectedBroadcasts.size();
6044                for (i=0; i<N; i++) {
6045                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6046                }
6047            }
6048
6049            pkgSetting.setTimeStamp(scanFileTime);
6050
6051            // Create idmap files for pairs of (packages, overlay packages).
6052            // Note: "android", ie framework-res.apk, is handled by native layers.
6053            if (pkg.mOverlayTarget != null) {
6054                // This is an overlay package.
6055                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6056                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6057                        mOverlays.put(pkg.mOverlayTarget,
6058                                new HashMap<String, PackageParser.Package>());
6059                    }
6060                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6061                    map.put(pkg.packageName, pkg);
6062                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6063                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6064                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6065                                "scanPackageLI failed to createIdmap");
6066                    }
6067                }
6068            } else if (mOverlays.containsKey(pkg.packageName) &&
6069                    !pkg.packageName.equals("android")) {
6070                // This is a regular package, with one or more known overlay packages.
6071                createIdmapsForPackageLI(pkg);
6072            }
6073        }
6074
6075        return pkg;
6076    }
6077
6078    /**
6079     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6080     * i.e, so that all packages can be run inside a single process if required.
6081     *
6082     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6083     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6084     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6085     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6086     * updating a package that belongs to a shared user.
6087     *
6088     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6089     * adds unnecessary complexity.
6090     */
6091    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6092            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6093        String requiredInstructionSet = null;
6094        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6095            requiredInstructionSet = VMRuntime.getInstructionSet(
6096                     scannedPackage.applicationInfo.primaryCpuAbi);
6097        }
6098
6099        PackageSetting requirer = null;
6100        for (PackageSetting ps : packagesForUser) {
6101            // If packagesForUser contains scannedPackage, we skip it. This will happen
6102            // when scannedPackage is an update of an existing package. Without this check,
6103            // we will never be able to change the ABI of any package belonging to a shared
6104            // user, even if it's compatible with other packages.
6105            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6106                if (ps.primaryCpuAbiString == null) {
6107                    continue;
6108                }
6109
6110                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6111                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6112                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6113                    // this but there's not much we can do.
6114                    String errorMessage = "Instruction set mismatch, "
6115                            + ((requirer == null) ? "[caller]" : requirer)
6116                            + " requires " + requiredInstructionSet + " whereas " + ps
6117                            + " requires " + instructionSet;
6118                    Slog.w(TAG, errorMessage);
6119                }
6120
6121                if (requiredInstructionSet == null) {
6122                    requiredInstructionSet = instructionSet;
6123                    requirer = ps;
6124                }
6125            }
6126        }
6127
6128        if (requiredInstructionSet != null) {
6129            String adjustedAbi;
6130            if (requirer != null) {
6131                // requirer != null implies that either scannedPackage was null or that scannedPackage
6132                // did not require an ABI, in which case we have to adjust scannedPackage to match
6133                // the ABI of the set (which is the same as requirer's ABI)
6134                adjustedAbi = requirer.primaryCpuAbiString;
6135                if (scannedPackage != null) {
6136                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6137                }
6138            } else {
6139                // requirer == null implies that we're updating all ABIs in the set to
6140                // match scannedPackage.
6141                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6142            }
6143
6144            for (PackageSetting ps : packagesForUser) {
6145                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6146                    if (ps.primaryCpuAbiString != null) {
6147                        continue;
6148                    }
6149
6150                    ps.primaryCpuAbiString = adjustedAbi;
6151                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6152                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6153                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6154
6155                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6156                                deferDexOpt, true) == DEX_OPT_FAILED) {
6157                            ps.primaryCpuAbiString = null;
6158                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6159                            return;
6160                        } else {
6161                            mInstaller.rmdex(ps.codePathString,
6162                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6163                        }
6164                    }
6165                }
6166            }
6167        }
6168    }
6169
6170    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6171        synchronized (mPackages) {
6172            mResolverReplaced = true;
6173            // Set up information for custom user intent resolution activity.
6174            mResolveActivity.applicationInfo = pkg.applicationInfo;
6175            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6176            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6177            mResolveActivity.processName = null;
6178            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6179            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6180                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6181            mResolveActivity.theme = 0;
6182            mResolveActivity.exported = true;
6183            mResolveActivity.enabled = true;
6184            mResolveInfo.activityInfo = mResolveActivity;
6185            mResolveInfo.priority = 0;
6186            mResolveInfo.preferredOrder = 0;
6187            mResolveInfo.match = 0;
6188            mResolveComponentName = mCustomResolverComponentName;
6189            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6190                    mResolveComponentName);
6191        }
6192    }
6193
6194    private static String calculateBundledApkRoot(final String codePathString) {
6195        final File codePath = new File(codePathString);
6196        final File codeRoot;
6197        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6198            codeRoot = Environment.getRootDirectory();
6199        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6200            codeRoot = Environment.getOemDirectory();
6201        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6202            codeRoot = Environment.getVendorDirectory();
6203        } else {
6204            // Unrecognized code path; take its top real segment as the apk root:
6205            // e.g. /something/app/blah.apk => /something
6206            try {
6207                File f = codePath.getCanonicalFile();
6208                File parent = f.getParentFile();    // non-null because codePath is a file
6209                File tmp;
6210                while ((tmp = parent.getParentFile()) != null) {
6211                    f = parent;
6212                    parent = tmp;
6213                }
6214                codeRoot = f;
6215                Slog.w(TAG, "Unrecognized code path "
6216                        + codePath + " - using " + codeRoot);
6217            } catch (IOException e) {
6218                // Can't canonicalize the code path -- shenanigans?
6219                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6220                return Environment.getRootDirectory().getPath();
6221            }
6222        }
6223        return codeRoot.getPath();
6224    }
6225
6226    /**
6227     * Derive and set the location of native libraries for the given package,
6228     * which varies depending on where and how the package was installed.
6229     */
6230    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6231        final ApplicationInfo info = pkg.applicationInfo;
6232        final String codePath = pkg.codePath;
6233        final File codeFile = new File(codePath);
6234        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6235        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6236
6237        info.nativeLibraryRootDir = null;
6238        info.nativeLibraryRootRequiresIsa = false;
6239        info.nativeLibraryDir = null;
6240        info.secondaryNativeLibraryDir = null;
6241
6242        if (isApkFile(codeFile)) {
6243            // Monolithic install
6244            if (bundledApp) {
6245                // If "/system/lib64/apkname" exists, assume that is the per-package
6246                // native library directory to use; otherwise use "/system/lib/apkname".
6247                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6248                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6249                        getPrimaryInstructionSet(info));
6250
6251                // This is a bundled system app so choose the path based on the ABI.
6252                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6253                // is just the default path.
6254                final String apkName = deriveCodePathName(codePath);
6255                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6256                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6257                        apkName).getAbsolutePath();
6258
6259                if (info.secondaryCpuAbi != null) {
6260                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6261                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6262                            secondaryLibDir, apkName).getAbsolutePath();
6263                }
6264            } else if (asecApp) {
6265                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6266                        .getAbsolutePath();
6267            } else {
6268                final String apkName = deriveCodePathName(codePath);
6269                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6270                        .getAbsolutePath();
6271            }
6272
6273            info.nativeLibraryRootRequiresIsa = false;
6274            info.nativeLibraryDir = info.nativeLibraryRootDir;
6275        } else {
6276            // Cluster install
6277            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6278            info.nativeLibraryRootRequiresIsa = true;
6279
6280            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6281                    getPrimaryInstructionSet(info)).getAbsolutePath();
6282
6283            if (info.secondaryCpuAbi != null) {
6284                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6285                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6286            }
6287        }
6288    }
6289
6290    /**
6291     * Calculate the abis and roots for a bundled app. These can uniquely
6292     * be determined from the contents of the system partition, i.e whether
6293     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6294     * of this information, and instead assume that the system was built
6295     * sensibly.
6296     */
6297    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6298                                           PackageSetting pkgSetting) {
6299        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6300
6301        // If "/system/lib64/apkname" exists, assume that is the per-package
6302        // native library directory to use; otherwise use "/system/lib/apkname".
6303        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6304        setBundledAppAbi(pkg, apkRoot, apkName);
6305        // pkgSetting might be null during rescan following uninstall of updates
6306        // to a bundled app, so accommodate that possibility.  The settings in
6307        // that case will be established later from the parsed package.
6308        //
6309        // If the settings aren't null, sync them up with what we've just derived.
6310        // note that apkRoot isn't stored in the package settings.
6311        if (pkgSetting != null) {
6312            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6313            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6314        }
6315    }
6316
6317    /**
6318     * Deduces the ABI of a bundled app and sets the relevant fields on the
6319     * parsed pkg object.
6320     *
6321     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6322     *        under which system libraries are installed.
6323     * @param apkName the name of the installed package.
6324     */
6325    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6326        final File codeFile = new File(pkg.codePath);
6327
6328        final boolean has64BitLibs;
6329        final boolean has32BitLibs;
6330        if (isApkFile(codeFile)) {
6331            // Monolithic install
6332            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6333            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6334        } else {
6335            // Cluster install
6336            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6337            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6338                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6339                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6340                has64BitLibs = (new File(rootDir, isa)).exists();
6341            } else {
6342                has64BitLibs = false;
6343            }
6344            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6345                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6346                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6347                has32BitLibs = (new File(rootDir, isa)).exists();
6348            } else {
6349                has32BitLibs = false;
6350            }
6351        }
6352
6353        if (has64BitLibs && !has32BitLibs) {
6354            // The package has 64 bit libs, but not 32 bit libs. Its primary
6355            // ABI should be 64 bit. We can safely assume here that the bundled
6356            // native libraries correspond to the most preferred ABI in the list.
6357
6358            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6359            pkg.applicationInfo.secondaryCpuAbi = null;
6360        } else if (has32BitLibs && !has64BitLibs) {
6361            // The package has 32 bit libs but not 64 bit libs. Its primary
6362            // ABI should be 32 bit.
6363
6364            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6365            pkg.applicationInfo.secondaryCpuAbi = null;
6366        } else if (has32BitLibs && has64BitLibs) {
6367            // The application has both 64 and 32 bit bundled libraries. We check
6368            // here that the app declares multiArch support, and warn if it doesn't.
6369            //
6370            // We will be lenient here and record both ABIs. The primary will be the
6371            // ABI that's higher on the list, i.e, a device that's configured to prefer
6372            // 64 bit apps will see a 64 bit primary ABI,
6373
6374            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6375                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6376            }
6377
6378            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6379                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6380                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6381            } else {
6382                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6383                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6384            }
6385        } else {
6386            pkg.applicationInfo.primaryCpuAbi = null;
6387            pkg.applicationInfo.secondaryCpuAbi = null;
6388        }
6389    }
6390
6391    private void killApplication(String pkgName, int appId, String reason) {
6392        // Request the ActivityManager to kill the process(only for existing packages)
6393        // so that we do not end up in a confused state while the user is still using the older
6394        // version of the application while the new one gets installed.
6395        IActivityManager am = ActivityManagerNative.getDefault();
6396        if (am != null) {
6397            try {
6398                am.killApplicationWithAppId(pkgName, appId, reason);
6399            } catch (RemoteException e) {
6400            }
6401        }
6402    }
6403
6404    void removePackageLI(PackageSetting ps, boolean chatty) {
6405        if (DEBUG_INSTALL) {
6406            if (chatty)
6407                Log.d(TAG, "Removing package " + ps.name);
6408        }
6409
6410        // writer
6411        synchronized (mPackages) {
6412            mPackages.remove(ps.name);
6413            final PackageParser.Package pkg = ps.pkg;
6414            if (pkg != null) {
6415                cleanPackageDataStructuresLILPw(pkg, chatty);
6416            }
6417        }
6418    }
6419
6420    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6421        if (DEBUG_INSTALL) {
6422            if (chatty)
6423                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6424        }
6425
6426        // writer
6427        synchronized (mPackages) {
6428            mPackages.remove(pkg.applicationInfo.packageName);
6429            cleanPackageDataStructuresLILPw(pkg, chatty);
6430        }
6431    }
6432
6433    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6434        int N = pkg.providers.size();
6435        StringBuilder r = null;
6436        int i;
6437        for (i=0; i<N; i++) {
6438            PackageParser.Provider p = pkg.providers.get(i);
6439            mProviders.removeProvider(p);
6440            if (p.info.authority == null) {
6441
6442                /* There was another ContentProvider with this authority when
6443                 * this app was installed so this authority is null,
6444                 * Ignore it as we don't have to unregister the provider.
6445                 */
6446                continue;
6447            }
6448            String names[] = p.info.authority.split(";");
6449            for (int j = 0; j < names.length; j++) {
6450                if (mProvidersByAuthority.get(names[j]) == p) {
6451                    mProvidersByAuthority.remove(names[j]);
6452                    if (DEBUG_REMOVE) {
6453                        if (chatty)
6454                            Log.d(TAG, "Unregistered content provider: " + names[j]
6455                                    + ", className = " + p.info.name + ", isSyncable = "
6456                                    + p.info.isSyncable);
6457                    }
6458                }
6459            }
6460            if (DEBUG_REMOVE && chatty) {
6461                if (r == null) {
6462                    r = new StringBuilder(256);
6463                } else {
6464                    r.append(' ');
6465                }
6466                r.append(p.info.name);
6467            }
6468        }
6469        if (r != null) {
6470            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6471        }
6472
6473        N = pkg.services.size();
6474        r = null;
6475        for (i=0; i<N; i++) {
6476            PackageParser.Service s = pkg.services.get(i);
6477            mServices.removeService(s);
6478            if (chatty) {
6479                if (r == null) {
6480                    r = new StringBuilder(256);
6481                } else {
6482                    r.append(' ');
6483                }
6484                r.append(s.info.name);
6485            }
6486        }
6487        if (r != null) {
6488            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6489        }
6490
6491        N = pkg.receivers.size();
6492        r = null;
6493        for (i=0; i<N; i++) {
6494            PackageParser.Activity a = pkg.receivers.get(i);
6495            mReceivers.removeActivity(a, "receiver");
6496            if (DEBUG_REMOVE && chatty) {
6497                if (r == null) {
6498                    r = new StringBuilder(256);
6499                } else {
6500                    r.append(' ');
6501                }
6502                r.append(a.info.name);
6503            }
6504        }
6505        if (r != null) {
6506            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6507        }
6508
6509        N = pkg.activities.size();
6510        r = null;
6511        for (i=0; i<N; i++) {
6512            PackageParser.Activity a = pkg.activities.get(i);
6513            mActivities.removeActivity(a, "activity");
6514            if (DEBUG_REMOVE && chatty) {
6515                if (r == null) {
6516                    r = new StringBuilder(256);
6517                } else {
6518                    r.append(' ');
6519                }
6520                r.append(a.info.name);
6521            }
6522        }
6523        if (r != null) {
6524            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6525        }
6526
6527        N = pkg.permissions.size();
6528        r = null;
6529        for (i=0; i<N; i++) {
6530            PackageParser.Permission p = pkg.permissions.get(i);
6531            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6532            if (bp == null) {
6533                bp = mSettings.mPermissionTrees.get(p.info.name);
6534            }
6535            if (bp != null && bp.perm == p) {
6536                bp.perm = null;
6537                if (DEBUG_REMOVE && chatty) {
6538                    if (r == null) {
6539                        r = new StringBuilder(256);
6540                    } else {
6541                        r.append(' ');
6542                    }
6543                    r.append(p.info.name);
6544                }
6545            }
6546            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6547                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6548                if (appOpPerms != null) {
6549                    appOpPerms.remove(pkg.packageName);
6550                }
6551            }
6552        }
6553        if (r != null) {
6554            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6555        }
6556
6557        N = pkg.requestedPermissions.size();
6558        r = null;
6559        for (i=0; i<N; i++) {
6560            String perm = pkg.requestedPermissions.get(i);
6561            BasePermission bp = mSettings.mPermissions.get(perm);
6562            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6563                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6564                if (appOpPerms != null) {
6565                    appOpPerms.remove(pkg.packageName);
6566                    if (appOpPerms.isEmpty()) {
6567                        mAppOpPermissionPackages.remove(perm);
6568                    }
6569                }
6570            }
6571        }
6572        if (r != null) {
6573            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6574        }
6575
6576        N = pkg.instrumentation.size();
6577        r = null;
6578        for (i=0; i<N; i++) {
6579            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6580            mInstrumentation.remove(a.getComponentName());
6581            if (DEBUG_REMOVE && chatty) {
6582                if (r == null) {
6583                    r = new StringBuilder(256);
6584                } else {
6585                    r.append(' ');
6586                }
6587                r.append(a.info.name);
6588            }
6589        }
6590        if (r != null) {
6591            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6592        }
6593
6594        r = null;
6595        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6596            // Only system apps can hold shared libraries.
6597            if (pkg.libraryNames != null) {
6598                for (i=0; i<pkg.libraryNames.size(); i++) {
6599                    String name = pkg.libraryNames.get(i);
6600                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6601                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6602                        mSharedLibraries.remove(name);
6603                        if (DEBUG_REMOVE && chatty) {
6604                            if (r == null) {
6605                                r = new StringBuilder(256);
6606                            } else {
6607                                r.append(' ');
6608                            }
6609                            r.append(name);
6610                        }
6611                    }
6612                }
6613            }
6614        }
6615        if (r != null) {
6616            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6617        }
6618    }
6619
6620    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6621        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6622            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6623                return true;
6624            }
6625        }
6626        return false;
6627    }
6628
6629    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6630    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6631    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6632
6633    private void updatePermissionsLPw(String changingPkg,
6634            PackageParser.Package pkgInfo, int flags) {
6635        // Make sure there are no dangling permission trees.
6636        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6637        while (it.hasNext()) {
6638            final BasePermission bp = it.next();
6639            if (bp.packageSetting == null) {
6640                // We may not yet have parsed the package, so just see if
6641                // we still know about its settings.
6642                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6643            }
6644            if (bp.packageSetting == null) {
6645                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6646                        + " from package " + bp.sourcePackage);
6647                it.remove();
6648            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6649                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6650                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6651                            + " from package " + bp.sourcePackage);
6652                    flags |= UPDATE_PERMISSIONS_ALL;
6653                    it.remove();
6654                }
6655            }
6656        }
6657
6658        // Make sure all dynamic permissions have been assigned to a package,
6659        // and make sure there are no dangling permissions.
6660        it = mSettings.mPermissions.values().iterator();
6661        while (it.hasNext()) {
6662            final BasePermission bp = it.next();
6663            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6664                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6665                        + bp.name + " pkg=" + bp.sourcePackage
6666                        + " info=" + bp.pendingInfo);
6667                if (bp.packageSetting == null && bp.pendingInfo != null) {
6668                    final BasePermission tree = findPermissionTreeLP(bp.name);
6669                    if (tree != null && tree.perm != null) {
6670                        bp.packageSetting = tree.packageSetting;
6671                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6672                                new PermissionInfo(bp.pendingInfo));
6673                        bp.perm.info.packageName = tree.perm.info.packageName;
6674                        bp.perm.info.name = bp.name;
6675                        bp.uid = tree.uid;
6676                    }
6677                }
6678            }
6679            if (bp.packageSetting == null) {
6680                // We may not yet have parsed the package, so just see if
6681                // we still know about its settings.
6682                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6683            }
6684            if (bp.packageSetting == null) {
6685                Slog.w(TAG, "Removing dangling permission: " + bp.name
6686                        + " from package " + bp.sourcePackage);
6687                it.remove();
6688            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6689                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6690                    Slog.i(TAG, "Removing old permission: " + bp.name
6691                            + " from package " + bp.sourcePackage);
6692                    flags |= UPDATE_PERMISSIONS_ALL;
6693                    it.remove();
6694                }
6695            }
6696        }
6697
6698        // Now update the permissions for all packages, in particular
6699        // replace the granted permissions of the system packages.
6700        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6701            for (PackageParser.Package pkg : mPackages.values()) {
6702                if (pkg != pkgInfo) {
6703                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6704                            changingPkg);
6705                }
6706            }
6707        }
6708
6709        if (pkgInfo != null) {
6710            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6711        }
6712    }
6713
6714    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6715            String packageOfInterest) {
6716        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6717        if (ps == null) {
6718            return;
6719        }
6720        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6721        HashSet<String> origPermissions = gp.grantedPermissions;
6722        boolean changedPermission = false;
6723
6724        if (replace) {
6725            ps.permissionsFixed = false;
6726            if (gp == ps) {
6727                origPermissions = new HashSet<String>(gp.grantedPermissions);
6728                gp.grantedPermissions.clear();
6729                gp.gids = mGlobalGids;
6730            }
6731        }
6732
6733        if (gp.gids == null) {
6734            gp.gids = mGlobalGids;
6735        }
6736
6737        final int N = pkg.requestedPermissions.size();
6738        for (int i=0; i<N; i++) {
6739            final String name = pkg.requestedPermissions.get(i);
6740            final boolean required = pkg.requestedPermissionsRequired.get(i);
6741            final BasePermission bp = mSettings.mPermissions.get(name);
6742            if (DEBUG_INSTALL) {
6743                if (gp != ps) {
6744                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6745                }
6746            }
6747
6748            if (bp == null || bp.packageSetting == null) {
6749                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6750                    Slog.w(TAG, "Unknown permission " + name
6751                            + " in package " + pkg.packageName);
6752                }
6753                continue;
6754            }
6755
6756            final String perm = bp.name;
6757            boolean allowed;
6758            boolean allowedSig = false;
6759            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6760                // Keep track of app op permissions.
6761                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6762                if (pkgs == null) {
6763                    pkgs = new ArraySet<>();
6764                    mAppOpPermissionPackages.put(bp.name, pkgs);
6765                }
6766                pkgs.add(pkg.packageName);
6767            }
6768            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6769            if (level == PermissionInfo.PROTECTION_NORMAL
6770                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6771                // We grant a normal or dangerous permission if any of the following
6772                // are true:
6773                // 1) The permission is required
6774                // 2) The permission is optional, but was granted in the past
6775                // 3) The permission is optional, but was requested by an
6776                //    app in /system (not /data)
6777                //
6778                // Otherwise, reject the permission.
6779                allowed = (required || origPermissions.contains(perm)
6780                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6781            } else if (bp.packageSetting == null) {
6782                // This permission is invalid; skip it.
6783                allowed = false;
6784            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6785                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6786                if (allowed) {
6787                    allowedSig = true;
6788                }
6789            } else {
6790                allowed = false;
6791            }
6792            if (DEBUG_INSTALL) {
6793                if (gp != ps) {
6794                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6795                }
6796            }
6797            if (allowed) {
6798                if (!isSystemApp(ps) && ps.permissionsFixed) {
6799                    // If this is an existing, non-system package, then
6800                    // we can't add any new permissions to it.
6801                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6802                        // Except...  if this is a permission that was added
6803                        // to the platform (note: need to only do this when
6804                        // updating the platform).
6805                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6806                    }
6807                }
6808                if (allowed) {
6809                    if (!gp.grantedPermissions.contains(perm)) {
6810                        changedPermission = true;
6811                        gp.grantedPermissions.add(perm);
6812                        gp.gids = appendInts(gp.gids, bp.gids);
6813                    } else if (!ps.haveGids) {
6814                        gp.gids = appendInts(gp.gids, bp.gids);
6815                    }
6816                } else {
6817                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6818                        Slog.w(TAG, "Not granting permission " + perm
6819                                + " to package " + pkg.packageName
6820                                + " because it was previously installed without");
6821                    }
6822                }
6823            } else {
6824                if (gp.grantedPermissions.remove(perm)) {
6825                    changedPermission = true;
6826                    gp.gids = removeInts(gp.gids, bp.gids);
6827                    Slog.i(TAG, "Un-granting permission " + perm
6828                            + " from package " + pkg.packageName
6829                            + " (protectionLevel=" + bp.protectionLevel
6830                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6831                            + ")");
6832                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6833                    // Don't print warning for app op permissions, since it is fine for them
6834                    // not to be granted, there is a UI for the user to decide.
6835                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6836                        Slog.w(TAG, "Not granting permission " + perm
6837                                + " to package " + pkg.packageName
6838                                + " (protectionLevel=" + bp.protectionLevel
6839                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6840                                + ")");
6841                    }
6842                }
6843            }
6844        }
6845
6846        if ((changedPermission || replace) && !ps.permissionsFixed &&
6847                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6848            // This is the first that we have heard about this package, so the
6849            // permissions we have now selected are fixed until explicitly
6850            // changed.
6851            ps.permissionsFixed = true;
6852        }
6853        ps.haveGids = true;
6854    }
6855
6856    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6857        boolean allowed = false;
6858        final int NP = PackageParser.NEW_PERMISSIONS.length;
6859        for (int ip=0; ip<NP; ip++) {
6860            final PackageParser.NewPermissionInfo npi
6861                    = PackageParser.NEW_PERMISSIONS[ip];
6862            if (npi.name.equals(perm)
6863                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6864                allowed = true;
6865                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6866                        + pkg.packageName);
6867                break;
6868            }
6869        }
6870        return allowed;
6871    }
6872
6873    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6874                                          BasePermission bp, HashSet<String> origPermissions) {
6875        boolean allowed;
6876        allowed = (compareSignatures(
6877                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6878                        == PackageManager.SIGNATURE_MATCH)
6879                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6880                        == PackageManager.SIGNATURE_MATCH);
6881        if (!allowed && (bp.protectionLevel
6882                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6883            if (isSystemApp(pkg)) {
6884                // For updated system applications, a system permission
6885                // is granted only if it had been defined by the original application.
6886                if (isUpdatedSystemApp(pkg)) {
6887                    final PackageSetting sysPs = mSettings
6888                            .getDisabledSystemPkgLPr(pkg.packageName);
6889                    final GrantedPermissions origGp = sysPs.sharedUser != null
6890                            ? sysPs.sharedUser : sysPs;
6891
6892                    if (origGp.grantedPermissions.contains(perm)) {
6893                        // If the original was granted this permission, we take
6894                        // that grant decision as read and propagate it to the
6895                        // update.
6896                        allowed = true;
6897                    } else {
6898                        // The system apk may have been updated with an older
6899                        // version of the one on the data partition, but which
6900                        // granted a new system permission that it didn't have
6901                        // before.  In this case we do want to allow the app to
6902                        // now get the new permission if the ancestral apk is
6903                        // privileged to get it.
6904                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6905                            for (int j=0;
6906                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6907                                if (perm.equals(
6908                                        sysPs.pkg.requestedPermissions.get(j))) {
6909                                    allowed = true;
6910                                    break;
6911                                }
6912                            }
6913                        }
6914                    }
6915                } else {
6916                    allowed = isPrivilegedApp(pkg);
6917                }
6918            }
6919        }
6920        if (!allowed && (bp.protectionLevel
6921                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6922            // For development permissions, a development permission
6923            // is granted only if it was already granted.
6924            allowed = origPermissions.contains(perm);
6925        }
6926        return allowed;
6927    }
6928
6929    final class ActivityIntentResolver
6930            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6931        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6932                boolean defaultOnly, int userId) {
6933            if (!sUserManager.exists(userId)) return null;
6934            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6935            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6936        }
6937
6938        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6939                int userId) {
6940            if (!sUserManager.exists(userId)) return null;
6941            mFlags = flags;
6942            return super.queryIntent(intent, resolvedType,
6943                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6944        }
6945
6946        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6947                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6948            if (!sUserManager.exists(userId)) return null;
6949            if (packageActivities == null) {
6950                return null;
6951            }
6952            mFlags = flags;
6953            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6954            final int N = packageActivities.size();
6955            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6956                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6957
6958            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6959            for (int i = 0; i < N; ++i) {
6960                intentFilters = packageActivities.get(i).intents;
6961                if (intentFilters != null && intentFilters.size() > 0) {
6962                    PackageParser.ActivityIntentInfo[] array =
6963                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6964                    intentFilters.toArray(array);
6965                    listCut.add(array);
6966                }
6967            }
6968            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6969        }
6970
6971        public final void addActivity(PackageParser.Activity a, String type) {
6972            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6973            mActivities.put(a.getComponentName(), a);
6974            if (DEBUG_SHOW_INFO)
6975                Log.v(
6976                TAG, "  " + type + " " +
6977                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6978            if (DEBUG_SHOW_INFO)
6979                Log.v(TAG, "    Class=" + a.info.name);
6980            final int NI = a.intents.size();
6981            for (int j=0; j<NI; j++) {
6982                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6983                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6984                    intent.setPriority(0);
6985                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6986                            + a.className + " with priority > 0, forcing to 0");
6987                }
6988                if (DEBUG_SHOW_INFO) {
6989                    Log.v(TAG, "    IntentFilter:");
6990                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6991                }
6992                if (!intent.debugCheck()) {
6993                    Log.w(TAG, "==> For Activity " + a.info.name);
6994                }
6995                addFilter(intent);
6996            }
6997        }
6998
6999        public final void removeActivity(PackageParser.Activity a, String type) {
7000            mActivities.remove(a.getComponentName());
7001            if (DEBUG_SHOW_INFO) {
7002                Log.v(TAG, "  " + type + " "
7003                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7004                                : a.info.name) + ":");
7005                Log.v(TAG, "    Class=" + a.info.name);
7006            }
7007            final int NI = a.intents.size();
7008            for (int j=0; j<NI; j++) {
7009                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7010                if (DEBUG_SHOW_INFO) {
7011                    Log.v(TAG, "    IntentFilter:");
7012                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7013                }
7014                removeFilter(intent);
7015            }
7016        }
7017
7018        @Override
7019        protected boolean allowFilterResult(
7020                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7021            ActivityInfo filterAi = filter.activity.info;
7022            for (int i=dest.size()-1; i>=0; i--) {
7023                ActivityInfo destAi = dest.get(i).activityInfo;
7024                if (destAi.name == filterAi.name
7025                        && destAi.packageName == filterAi.packageName) {
7026                    return false;
7027                }
7028            }
7029            return true;
7030        }
7031
7032        @Override
7033        protected ActivityIntentInfo[] newArray(int size) {
7034            return new ActivityIntentInfo[size];
7035        }
7036
7037        @Override
7038        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7039            if (!sUserManager.exists(userId)) return true;
7040            PackageParser.Package p = filter.activity.owner;
7041            if (p != null) {
7042                PackageSetting ps = (PackageSetting)p.mExtras;
7043                if (ps != null) {
7044                    // System apps are never considered stopped for purposes of
7045                    // filtering, because there may be no way for the user to
7046                    // actually re-launch them.
7047                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7048                            && ps.getStopped(userId);
7049                }
7050            }
7051            return false;
7052        }
7053
7054        @Override
7055        protected boolean isPackageForFilter(String packageName,
7056                PackageParser.ActivityIntentInfo info) {
7057            return packageName.equals(info.activity.owner.packageName);
7058        }
7059
7060        @Override
7061        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7062                int match, int userId) {
7063            if (!sUserManager.exists(userId)) return null;
7064            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7065                return null;
7066            }
7067            final PackageParser.Activity activity = info.activity;
7068            if (mSafeMode && (activity.info.applicationInfo.flags
7069                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7070                return null;
7071            }
7072            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7073            if (ps == null) {
7074                return null;
7075            }
7076            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7077                    ps.readUserState(userId), userId);
7078            if (ai == null) {
7079                return null;
7080            }
7081            final ResolveInfo res = new ResolveInfo();
7082            res.activityInfo = ai;
7083            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7084                res.filter = info;
7085            }
7086            res.priority = info.getPriority();
7087            res.preferredOrder = activity.owner.mPreferredOrder;
7088            //System.out.println("Result: " + res.activityInfo.className +
7089            //                   " = " + res.priority);
7090            res.match = match;
7091            res.isDefault = info.hasDefault;
7092            res.labelRes = info.labelRes;
7093            res.nonLocalizedLabel = info.nonLocalizedLabel;
7094            if (userNeedsBadging(userId)) {
7095                res.noResourceId = true;
7096            } else {
7097                res.icon = info.icon;
7098            }
7099            res.system = isSystemApp(res.activityInfo.applicationInfo);
7100            return res;
7101        }
7102
7103        @Override
7104        protected void sortResults(List<ResolveInfo> results) {
7105            Collections.sort(results, mResolvePrioritySorter);
7106        }
7107
7108        @Override
7109        protected void dumpFilter(PrintWriter out, String prefix,
7110                PackageParser.ActivityIntentInfo filter) {
7111            out.print(prefix); out.print(
7112                    Integer.toHexString(System.identityHashCode(filter.activity)));
7113                    out.print(' ');
7114                    filter.activity.printComponentShortName(out);
7115                    out.print(" filter ");
7116                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7117        }
7118
7119//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7120//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7121//            final List<ResolveInfo> retList = Lists.newArrayList();
7122//            while (i.hasNext()) {
7123//                final ResolveInfo resolveInfo = i.next();
7124//                if (isEnabledLP(resolveInfo.activityInfo)) {
7125//                    retList.add(resolveInfo);
7126//                }
7127//            }
7128//            return retList;
7129//        }
7130
7131        // Keys are String (activity class name), values are Activity.
7132        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7133                = new HashMap<ComponentName, PackageParser.Activity>();
7134        private int mFlags;
7135    }
7136
7137    private final class ServiceIntentResolver
7138            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7139        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7140                boolean defaultOnly, int userId) {
7141            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7142            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7143        }
7144
7145        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7146                int userId) {
7147            if (!sUserManager.exists(userId)) return null;
7148            mFlags = flags;
7149            return super.queryIntent(intent, resolvedType,
7150                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7151        }
7152
7153        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7154                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7155            if (!sUserManager.exists(userId)) return null;
7156            if (packageServices == null) {
7157                return null;
7158            }
7159            mFlags = flags;
7160            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7161            final int N = packageServices.size();
7162            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7163                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7164
7165            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7166            for (int i = 0; i < N; ++i) {
7167                intentFilters = packageServices.get(i).intents;
7168                if (intentFilters != null && intentFilters.size() > 0) {
7169                    PackageParser.ServiceIntentInfo[] array =
7170                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7171                    intentFilters.toArray(array);
7172                    listCut.add(array);
7173                }
7174            }
7175            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7176        }
7177
7178        public final void addService(PackageParser.Service s) {
7179            mServices.put(s.getComponentName(), s);
7180            if (DEBUG_SHOW_INFO) {
7181                Log.v(TAG, "  "
7182                        + (s.info.nonLocalizedLabel != null
7183                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7184                Log.v(TAG, "    Class=" + s.info.name);
7185            }
7186            final int NI = s.intents.size();
7187            int j;
7188            for (j=0; j<NI; j++) {
7189                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7190                if (DEBUG_SHOW_INFO) {
7191                    Log.v(TAG, "    IntentFilter:");
7192                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7193                }
7194                if (!intent.debugCheck()) {
7195                    Log.w(TAG, "==> For Service " + s.info.name);
7196                }
7197                addFilter(intent);
7198            }
7199        }
7200
7201        public final void removeService(PackageParser.Service s) {
7202            mServices.remove(s.getComponentName());
7203            if (DEBUG_SHOW_INFO) {
7204                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7205                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7206                Log.v(TAG, "    Class=" + s.info.name);
7207            }
7208            final int NI = s.intents.size();
7209            int j;
7210            for (j=0; j<NI; j++) {
7211                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7212                if (DEBUG_SHOW_INFO) {
7213                    Log.v(TAG, "    IntentFilter:");
7214                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7215                }
7216                removeFilter(intent);
7217            }
7218        }
7219
7220        @Override
7221        protected boolean allowFilterResult(
7222                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7223            ServiceInfo filterSi = filter.service.info;
7224            for (int i=dest.size()-1; i>=0; i--) {
7225                ServiceInfo destAi = dest.get(i).serviceInfo;
7226                if (destAi.name == filterSi.name
7227                        && destAi.packageName == filterSi.packageName) {
7228                    return false;
7229                }
7230            }
7231            return true;
7232        }
7233
7234        @Override
7235        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7236            return new PackageParser.ServiceIntentInfo[size];
7237        }
7238
7239        @Override
7240        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7241            if (!sUserManager.exists(userId)) return true;
7242            PackageParser.Package p = filter.service.owner;
7243            if (p != null) {
7244                PackageSetting ps = (PackageSetting)p.mExtras;
7245                if (ps != null) {
7246                    // System apps are never considered stopped for purposes of
7247                    // filtering, because there may be no way for the user to
7248                    // actually re-launch them.
7249                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7250                            && ps.getStopped(userId);
7251                }
7252            }
7253            return false;
7254        }
7255
7256        @Override
7257        protected boolean isPackageForFilter(String packageName,
7258                PackageParser.ServiceIntentInfo info) {
7259            return packageName.equals(info.service.owner.packageName);
7260        }
7261
7262        @Override
7263        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7264                int match, int userId) {
7265            if (!sUserManager.exists(userId)) return null;
7266            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7267            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7268                return null;
7269            }
7270            final PackageParser.Service service = info.service;
7271            if (mSafeMode && (service.info.applicationInfo.flags
7272                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7273                return null;
7274            }
7275            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7276            if (ps == null) {
7277                return null;
7278            }
7279            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7280                    ps.readUserState(userId), userId);
7281            if (si == null) {
7282                return null;
7283            }
7284            final ResolveInfo res = new ResolveInfo();
7285            res.serviceInfo = si;
7286            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7287                res.filter = filter;
7288            }
7289            res.priority = info.getPriority();
7290            res.preferredOrder = service.owner.mPreferredOrder;
7291            //System.out.println("Result: " + res.activityInfo.className +
7292            //                   " = " + res.priority);
7293            res.match = match;
7294            res.isDefault = info.hasDefault;
7295            res.labelRes = info.labelRes;
7296            res.nonLocalizedLabel = info.nonLocalizedLabel;
7297            res.icon = info.icon;
7298            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7299            return res;
7300        }
7301
7302        @Override
7303        protected void sortResults(List<ResolveInfo> results) {
7304            Collections.sort(results, mResolvePrioritySorter);
7305        }
7306
7307        @Override
7308        protected void dumpFilter(PrintWriter out, String prefix,
7309                PackageParser.ServiceIntentInfo filter) {
7310            out.print(prefix); out.print(
7311                    Integer.toHexString(System.identityHashCode(filter.service)));
7312                    out.print(' ');
7313                    filter.service.printComponentShortName(out);
7314                    out.print(" filter ");
7315                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7316        }
7317
7318//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7319//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7320//            final List<ResolveInfo> retList = Lists.newArrayList();
7321//            while (i.hasNext()) {
7322//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7323//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7324//                    retList.add(resolveInfo);
7325//                }
7326//            }
7327//            return retList;
7328//        }
7329
7330        // Keys are String (activity class name), values are Activity.
7331        private final HashMap<ComponentName, PackageParser.Service> mServices
7332                = new HashMap<ComponentName, PackageParser.Service>();
7333        private int mFlags;
7334    };
7335
7336    private final class ProviderIntentResolver
7337            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7338        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7339                boolean defaultOnly, int userId) {
7340            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7341            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7342        }
7343
7344        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7345                int userId) {
7346            if (!sUserManager.exists(userId))
7347                return null;
7348            mFlags = flags;
7349            return super.queryIntent(intent, resolvedType,
7350                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7351        }
7352
7353        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7354                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7355            if (!sUserManager.exists(userId))
7356                return null;
7357            if (packageProviders == null) {
7358                return null;
7359            }
7360            mFlags = flags;
7361            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7362            final int N = packageProviders.size();
7363            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7364                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7365
7366            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7367            for (int i = 0; i < N; ++i) {
7368                intentFilters = packageProviders.get(i).intents;
7369                if (intentFilters != null && intentFilters.size() > 0) {
7370                    PackageParser.ProviderIntentInfo[] array =
7371                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7372                    intentFilters.toArray(array);
7373                    listCut.add(array);
7374                }
7375            }
7376            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7377        }
7378
7379        public final void addProvider(PackageParser.Provider p) {
7380            if (mProviders.containsKey(p.getComponentName())) {
7381                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7382                return;
7383            }
7384
7385            mProviders.put(p.getComponentName(), p);
7386            if (DEBUG_SHOW_INFO) {
7387                Log.v(TAG, "  "
7388                        + (p.info.nonLocalizedLabel != null
7389                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7390                Log.v(TAG, "    Class=" + p.info.name);
7391            }
7392            final int NI = p.intents.size();
7393            int j;
7394            for (j = 0; j < NI; j++) {
7395                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7396                if (DEBUG_SHOW_INFO) {
7397                    Log.v(TAG, "    IntentFilter:");
7398                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7399                }
7400                if (!intent.debugCheck()) {
7401                    Log.w(TAG, "==> For Provider " + p.info.name);
7402                }
7403                addFilter(intent);
7404            }
7405        }
7406
7407        public final void removeProvider(PackageParser.Provider p) {
7408            mProviders.remove(p.getComponentName());
7409            if (DEBUG_SHOW_INFO) {
7410                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7411                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7412                Log.v(TAG, "    Class=" + p.info.name);
7413            }
7414            final int NI = p.intents.size();
7415            int j;
7416            for (j = 0; j < NI; j++) {
7417                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7418                if (DEBUG_SHOW_INFO) {
7419                    Log.v(TAG, "    IntentFilter:");
7420                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7421                }
7422                removeFilter(intent);
7423            }
7424        }
7425
7426        @Override
7427        protected boolean allowFilterResult(
7428                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7429            ProviderInfo filterPi = filter.provider.info;
7430            for (int i = dest.size() - 1; i >= 0; i--) {
7431                ProviderInfo destPi = dest.get(i).providerInfo;
7432                if (destPi.name == filterPi.name
7433                        && destPi.packageName == filterPi.packageName) {
7434                    return false;
7435                }
7436            }
7437            return true;
7438        }
7439
7440        @Override
7441        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7442            return new PackageParser.ProviderIntentInfo[size];
7443        }
7444
7445        @Override
7446        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7447            if (!sUserManager.exists(userId))
7448                return true;
7449            PackageParser.Package p = filter.provider.owner;
7450            if (p != null) {
7451                PackageSetting ps = (PackageSetting) p.mExtras;
7452                if (ps != null) {
7453                    // System apps are never considered stopped for purposes of
7454                    // filtering, because there may be no way for the user to
7455                    // actually re-launch them.
7456                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7457                            && ps.getStopped(userId);
7458                }
7459            }
7460            return false;
7461        }
7462
7463        @Override
7464        protected boolean isPackageForFilter(String packageName,
7465                PackageParser.ProviderIntentInfo info) {
7466            return packageName.equals(info.provider.owner.packageName);
7467        }
7468
7469        @Override
7470        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7471                int match, int userId) {
7472            if (!sUserManager.exists(userId))
7473                return null;
7474            final PackageParser.ProviderIntentInfo info = filter;
7475            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7476                return null;
7477            }
7478            final PackageParser.Provider provider = info.provider;
7479            if (mSafeMode && (provider.info.applicationInfo.flags
7480                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7481                return null;
7482            }
7483            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7484            if (ps == null) {
7485                return null;
7486            }
7487            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7488                    ps.readUserState(userId), userId);
7489            if (pi == null) {
7490                return null;
7491            }
7492            final ResolveInfo res = new ResolveInfo();
7493            res.providerInfo = pi;
7494            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7495                res.filter = filter;
7496            }
7497            res.priority = info.getPriority();
7498            res.preferredOrder = provider.owner.mPreferredOrder;
7499            res.match = match;
7500            res.isDefault = info.hasDefault;
7501            res.labelRes = info.labelRes;
7502            res.nonLocalizedLabel = info.nonLocalizedLabel;
7503            res.icon = info.icon;
7504            res.system = isSystemApp(res.providerInfo.applicationInfo);
7505            return res;
7506        }
7507
7508        @Override
7509        protected void sortResults(List<ResolveInfo> results) {
7510            Collections.sort(results, mResolvePrioritySorter);
7511        }
7512
7513        @Override
7514        protected void dumpFilter(PrintWriter out, String prefix,
7515                PackageParser.ProviderIntentInfo filter) {
7516            out.print(prefix);
7517            out.print(
7518                    Integer.toHexString(System.identityHashCode(filter.provider)));
7519            out.print(' ');
7520            filter.provider.printComponentShortName(out);
7521            out.print(" filter ");
7522            out.println(Integer.toHexString(System.identityHashCode(filter)));
7523        }
7524
7525        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7526                = new HashMap<ComponentName, PackageParser.Provider>();
7527        private int mFlags;
7528    };
7529
7530    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7531            new Comparator<ResolveInfo>() {
7532        public int compare(ResolveInfo r1, ResolveInfo r2) {
7533            int v1 = r1.priority;
7534            int v2 = r2.priority;
7535            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7536            if (v1 != v2) {
7537                return (v1 > v2) ? -1 : 1;
7538            }
7539            v1 = r1.preferredOrder;
7540            v2 = r2.preferredOrder;
7541            if (v1 != v2) {
7542                return (v1 > v2) ? -1 : 1;
7543            }
7544            if (r1.isDefault != r2.isDefault) {
7545                return r1.isDefault ? -1 : 1;
7546            }
7547            v1 = r1.match;
7548            v2 = r2.match;
7549            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7550            if (v1 != v2) {
7551                return (v1 > v2) ? -1 : 1;
7552            }
7553            if (r1.system != r2.system) {
7554                return r1.system ? -1 : 1;
7555            }
7556            return 0;
7557        }
7558    };
7559
7560    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7561            new Comparator<ProviderInfo>() {
7562        public int compare(ProviderInfo p1, ProviderInfo p2) {
7563            final int v1 = p1.initOrder;
7564            final int v2 = p2.initOrder;
7565            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7566        }
7567    };
7568
7569    static final void sendPackageBroadcast(String action, String pkg,
7570            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7571            int[] userIds) {
7572        IActivityManager am = ActivityManagerNative.getDefault();
7573        if (am != null) {
7574            try {
7575                if (userIds == null) {
7576                    userIds = am.getRunningUserIds();
7577                }
7578                for (int id : userIds) {
7579                    final Intent intent = new Intent(action,
7580                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7581                    if (extras != null) {
7582                        intent.putExtras(extras);
7583                    }
7584                    if (targetPkg != null) {
7585                        intent.setPackage(targetPkg);
7586                    }
7587                    // Modify the UID when posting to other users
7588                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7589                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7590                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7591                        intent.putExtra(Intent.EXTRA_UID, uid);
7592                    }
7593                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7594                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7595                    if (DEBUG_BROADCASTS) {
7596                        RuntimeException here = new RuntimeException("here");
7597                        here.fillInStackTrace();
7598                        Slog.d(TAG, "Sending to user " + id + ": "
7599                                + intent.toShortString(false, true, false, false)
7600                                + " " + intent.getExtras(), here);
7601                    }
7602                    am.broadcastIntent(null, intent, null, finishedReceiver,
7603                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7604                            finishedReceiver != null, false, id);
7605                }
7606            } catch (RemoteException ex) {
7607            }
7608        }
7609    }
7610
7611    /**
7612     * Check if the external storage media is available. This is true if there
7613     * is a mounted external storage medium or if the external storage is
7614     * emulated.
7615     */
7616    private boolean isExternalMediaAvailable() {
7617        return mMediaMounted || Environment.isExternalStorageEmulated();
7618    }
7619
7620    @Override
7621    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7622        // writer
7623        synchronized (mPackages) {
7624            if (!isExternalMediaAvailable()) {
7625                // If the external storage is no longer mounted at this point,
7626                // the caller may not have been able to delete all of this
7627                // packages files and can not delete any more.  Bail.
7628                return null;
7629            }
7630            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7631            if (lastPackage != null) {
7632                pkgs.remove(lastPackage);
7633            }
7634            if (pkgs.size() > 0) {
7635                return pkgs.get(0);
7636            }
7637        }
7638        return null;
7639    }
7640
7641    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7642        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7643                userId, andCode ? 1 : 0, packageName);
7644        if (mSystemReady) {
7645            msg.sendToTarget();
7646        } else {
7647            if (mPostSystemReadyMessages == null) {
7648                mPostSystemReadyMessages = new ArrayList<>();
7649            }
7650            mPostSystemReadyMessages.add(msg);
7651        }
7652    }
7653
7654    void startCleaningPackages() {
7655        // reader
7656        synchronized (mPackages) {
7657            if (!isExternalMediaAvailable()) {
7658                return;
7659            }
7660            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7661                return;
7662            }
7663        }
7664        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7665        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7666        IActivityManager am = ActivityManagerNative.getDefault();
7667        if (am != null) {
7668            try {
7669                am.startService(null, intent, null, UserHandle.USER_OWNER);
7670            } catch (RemoteException e) {
7671            }
7672        }
7673    }
7674
7675    @Override
7676    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7677            int installFlags, String installerPackageName, VerificationParams verificationParams,
7678            String packageAbiOverride) {
7679        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7680                packageAbiOverride, UserHandle.getCallingUserId());
7681    }
7682
7683    @Override
7684    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7685            int installFlags, String installerPackageName, VerificationParams verificationParams,
7686            String packageAbiOverride, int userId) {
7687        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7688
7689        final int callingUid = Binder.getCallingUid();
7690        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7691
7692        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7693            try {
7694                if (observer != null) {
7695                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7696                }
7697            } catch (RemoteException re) {
7698            }
7699            return;
7700        }
7701
7702        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7703            installFlags |= PackageManager.INSTALL_FROM_ADB;
7704
7705        } else {
7706            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7707            // about installerPackageName.
7708
7709            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7710            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7711        }
7712
7713        UserHandle user;
7714        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7715            user = UserHandle.ALL;
7716        } else {
7717            user = new UserHandle(userId);
7718        }
7719
7720        verificationParams.setInstallerUid(callingUid);
7721
7722        final File originFile = new File(originPath);
7723        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7724
7725        final Message msg = mHandler.obtainMessage(INIT_COPY);
7726        msg.obj = new InstallParams(origin, observer, installFlags,
7727                installerPackageName, verificationParams, user, packageAbiOverride);
7728        mHandler.sendMessage(msg);
7729    }
7730
7731    void installStage(String packageName, File stagedDir, String stagedCid,
7732            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7733            String installerPackageName, int installerUid, UserHandle user) {
7734        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7735                params.referrerUri, installerUid, null);
7736
7737        final OriginInfo origin;
7738        if (stagedDir != null) {
7739            origin = OriginInfo.fromStagedFile(stagedDir);
7740        } else {
7741            origin = OriginInfo.fromStagedContainer(stagedCid);
7742        }
7743
7744        final Message msg = mHandler.obtainMessage(INIT_COPY);
7745        msg.obj = new InstallParams(origin, observer, params.installFlags,
7746                installerPackageName, verifParams, user, params.abiOverride);
7747        mHandler.sendMessage(msg);
7748    }
7749
7750    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7751        Bundle extras = new Bundle(1);
7752        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7753
7754        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7755                packageName, extras, null, null, new int[] {userId});
7756        try {
7757            IActivityManager am = ActivityManagerNative.getDefault();
7758            final boolean isSystem =
7759                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7760            if (isSystem && am.isUserRunning(userId, false)) {
7761                // The just-installed/enabled app is bundled on the system, so presumed
7762                // to be able to run automatically without needing an explicit launch.
7763                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7764                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7765                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7766                        .setPackage(packageName);
7767                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7768                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7769            }
7770        } catch (RemoteException e) {
7771            // shouldn't happen
7772            Slog.w(TAG, "Unable to bootstrap installed package", e);
7773        }
7774    }
7775
7776    @Override
7777    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7778            int userId) {
7779        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7780        PackageSetting pkgSetting;
7781        final int uid = Binder.getCallingUid();
7782        enforceCrossUserPermission(uid, userId, true, true,
7783                "setApplicationHiddenSetting for user " + userId);
7784
7785        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7786            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7787            return false;
7788        }
7789
7790        long callingId = Binder.clearCallingIdentity();
7791        try {
7792            boolean sendAdded = false;
7793            boolean sendRemoved = false;
7794            // writer
7795            synchronized (mPackages) {
7796                pkgSetting = mSettings.mPackages.get(packageName);
7797                if (pkgSetting == null) {
7798                    return false;
7799                }
7800                if (pkgSetting.getHidden(userId) != hidden) {
7801                    pkgSetting.setHidden(hidden, userId);
7802                    mSettings.writePackageRestrictionsLPr(userId);
7803                    if (hidden) {
7804                        sendRemoved = true;
7805                    } else {
7806                        sendAdded = true;
7807                    }
7808                }
7809            }
7810            if (sendAdded) {
7811                sendPackageAddedForUser(packageName, pkgSetting, userId);
7812                return true;
7813            }
7814            if (sendRemoved) {
7815                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7816                        "hiding pkg");
7817                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7818            }
7819        } finally {
7820            Binder.restoreCallingIdentity(callingId);
7821        }
7822        return false;
7823    }
7824
7825    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7826            int userId) {
7827        final PackageRemovedInfo info = new PackageRemovedInfo();
7828        info.removedPackage = packageName;
7829        info.removedUsers = new int[] {userId};
7830        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7831        info.sendBroadcast(false, false, false);
7832    }
7833
7834    /**
7835     * Returns true if application is not found or there was an error. Otherwise it returns
7836     * the hidden state of the package for the given user.
7837     */
7838    @Override
7839    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7840        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7841        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7842                false, "getApplicationHidden for user " + userId);
7843        PackageSetting pkgSetting;
7844        long callingId = Binder.clearCallingIdentity();
7845        try {
7846            // writer
7847            synchronized (mPackages) {
7848                pkgSetting = mSettings.mPackages.get(packageName);
7849                if (pkgSetting == null) {
7850                    return true;
7851                }
7852                return pkgSetting.getHidden(userId);
7853            }
7854        } finally {
7855            Binder.restoreCallingIdentity(callingId);
7856        }
7857    }
7858
7859    /**
7860     * @hide
7861     */
7862    @Override
7863    public int installExistingPackageAsUser(String packageName, int userId) {
7864        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7865                null);
7866        PackageSetting pkgSetting;
7867        final int uid = Binder.getCallingUid();
7868        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7869                + userId);
7870        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7871            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7872        }
7873
7874        long callingId = Binder.clearCallingIdentity();
7875        try {
7876            boolean sendAdded = false;
7877            Bundle extras = new Bundle(1);
7878
7879            // writer
7880            synchronized (mPackages) {
7881                pkgSetting = mSettings.mPackages.get(packageName);
7882                if (pkgSetting == null) {
7883                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7884                }
7885                if (!pkgSetting.getInstalled(userId)) {
7886                    pkgSetting.setInstalled(true, userId);
7887                    pkgSetting.setHidden(false, userId);
7888                    mSettings.writePackageRestrictionsLPr(userId);
7889                    sendAdded = true;
7890                }
7891            }
7892
7893            if (sendAdded) {
7894                sendPackageAddedForUser(packageName, pkgSetting, userId);
7895            }
7896        } finally {
7897            Binder.restoreCallingIdentity(callingId);
7898        }
7899
7900        return PackageManager.INSTALL_SUCCEEDED;
7901    }
7902
7903    boolean isUserRestricted(int userId, String restrictionKey) {
7904        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7905        if (restrictions.getBoolean(restrictionKey, false)) {
7906            Log.w(TAG, "User is restricted: " + restrictionKey);
7907            return true;
7908        }
7909        return false;
7910    }
7911
7912    @Override
7913    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7914        mContext.enforceCallingOrSelfPermission(
7915                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7916                "Only package verification agents can verify applications");
7917
7918        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7919        final PackageVerificationResponse response = new PackageVerificationResponse(
7920                verificationCode, Binder.getCallingUid());
7921        msg.arg1 = id;
7922        msg.obj = response;
7923        mHandler.sendMessage(msg);
7924    }
7925
7926    @Override
7927    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7928            long millisecondsToDelay) {
7929        mContext.enforceCallingOrSelfPermission(
7930                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7931                "Only package verification agents can extend verification timeouts");
7932
7933        final PackageVerificationState state = mPendingVerification.get(id);
7934        final PackageVerificationResponse response = new PackageVerificationResponse(
7935                verificationCodeAtTimeout, Binder.getCallingUid());
7936
7937        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7938            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7939        }
7940        if (millisecondsToDelay < 0) {
7941            millisecondsToDelay = 0;
7942        }
7943        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7944                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7945            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7946        }
7947
7948        if ((state != null) && !state.timeoutExtended()) {
7949            state.extendTimeout();
7950
7951            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7952            msg.arg1 = id;
7953            msg.obj = response;
7954            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7955        }
7956    }
7957
7958    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7959            int verificationCode, UserHandle user) {
7960        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7961        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7962        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7963        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7964        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7965
7966        mContext.sendBroadcastAsUser(intent, user,
7967                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7968    }
7969
7970    private ComponentName matchComponentForVerifier(String packageName,
7971            List<ResolveInfo> receivers) {
7972        ActivityInfo targetReceiver = null;
7973
7974        final int NR = receivers.size();
7975        for (int i = 0; i < NR; i++) {
7976            final ResolveInfo info = receivers.get(i);
7977            if (info.activityInfo == null) {
7978                continue;
7979            }
7980
7981            if (packageName.equals(info.activityInfo.packageName)) {
7982                targetReceiver = info.activityInfo;
7983                break;
7984            }
7985        }
7986
7987        if (targetReceiver == null) {
7988            return null;
7989        }
7990
7991        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7992    }
7993
7994    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7995            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7996        if (pkgInfo.verifiers.length == 0) {
7997            return null;
7998        }
7999
8000        final int N = pkgInfo.verifiers.length;
8001        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8002        for (int i = 0; i < N; i++) {
8003            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8004
8005            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8006                    receivers);
8007            if (comp == null) {
8008                continue;
8009            }
8010
8011            final int verifierUid = getUidForVerifier(verifierInfo);
8012            if (verifierUid == -1) {
8013                continue;
8014            }
8015
8016            if (DEBUG_VERIFY) {
8017                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8018                        + " with the correct signature");
8019            }
8020            sufficientVerifiers.add(comp);
8021            verificationState.addSufficientVerifier(verifierUid);
8022        }
8023
8024        return sufficientVerifiers;
8025    }
8026
8027    private int getUidForVerifier(VerifierInfo verifierInfo) {
8028        synchronized (mPackages) {
8029            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8030            if (pkg == null) {
8031                return -1;
8032            } else if (pkg.mSignatures.length != 1) {
8033                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8034                        + " has more than one signature; ignoring");
8035                return -1;
8036            }
8037
8038            /*
8039             * If the public key of the package's signature does not match
8040             * our expected public key, then this is a different package and
8041             * we should skip.
8042             */
8043
8044            final byte[] expectedPublicKey;
8045            try {
8046                final Signature verifierSig = pkg.mSignatures[0];
8047                final PublicKey publicKey = verifierSig.getPublicKey();
8048                expectedPublicKey = publicKey.getEncoded();
8049            } catch (CertificateException e) {
8050                return -1;
8051            }
8052
8053            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8054
8055            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8056                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8057                        + " does not have the expected public key; ignoring");
8058                return -1;
8059            }
8060
8061            return pkg.applicationInfo.uid;
8062        }
8063    }
8064
8065    @Override
8066    public void finishPackageInstall(int token) {
8067        enforceSystemOrRoot("Only the system is allowed to finish installs");
8068
8069        if (DEBUG_INSTALL) {
8070            Slog.v(TAG, "BM finishing package install for " + token);
8071        }
8072
8073        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8074        mHandler.sendMessage(msg);
8075    }
8076
8077    /**
8078     * Get the verification agent timeout.
8079     *
8080     * @return verification timeout in milliseconds
8081     */
8082    private long getVerificationTimeout() {
8083        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8084                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8085                DEFAULT_VERIFICATION_TIMEOUT);
8086    }
8087
8088    /**
8089     * Get the default verification agent response code.
8090     *
8091     * @return default verification response code
8092     */
8093    private int getDefaultVerificationResponse() {
8094        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8095                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8096                DEFAULT_VERIFICATION_RESPONSE);
8097    }
8098
8099    /**
8100     * Check whether or not package verification has been enabled.
8101     *
8102     * @return true if verification should be performed
8103     */
8104    private boolean isVerificationEnabled(int userId, int installFlags) {
8105        if (!DEFAULT_VERIFY_ENABLE) {
8106            return false;
8107        }
8108
8109        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8110
8111        // Check if installing from ADB
8112        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8113            // Do not run verification in a test harness environment
8114            if (ActivityManager.isRunningInTestHarness()) {
8115                return false;
8116            }
8117            if (ensureVerifyAppsEnabled) {
8118                return true;
8119            }
8120            // Check if the developer does not want package verification for ADB installs
8121            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8122                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8123                return false;
8124            }
8125        }
8126
8127        if (ensureVerifyAppsEnabled) {
8128            return true;
8129        }
8130
8131        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8132                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8133    }
8134
8135    /**
8136     * Get the "allow unknown sources" setting.
8137     *
8138     * @return the current "allow unknown sources" setting
8139     */
8140    private int getUnknownSourcesSettings() {
8141        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8142                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8143                -1);
8144    }
8145
8146    @Override
8147    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8148        final int uid = Binder.getCallingUid();
8149        // writer
8150        synchronized (mPackages) {
8151            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8152            if (targetPackageSetting == null) {
8153                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8154            }
8155
8156            PackageSetting installerPackageSetting;
8157            if (installerPackageName != null) {
8158                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8159                if (installerPackageSetting == null) {
8160                    throw new IllegalArgumentException("Unknown installer package: "
8161                            + installerPackageName);
8162                }
8163            } else {
8164                installerPackageSetting = null;
8165            }
8166
8167            Signature[] callerSignature;
8168            Object obj = mSettings.getUserIdLPr(uid);
8169            if (obj != null) {
8170                if (obj instanceof SharedUserSetting) {
8171                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8172                } else if (obj instanceof PackageSetting) {
8173                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8174                } else {
8175                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8176                }
8177            } else {
8178                throw new SecurityException("Unknown calling uid " + uid);
8179            }
8180
8181            // Verify: can't set installerPackageName to a package that is
8182            // not signed with the same cert as the caller.
8183            if (installerPackageSetting != null) {
8184                if (compareSignatures(callerSignature,
8185                        installerPackageSetting.signatures.mSignatures)
8186                        != PackageManager.SIGNATURE_MATCH) {
8187                    throw new SecurityException(
8188                            "Caller does not have same cert as new installer package "
8189                            + installerPackageName);
8190                }
8191            }
8192
8193            // Verify: if target already has an installer package, it must
8194            // be signed with the same cert as the caller.
8195            if (targetPackageSetting.installerPackageName != null) {
8196                PackageSetting setting = mSettings.mPackages.get(
8197                        targetPackageSetting.installerPackageName);
8198                // If the currently set package isn't valid, then it's always
8199                // okay to change it.
8200                if (setting != null) {
8201                    if (compareSignatures(callerSignature,
8202                            setting.signatures.mSignatures)
8203                            != PackageManager.SIGNATURE_MATCH) {
8204                        throw new SecurityException(
8205                                "Caller does not have same cert as old installer package "
8206                                + targetPackageSetting.installerPackageName);
8207                    }
8208                }
8209            }
8210
8211            // Okay!
8212            targetPackageSetting.installerPackageName = installerPackageName;
8213            scheduleWriteSettingsLocked();
8214        }
8215    }
8216
8217    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8218        // Queue up an async operation since the package installation may take a little while.
8219        mHandler.post(new Runnable() {
8220            public void run() {
8221                mHandler.removeCallbacks(this);
8222                 // Result object to be returned
8223                PackageInstalledInfo res = new PackageInstalledInfo();
8224                res.returnCode = currentStatus;
8225                res.uid = -1;
8226                res.pkg = null;
8227                res.removedInfo = new PackageRemovedInfo();
8228                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8229                    args.doPreInstall(res.returnCode);
8230                    synchronized (mInstallLock) {
8231                        installPackageLI(args, res);
8232                    }
8233                    args.doPostInstall(res.returnCode, res.uid);
8234                }
8235
8236                // A restore should be performed at this point if (a) the install
8237                // succeeded, (b) the operation is not an update, and (c) the new
8238                // package has not opted out of backup participation.
8239                final boolean update = res.removedInfo.removedPackage != null;
8240                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8241                boolean doRestore = !update
8242                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8243
8244                // Set up the post-install work request bookkeeping.  This will be used
8245                // and cleaned up by the post-install event handling regardless of whether
8246                // there's a restore pass performed.  Token values are >= 1.
8247                int token;
8248                if (mNextInstallToken < 0) mNextInstallToken = 1;
8249                token = mNextInstallToken++;
8250
8251                PostInstallData data = new PostInstallData(args, res);
8252                mRunningInstalls.put(token, data);
8253                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8254
8255                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8256                    // Pass responsibility to the Backup Manager.  It will perform a
8257                    // restore if appropriate, then pass responsibility back to the
8258                    // Package Manager to run the post-install observer callbacks
8259                    // and broadcasts.
8260                    IBackupManager bm = IBackupManager.Stub.asInterface(
8261                            ServiceManager.getService(Context.BACKUP_SERVICE));
8262                    if (bm != null) {
8263                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8264                                + " to BM for possible restore");
8265                        try {
8266                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8267                        } catch (RemoteException e) {
8268                            // can't happen; the backup manager is local
8269                        } catch (Exception e) {
8270                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8271                            doRestore = false;
8272                        }
8273                    } else {
8274                        Slog.e(TAG, "Backup Manager not found!");
8275                        doRestore = false;
8276                    }
8277                }
8278
8279                if (!doRestore) {
8280                    // No restore possible, or the Backup Manager was mysteriously not
8281                    // available -- just fire the post-install work request directly.
8282                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8283                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8284                    mHandler.sendMessage(msg);
8285                }
8286            }
8287        });
8288    }
8289
8290    private abstract class HandlerParams {
8291        private static final int MAX_RETRIES = 4;
8292
8293        /**
8294         * Number of times startCopy() has been attempted and had a non-fatal
8295         * error.
8296         */
8297        private int mRetries = 0;
8298
8299        /** User handle for the user requesting the information or installation. */
8300        private final UserHandle mUser;
8301
8302        HandlerParams(UserHandle user) {
8303            mUser = user;
8304        }
8305
8306        UserHandle getUser() {
8307            return mUser;
8308        }
8309
8310        final boolean startCopy() {
8311            boolean res;
8312            try {
8313                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8314
8315                if (++mRetries > MAX_RETRIES) {
8316                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8317                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8318                    handleServiceError();
8319                    return false;
8320                } else {
8321                    handleStartCopy();
8322                    res = true;
8323                }
8324            } catch (RemoteException e) {
8325                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8326                mHandler.sendEmptyMessage(MCS_RECONNECT);
8327                res = false;
8328            }
8329            handleReturnCode();
8330            return res;
8331        }
8332
8333        final void serviceError() {
8334            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8335            handleServiceError();
8336            handleReturnCode();
8337        }
8338
8339        abstract void handleStartCopy() throws RemoteException;
8340        abstract void handleServiceError();
8341        abstract void handleReturnCode();
8342    }
8343
8344    class MeasureParams extends HandlerParams {
8345        private final PackageStats mStats;
8346        private boolean mSuccess;
8347
8348        private final IPackageStatsObserver mObserver;
8349
8350        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8351            super(new UserHandle(stats.userHandle));
8352            mObserver = observer;
8353            mStats = stats;
8354        }
8355
8356        @Override
8357        public String toString() {
8358            return "MeasureParams{"
8359                + Integer.toHexString(System.identityHashCode(this))
8360                + " " + mStats.packageName + "}";
8361        }
8362
8363        @Override
8364        void handleStartCopy() throws RemoteException {
8365            synchronized (mInstallLock) {
8366                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8367            }
8368
8369            if (mSuccess) {
8370                final boolean mounted;
8371                if (Environment.isExternalStorageEmulated()) {
8372                    mounted = true;
8373                } else {
8374                    final String status = Environment.getExternalStorageState();
8375                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8376                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8377                }
8378
8379                if (mounted) {
8380                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8381
8382                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8383                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8384
8385                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8386                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8387
8388                    // Always subtract cache size, since it's a subdirectory
8389                    mStats.externalDataSize -= mStats.externalCacheSize;
8390
8391                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8392                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8393
8394                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8395                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8396                }
8397            }
8398        }
8399
8400        @Override
8401        void handleReturnCode() {
8402            if (mObserver != null) {
8403                try {
8404                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8405                } catch (RemoteException e) {
8406                    Slog.i(TAG, "Observer no longer exists.");
8407                }
8408            }
8409        }
8410
8411        @Override
8412        void handleServiceError() {
8413            Slog.e(TAG, "Could not measure application " + mStats.packageName
8414                            + " external storage");
8415        }
8416    }
8417
8418    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8419            throws RemoteException {
8420        long result = 0;
8421        for (File path : paths) {
8422            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8423        }
8424        return result;
8425    }
8426
8427    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8428        for (File path : paths) {
8429            try {
8430                mcs.clearDirectory(path.getAbsolutePath());
8431            } catch (RemoteException e) {
8432            }
8433        }
8434    }
8435
8436    static class OriginInfo {
8437        /**
8438         * Location where install is coming from, before it has been
8439         * copied/renamed into place. This could be a single monolithic APK
8440         * file, or a cluster directory. This location may be untrusted.
8441         */
8442        final File file;
8443        final String cid;
8444
8445        /**
8446         * Flag indicating that {@link #file} or {@link #cid} has already been
8447         * staged, meaning downstream users don't need to defensively copy the
8448         * contents.
8449         */
8450        final boolean staged;
8451
8452        /**
8453         * Flag indicating that {@link #file} or {@link #cid} is an already
8454         * installed app that is being moved.
8455         */
8456        final boolean existing;
8457
8458        final String resolvedPath;
8459        final File resolvedFile;
8460
8461        static OriginInfo fromNothing() {
8462            return new OriginInfo(null, null, false, false);
8463        }
8464
8465        static OriginInfo fromUntrustedFile(File file) {
8466            return new OriginInfo(file, null, false, false);
8467        }
8468
8469        static OriginInfo fromExistingFile(File file) {
8470            return new OriginInfo(file, null, false, true);
8471        }
8472
8473        static OriginInfo fromStagedFile(File file) {
8474            return new OriginInfo(file, null, true, false);
8475        }
8476
8477        static OriginInfo fromStagedContainer(String cid) {
8478            return new OriginInfo(null, cid, true, false);
8479        }
8480
8481        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8482            this.file = file;
8483            this.cid = cid;
8484            this.staged = staged;
8485            this.existing = existing;
8486
8487            if (cid != null) {
8488                resolvedPath = PackageHelper.getSdDir(cid);
8489                resolvedFile = new File(resolvedPath);
8490            } else if (file != null) {
8491                resolvedPath = file.getAbsolutePath();
8492                resolvedFile = file;
8493            } else {
8494                resolvedPath = null;
8495                resolvedFile = null;
8496            }
8497        }
8498    }
8499
8500    class InstallParams extends HandlerParams {
8501        final OriginInfo origin;
8502        final IPackageInstallObserver2 observer;
8503        int installFlags;
8504        final String installerPackageName;
8505        final VerificationParams verificationParams;
8506        private InstallArgs mArgs;
8507        private int mRet;
8508        final String packageAbiOverride;
8509
8510        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8511                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8512                String packageAbiOverride) {
8513            super(user);
8514            this.origin = origin;
8515            this.observer = observer;
8516            this.installFlags = installFlags;
8517            this.installerPackageName = installerPackageName;
8518            this.verificationParams = verificationParams;
8519            this.packageAbiOverride = packageAbiOverride;
8520        }
8521
8522        @Override
8523        public String toString() {
8524            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8525                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8526        }
8527
8528        public ManifestDigest getManifestDigest() {
8529            if (verificationParams == null) {
8530                return null;
8531            }
8532            return verificationParams.getManifestDigest();
8533        }
8534
8535        private int installLocationPolicy(PackageInfoLite pkgLite) {
8536            String packageName = pkgLite.packageName;
8537            int installLocation = pkgLite.installLocation;
8538            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8539            // reader
8540            synchronized (mPackages) {
8541                PackageParser.Package pkg = mPackages.get(packageName);
8542                if (pkg != null) {
8543                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8544                        // Check for downgrading.
8545                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8546                            if (pkgLite.versionCode < pkg.mVersionCode) {
8547                                Slog.w(TAG, "Can't install update of " + packageName
8548                                        + " update version " + pkgLite.versionCode
8549                                        + " is older than installed version "
8550                                        + pkg.mVersionCode);
8551                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8552                            }
8553                        }
8554                        // Check for updated system application.
8555                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8556                            if (onSd) {
8557                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8558                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8559                            }
8560                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8561                        } else {
8562                            if (onSd) {
8563                                // Install flag overrides everything.
8564                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8565                            }
8566                            // If current upgrade specifies particular preference
8567                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8568                                // Application explicitly specified internal.
8569                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8570                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8571                                // App explictly prefers external. Let policy decide
8572                            } else {
8573                                // Prefer previous location
8574                                if (isExternal(pkg)) {
8575                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8576                                }
8577                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8578                            }
8579                        }
8580                    } else {
8581                        // Invalid install. Return error code
8582                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8583                    }
8584                }
8585            }
8586            // All the special cases have been taken care of.
8587            // Return result based on recommended install location.
8588            if (onSd) {
8589                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8590            }
8591            return pkgLite.recommendedInstallLocation;
8592        }
8593
8594        /*
8595         * Invoke remote method to get package information and install
8596         * location values. Override install location based on default
8597         * policy if needed and then create install arguments based
8598         * on the install location.
8599         */
8600        public void handleStartCopy() throws RemoteException {
8601            int ret = PackageManager.INSTALL_SUCCEEDED;
8602
8603            // If we're already staged, we've firmly committed to an install location
8604            if (origin.staged) {
8605                if (origin.file != null) {
8606                    installFlags |= PackageManager.INSTALL_INTERNAL;
8607                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8608                } else if (origin.cid != null) {
8609                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8610                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8611                } else {
8612                    throw new IllegalStateException("Invalid stage location");
8613                }
8614            }
8615
8616            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8617            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8618
8619            PackageInfoLite pkgLite = null;
8620
8621            if (onInt && onSd) {
8622                // Check if both bits are set.
8623                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8624                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8625            } else {
8626                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8627                        packageAbiOverride);
8628
8629                /*
8630                 * If we have too little free space, try to free cache
8631                 * before giving up.
8632                 */
8633                if (!origin.staged && pkgLite.recommendedInstallLocation
8634                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8635                    // TODO: focus freeing disk space on the target device
8636                    final StorageManager storage = StorageManager.from(mContext);
8637                    final long lowThreshold = storage.getStorageLowBytes(
8638                            Environment.getDataDirectory());
8639
8640                    final long sizeBytes = mContainerService.calculateInstalledSize(
8641                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8642
8643                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8644                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8645                                installFlags, packageAbiOverride);
8646                    }
8647
8648                    /*
8649                     * The cache free must have deleted the file we
8650                     * downloaded to install.
8651                     *
8652                     * TODO: fix the "freeCache" call to not delete
8653                     *       the file we care about.
8654                     */
8655                    if (pkgLite.recommendedInstallLocation
8656                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8657                        pkgLite.recommendedInstallLocation
8658                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8659                    }
8660                }
8661            }
8662
8663            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8664                int loc = pkgLite.recommendedInstallLocation;
8665                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8666                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8667                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8668                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8669                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8670                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8671                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8672                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8673                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8674                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8675                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8676                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8677                } else {
8678                    // Override with defaults if needed.
8679                    loc = installLocationPolicy(pkgLite);
8680                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8681                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8682                    } else if (!onSd && !onInt) {
8683                        // Override install location with flags
8684                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8685                            // Set the flag to install on external media.
8686                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8687                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8688                        } else {
8689                            // Make sure the flag for installing on external
8690                            // media is unset
8691                            installFlags |= PackageManager.INSTALL_INTERNAL;
8692                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8693                        }
8694                    }
8695                }
8696            }
8697
8698            final InstallArgs args = createInstallArgs(this);
8699            mArgs = args;
8700
8701            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8702                 /*
8703                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8704                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8705                 */
8706                int userIdentifier = getUser().getIdentifier();
8707                if (userIdentifier == UserHandle.USER_ALL
8708                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8709                    userIdentifier = UserHandle.USER_OWNER;
8710                }
8711
8712                /*
8713                 * Determine if we have any installed package verifiers. If we
8714                 * do, then we'll defer to them to verify the packages.
8715                 */
8716                final int requiredUid = mRequiredVerifierPackage == null ? -1
8717                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8718                if (!origin.existing && requiredUid != -1
8719                        && isVerificationEnabled(userIdentifier, installFlags)) {
8720                    final Intent verification = new Intent(
8721                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8722                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8723                            PACKAGE_MIME_TYPE);
8724                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8725
8726                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8727                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8728                            0 /* TODO: Which userId? */);
8729
8730                    if (DEBUG_VERIFY) {
8731                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8732                                + verification.toString() + " with " + pkgLite.verifiers.length
8733                                + " optional verifiers");
8734                    }
8735
8736                    final int verificationId = mPendingVerificationToken++;
8737
8738                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8739
8740                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8741                            installerPackageName);
8742
8743                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8744                            installFlags);
8745
8746                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8747                            pkgLite.packageName);
8748
8749                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8750                            pkgLite.versionCode);
8751
8752                    if (verificationParams != null) {
8753                        if (verificationParams.getVerificationURI() != null) {
8754                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8755                                 verificationParams.getVerificationURI());
8756                        }
8757                        if (verificationParams.getOriginatingURI() != null) {
8758                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8759                                  verificationParams.getOriginatingURI());
8760                        }
8761                        if (verificationParams.getReferrer() != null) {
8762                            verification.putExtra(Intent.EXTRA_REFERRER,
8763                                  verificationParams.getReferrer());
8764                        }
8765                        if (verificationParams.getOriginatingUid() >= 0) {
8766                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8767                                  verificationParams.getOriginatingUid());
8768                        }
8769                        if (verificationParams.getInstallerUid() >= 0) {
8770                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8771                                  verificationParams.getInstallerUid());
8772                        }
8773                    }
8774
8775                    final PackageVerificationState verificationState = new PackageVerificationState(
8776                            requiredUid, args);
8777
8778                    mPendingVerification.append(verificationId, verificationState);
8779
8780                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8781                            receivers, verificationState);
8782
8783                    /*
8784                     * If any sufficient verifiers were listed in the package
8785                     * manifest, attempt to ask them.
8786                     */
8787                    if (sufficientVerifiers != null) {
8788                        final int N = sufficientVerifiers.size();
8789                        if (N == 0) {
8790                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8791                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8792                        } else {
8793                            for (int i = 0; i < N; i++) {
8794                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8795
8796                                final Intent sufficientIntent = new Intent(verification);
8797                                sufficientIntent.setComponent(verifierComponent);
8798
8799                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8800                            }
8801                        }
8802                    }
8803
8804                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8805                            mRequiredVerifierPackage, receivers);
8806                    if (ret == PackageManager.INSTALL_SUCCEEDED
8807                            && mRequiredVerifierPackage != null) {
8808                        /*
8809                         * Send the intent to the required verification agent,
8810                         * but only start the verification timeout after the
8811                         * target BroadcastReceivers have run.
8812                         */
8813                        verification.setComponent(requiredVerifierComponent);
8814                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8815                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8816                                new BroadcastReceiver() {
8817                                    @Override
8818                                    public void onReceive(Context context, Intent intent) {
8819                                        final Message msg = mHandler
8820                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8821                                        msg.arg1 = verificationId;
8822                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8823                                    }
8824                                }, null, 0, null, null);
8825
8826                        /*
8827                         * We don't want the copy to proceed until verification
8828                         * succeeds, so null out this field.
8829                         */
8830                        mArgs = null;
8831                    }
8832                } else {
8833                    /*
8834                     * No package verification is enabled, so immediately start
8835                     * the remote call to initiate copy using temporary file.
8836                     */
8837                    ret = args.copyApk(mContainerService, true);
8838                }
8839            }
8840
8841            mRet = ret;
8842        }
8843
8844        @Override
8845        void handleReturnCode() {
8846            // If mArgs is null, then MCS couldn't be reached. When it
8847            // reconnects, it will try again to install. At that point, this
8848            // will succeed.
8849            if (mArgs != null) {
8850                processPendingInstall(mArgs, mRet);
8851            }
8852        }
8853
8854        @Override
8855        void handleServiceError() {
8856            mArgs = createInstallArgs(this);
8857            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8858        }
8859
8860        public boolean isForwardLocked() {
8861            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8862        }
8863    }
8864
8865    /**
8866     * Used during creation of InstallArgs
8867     *
8868     * @param installFlags package installation flags
8869     * @return true if should be installed on external storage
8870     */
8871    private static boolean installOnSd(int installFlags) {
8872        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8873            return false;
8874        }
8875        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8876            return true;
8877        }
8878        return false;
8879    }
8880
8881    /**
8882     * Used during creation of InstallArgs
8883     *
8884     * @param installFlags package installation flags
8885     * @return true if should be installed as forward locked
8886     */
8887    private static boolean installForwardLocked(int installFlags) {
8888        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8889    }
8890
8891    private InstallArgs createInstallArgs(InstallParams params) {
8892        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8893            return new AsecInstallArgs(params);
8894        } else {
8895            return new FileInstallArgs(params);
8896        }
8897    }
8898
8899    /**
8900     * Create args that describe an existing installed package. Typically used
8901     * when cleaning up old installs, or used as a move source.
8902     */
8903    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8904            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8905        final boolean isInAsec;
8906        if (installOnSd(installFlags)) {
8907            /* Apps on SD card are always in ASEC containers. */
8908            isInAsec = true;
8909        } else if (installForwardLocked(installFlags)
8910                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8911            /*
8912             * Forward-locked apps are only in ASEC containers if they're the
8913             * new style
8914             */
8915            isInAsec = true;
8916        } else {
8917            isInAsec = false;
8918        }
8919
8920        if (isInAsec) {
8921            return new AsecInstallArgs(codePath, instructionSets,
8922                    installOnSd(installFlags), installForwardLocked(installFlags));
8923        } else {
8924            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8925                    instructionSets);
8926        }
8927    }
8928
8929    static abstract class InstallArgs {
8930        /** @see InstallParams#origin */
8931        final OriginInfo origin;
8932
8933        final IPackageInstallObserver2 observer;
8934        // Always refers to PackageManager flags only
8935        final int installFlags;
8936        final String installerPackageName;
8937        final ManifestDigest manifestDigest;
8938        final UserHandle user;
8939        final String abiOverride;
8940
8941        // The list of instruction sets supported by this app. This is currently
8942        // only used during the rmdex() phase to clean up resources. We can get rid of this
8943        // if we move dex files under the common app path.
8944        /* nullable */ String[] instructionSets;
8945
8946        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8947                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
8948                String[] instructionSets, String abiOverride) {
8949            this.origin = origin;
8950            this.installFlags = installFlags;
8951            this.observer = observer;
8952            this.installerPackageName = installerPackageName;
8953            this.manifestDigest = manifestDigest;
8954            this.user = user;
8955            this.instructionSets = instructionSets;
8956            this.abiOverride = abiOverride;
8957        }
8958
8959        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8960        abstract int doPreInstall(int status);
8961
8962        /**
8963         * Rename package into final resting place. All paths on the given
8964         * scanned package should be updated to reflect the rename.
8965         */
8966        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
8967        abstract int doPostInstall(int status, int uid);
8968
8969        /** @see PackageSettingBase#codePathString */
8970        abstract String getCodePath();
8971        /** @see PackageSettingBase#resourcePathString */
8972        abstract String getResourcePath();
8973        abstract String getLegacyNativeLibraryPath();
8974
8975        // Need installer lock especially for dex file removal.
8976        abstract void cleanUpResourcesLI();
8977        abstract boolean doPostDeleteLI(boolean delete);
8978        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8979
8980        /**
8981         * Called before the source arguments are copied. This is used mostly
8982         * for MoveParams when it needs to read the source file to put it in the
8983         * destination.
8984         */
8985        int doPreCopy() {
8986            return PackageManager.INSTALL_SUCCEEDED;
8987        }
8988
8989        /**
8990         * Called after the source arguments are copied. This is used mostly for
8991         * MoveParams when it needs to read the source file to put it in the
8992         * destination.
8993         *
8994         * @return
8995         */
8996        int doPostCopy(int uid) {
8997            return PackageManager.INSTALL_SUCCEEDED;
8998        }
8999
9000        protected boolean isFwdLocked() {
9001            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9002        }
9003
9004        protected boolean isExternal() {
9005            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9006        }
9007
9008        UserHandle getUser() {
9009            return user;
9010        }
9011    }
9012
9013    /**
9014     * Logic to handle installation of non-ASEC applications, including copying
9015     * and renaming logic.
9016     */
9017    class FileInstallArgs extends InstallArgs {
9018        private File codeFile;
9019        private File resourceFile;
9020        private File legacyNativeLibraryPath;
9021
9022        // Example topology:
9023        // /data/app/com.example/base.apk
9024        // /data/app/com.example/split_foo.apk
9025        // /data/app/com.example/lib/arm/libfoo.so
9026        // /data/app/com.example/lib/arm64/libfoo.so
9027        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9028
9029        /** New install */
9030        FileInstallArgs(InstallParams params) {
9031            super(params.origin, params.observer, params.installFlags,
9032                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9033                    null /* instruction sets */, params.packageAbiOverride);
9034            if (isFwdLocked()) {
9035                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9036            }
9037        }
9038
9039        /** Existing install */
9040        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9041                String[] instructionSets) {
9042            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9043            this.codeFile = (codePath != null) ? new File(codePath) : null;
9044            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9045            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9046                    new File(legacyNativeLibraryPath) : null;
9047        }
9048
9049        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9050            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9051                    isFwdLocked(), abiOverride);
9052
9053            final StorageManager storage = StorageManager.from(mContext);
9054            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9055        }
9056
9057        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9058            if (origin.staged) {
9059                Slog.d(TAG, origin.file + " already staged; skipping copy");
9060                codeFile = origin.file;
9061                resourceFile = origin.file;
9062                return PackageManager.INSTALL_SUCCEEDED;
9063            }
9064
9065            try {
9066                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9067                codeFile = tempDir;
9068                resourceFile = tempDir;
9069            } catch (IOException e) {
9070                Slog.w(TAG, "Failed to create copy file: " + e);
9071                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9072            }
9073
9074            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9075                @Override
9076                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9077                    if (!FileUtils.isValidExtFilename(name)) {
9078                        throw new IllegalArgumentException("Invalid filename: " + name);
9079                    }
9080                    try {
9081                        final File file = new File(codeFile, name);
9082                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9083                                O_RDWR | O_CREAT, 0644);
9084                        Os.chmod(file.getAbsolutePath(), 0644);
9085                        return new ParcelFileDescriptor(fd);
9086                    } catch (ErrnoException e) {
9087                        throw new RemoteException("Failed to open: " + e.getMessage());
9088                    }
9089                }
9090            };
9091
9092            int ret = PackageManager.INSTALL_SUCCEEDED;
9093            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9094            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9095                Slog.e(TAG, "Failed to copy package");
9096                return ret;
9097            }
9098
9099            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9100            NativeLibraryHelper.Handle handle = null;
9101            try {
9102                handle = NativeLibraryHelper.Handle.create(codeFile);
9103                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9104                        abiOverride);
9105            } catch (IOException e) {
9106                Slog.e(TAG, "Copying native libraries failed", e);
9107                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9108            } finally {
9109                IoUtils.closeQuietly(handle);
9110            }
9111
9112            return ret;
9113        }
9114
9115        int doPreInstall(int status) {
9116            if (status != PackageManager.INSTALL_SUCCEEDED) {
9117                cleanUp();
9118            }
9119            return status;
9120        }
9121
9122        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9123            if (status != PackageManager.INSTALL_SUCCEEDED) {
9124                cleanUp();
9125                return false;
9126            } else {
9127                final File beforeCodeFile = codeFile;
9128                final File afterCodeFile = getNextCodePath(pkg.packageName);
9129
9130                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9131                try {
9132                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9133                } catch (ErrnoException e) {
9134                    Slog.d(TAG, "Failed to rename", e);
9135                    return false;
9136                }
9137
9138                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9139                    Slog.d(TAG, "Failed to restorecon");
9140                    return false;
9141                }
9142
9143                // Reflect the rename internally
9144                codeFile = afterCodeFile;
9145                resourceFile = afterCodeFile;
9146
9147                // Reflect the rename in scanned details
9148                pkg.codePath = afterCodeFile.getAbsolutePath();
9149                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9150                        pkg.baseCodePath);
9151                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9152                        pkg.splitCodePaths);
9153
9154                // Reflect the rename in app info
9155                pkg.applicationInfo.setCodePath(pkg.codePath);
9156                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9157                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9158                pkg.applicationInfo.setResourcePath(pkg.codePath);
9159                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9160                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9161
9162                return true;
9163            }
9164        }
9165
9166        int doPostInstall(int status, int uid) {
9167            if (status != PackageManager.INSTALL_SUCCEEDED) {
9168                cleanUp();
9169            }
9170            return status;
9171        }
9172
9173        @Override
9174        String getCodePath() {
9175            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9176        }
9177
9178        @Override
9179        String getResourcePath() {
9180            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9181        }
9182
9183        @Override
9184        String getLegacyNativeLibraryPath() {
9185            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9186        }
9187
9188        private boolean cleanUp() {
9189            if (codeFile == null || !codeFile.exists()) {
9190                return false;
9191            }
9192
9193            if (codeFile.isDirectory()) {
9194                FileUtils.deleteContents(codeFile);
9195            }
9196            codeFile.delete();
9197
9198            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9199                resourceFile.delete();
9200            }
9201
9202            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9203                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9204                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9205                }
9206                legacyNativeLibraryPath.delete();
9207            }
9208
9209            return true;
9210        }
9211
9212        void cleanUpResourcesLI() {
9213            // Try enumerating all code paths before deleting
9214            List<String> allCodePaths = Collections.EMPTY_LIST;
9215            if (codeFile != null && codeFile.exists()) {
9216                try {
9217                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9218                    allCodePaths = pkg.getAllCodePaths();
9219                } catch (PackageParserException e) {
9220                    // Ignored; we tried our best
9221                }
9222            }
9223
9224            cleanUp();
9225
9226            if (!allCodePaths.isEmpty()) {
9227                if (instructionSets == null) {
9228                    throw new IllegalStateException("instructionSet == null");
9229                }
9230                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9231                for (String codePath : allCodePaths) {
9232                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9233                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9234                        if (retCode < 0) {
9235                            Slog.w(TAG, "Couldn't remove dex file for package: "
9236                                    + " at location " + codePath + ", retcode=" + retCode);
9237                            // we don't consider this to be a failure of the core package deletion
9238                        }
9239                    }
9240                }
9241            }
9242        }
9243
9244        boolean doPostDeleteLI(boolean delete) {
9245            // XXX err, shouldn't we respect the delete flag?
9246            cleanUpResourcesLI();
9247            return true;
9248        }
9249    }
9250
9251    private boolean isAsecExternal(String cid) {
9252        final String asecPath = PackageHelper.getSdFilesystem(cid);
9253        return !asecPath.startsWith(mAsecInternalPath);
9254    }
9255
9256    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9257            PackageManagerException {
9258        if (copyRet < 0) {
9259            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9260                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9261                throw new PackageManagerException(copyRet, message);
9262            }
9263        }
9264    }
9265
9266    /**
9267     * Extract the MountService "container ID" from the full code path of an
9268     * .apk.
9269     */
9270    static String cidFromCodePath(String fullCodePath) {
9271        int eidx = fullCodePath.lastIndexOf("/");
9272        String subStr1 = fullCodePath.substring(0, eidx);
9273        int sidx = subStr1.lastIndexOf("/");
9274        return subStr1.substring(sidx+1, eidx);
9275    }
9276
9277    /**
9278     * Logic to handle installation of ASEC applications, including copying and
9279     * renaming logic.
9280     */
9281    class AsecInstallArgs extends InstallArgs {
9282        static final String RES_FILE_NAME = "pkg.apk";
9283        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9284
9285        String cid;
9286        String packagePath;
9287        String resourcePath;
9288        String legacyNativeLibraryDir;
9289
9290        /** New install */
9291        AsecInstallArgs(InstallParams params) {
9292            super(params.origin, params.observer, params.installFlags,
9293                    params.installerPackageName, params.getManifestDigest(),
9294                    params.getUser(), null /* instruction sets */,
9295                    params.packageAbiOverride);
9296        }
9297
9298        /** Existing install */
9299        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9300                        boolean isExternal, boolean isForwardLocked) {
9301            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9302                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9303                    instructionSets, null);
9304            // Hackily pretend we're still looking at a full code path
9305            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9306                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9307            }
9308
9309            // Extract cid from fullCodePath
9310            int eidx = fullCodePath.lastIndexOf("/");
9311            String subStr1 = fullCodePath.substring(0, eidx);
9312            int sidx = subStr1.lastIndexOf("/");
9313            cid = subStr1.substring(sidx+1, eidx);
9314            setMountPath(subStr1);
9315        }
9316
9317        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9318            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9319                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9320                    instructionSets, null);
9321            this.cid = cid;
9322            setMountPath(PackageHelper.getSdDir(cid));
9323        }
9324
9325        void createCopyFile() {
9326            cid = mInstallerService.allocateExternalStageCidLegacy();
9327        }
9328
9329        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9330            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9331                    abiOverride);
9332
9333            final File target;
9334            if (isExternal()) {
9335                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9336            } else {
9337                target = Environment.getDataDirectory();
9338            }
9339
9340            final StorageManager storage = StorageManager.from(mContext);
9341            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9342        }
9343
9344        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9345            if (origin.staged) {
9346                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9347                cid = origin.cid;
9348                setMountPath(PackageHelper.getSdDir(cid));
9349                return PackageManager.INSTALL_SUCCEEDED;
9350            }
9351
9352            if (temp) {
9353                createCopyFile();
9354            } else {
9355                /*
9356                 * Pre-emptively destroy the container since it's destroyed if
9357                 * copying fails due to it existing anyway.
9358                 */
9359                PackageHelper.destroySdDir(cid);
9360            }
9361
9362            final String newMountPath = imcs.copyPackageToContainer(
9363                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9364                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9365
9366            if (newMountPath != null) {
9367                setMountPath(newMountPath);
9368                return PackageManager.INSTALL_SUCCEEDED;
9369            } else {
9370                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9371            }
9372        }
9373
9374        @Override
9375        String getCodePath() {
9376            return packagePath;
9377        }
9378
9379        @Override
9380        String getResourcePath() {
9381            return resourcePath;
9382        }
9383
9384        @Override
9385        String getLegacyNativeLibraryPath() {
9386            return legacyNativeLibraryDir;
9387        }
9388
9389        int doPreInstall(int status) {
9390            if (status != PackageManager.INSTALL_SUCCEEDED) {
9391                // Destroy container
9392                PackageHelper.destroySdDir(cid);
9393            } else {
9394                boolean mounted = PackageHelper.isContainerMounted(cid);
9395                if (!mounted) {
9396                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9397                            Process.SYSTEM_UID);
9398                    if (newMountPath != null) {
9399                        setMountPath(newMountPath);
9400                    } else {
9401                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9402                    }
9403                }
9404            }
9405            return status;
9406        }
9407
9408        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9409            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9410            String newMountPath = null;
9411            if (PackageHelper.isContainerMounted(cid)) {
9412                // Unmount the container
9413                if (!PackageHelper.unMountSdDir(cid)) {
9414                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9415                    return false;
9416                }
9417            }
9418            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9419                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9420                        " which might be stale. Will try to clean up.");
9421                // Clean up the stale container and proceed to recreate.
9422                if (!PackageHelper.destroySdDir(newCacheId)) {
9423                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9424                    return false;
9425                }
9426                // Successfully cleaned up stale container. Try to rename again.
9427                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9428                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9429                            + " inspite of cleaning it up.");
9430                    return false;
9431                }
9432            }
9433            if (!PackageHelper.isContainerMounted(newCacheId)) {
9434                Slog.w(TAG, "Mounting container " + newCacheId);
9435                newMountPath = PackageHelper.mountSdDir(newCacheId,
9436                        getEncryptKey(), Process.SYSTEM_UID);
9437            } else {
9438                newMountPath = PackageHelper.getSdDir(newCacheId);
9439            }
9440            if (newMountPath == null) {
9441                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9442                return false;
9443            }
9444            Log.i(TAG, "Succesfully renamed " + cid +
9445                    " to " + newCacheId +
9446                    " at new path: " + newMountPath);
9447            cid = newCacheId;
9448
9449            final File beforeCodeFile = new File(packagePath);
9450            setMountPath(newMountPath);
9451            final File afterCodeFile = new File(packagePath);
9452
9453            // Reflect the rename in scanned details
9454            pkg.codePath = afterCodeFile.getAbsolutePath();
9455            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9456                    pkg.baseCodePath);
9457            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9458                    pkg.splitCodePaths);
9459
9460            // Reflect the rename in app info
9461            pkg.applicationInfo.setCodePath(pkg.codePath);
9462            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9463            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9464            pkg.applicationInfo.setResourcePath(pkg.codePath);
9465            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9466            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9467
9468            return true;
9469        }
9470
9471        private void setMountPath(String mountPath) {
9472            final File mountFile = new File(mountPath);
9473
9474            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9475            if (monolithicFile.exists()) {
9476                packagePath = monolithicFile.getAbsolutePath();
9477                if (isFwdLocked()) {
9478                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9479                } else {
9480                    resourcePath = packagePath;
9481                }
9482            } else {
9483                packagePath = mountFile.getAbsolutePath();
9484                resourcePath = packagePath;
9485            }
9486
9487            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9488        }
9489
9490        int doPostInstall(int status, int uid) {
9491            if (status != PackageManager.INSTALL_SUCCEEDED) {
9492                cleanUp();
9493            } else {
9494                final int groupOwner;
9495                final String protectedFile;
9496                if (isFwdLocked()) {
9497                    groupOwner = UserHandle.getSharedAppGid(uid);
9498                    protectedFile = RES_FILE_NAME;
9499                } else {
9500                    groupOwner = -1;
9501                    protectedFile = null;
9502                }
9503
9504                if (uid < Process.FIRST_APPLICATION_UID
9505                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9506                    Slog.e(TAG, "Failed to finalize " + cid);
9507                    PackageHelper.destroySdDir(cid);
9508                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9509                }
9510
9511                boolean mounted = PackageHelper.isContainerMounted(cid);
9512                if (!mounted) {
9513                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9514                }
9515            }
9516            return status;
9517        }
9518
9519        private void cleanUp() {
9520            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9521
9522            // Destroy secure container
9523            PackageHelper.destroySdDir(cid);
9524        }
9525
9526        private List<String> getAllCodePaths() {
9527            final File codeFile = new File(getCodePath());
9528            if (codeFile != null && codeFile.exists()) {
9529                try {
9530                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9531                    return pkg.getAllCodePaths();
9532                } catch (PackageParserException e) {
9533                    // Ignored; we tried our best
9534                }
9535            }
9536            return Collections.EMPTY_LIST;
9537        }
9538
9539        void cleanUpResourcesLI() {
9540            // Enumerate all code paths before deleting
9541            cleanUpResourcesLI(getAllCodePaths());
9542        }
9543
9544        private void cleanUpResourcesLI(List<String> allCodePaths) {
9545            cleanUp();
9546
9547            if (!allCodePaths.isEmpty()) {
9548                if (instructionSets == null) {
9549                    throw new IllegalStateException("instructionSet == null");
9550                }
9551                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9552                for (String codePath : allCodePaths) {
9553                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9554                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9555                        if (retCode < 0) {
9556                            Slog.w(TAG, "Couldn't remove dex file for package: "
9557                                    + " at location " + codePath + ", retcode=" + retCode);
9558                            // we don't consider this to be a failure of the core package deletion
9559                        }
9560                    }
9561                }
9562            }
9563        }
9564
9565        boolean matchContainer(String app) {
9566            if (cid.startsWith(app)) {
9567                return true;
9568            }
9569            return false;
9570        }
9571
9572        String getPackageName() {
9573            return getAsecPackageName(cid);
9574        }
9575
9576        boolean doPostDeleteLI(boolean delete) {
9577            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9578            final List<String> allCodePaths = getAllCodePaths();
9579            boolean mounted = PackageHelper.isContainerMounted(cid);
9580            if (mounted) {
9581                // Unmount first
9582                if (PackageHelper.unMountSdDir(cid)) {
9583                    mounted = false;
9584                }
9585            }
9586            if (!mounted && delete) {
9587                cleanUpResourcesLI(allCodePaths);
9588            }
9589            return !mounted;
9590        }
9591
9592        @Override
9593        int doPreCopy() {
9594            if (isFwdLocked()) {
9595                if (!PackageHelper.fixSdPermissions(cid,
9596                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9597                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9598                }
9599            }
9600
9601            return PackageManager.INSTALL_SUCCEEDED;
9602        }
9603
9604        @Override
9605        int doPostCopy(int uid) {
9606            if (isFwdLocked()) {
9607                if (uid < Process.FIRST_APPLICATION_UID
9608                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9609                                RES_FILE_NAME)) {
9610                    Slog.e(TAG, "Failed to finalize " + cid);
9611                    PackageHelper.destroySdDir(cid);
9612                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9613                }
9614            }
9615
9616            return PackageManager.INSTALL_SUCCEEDED;
9617        }
9618    }
9619
9620    static String getAsecPackageName(String packageCid) {
9621        int idx = packageCid.lastIndexOf("-");
9622        if (idx == -1) {
9623            return packageCid;
9624        }
9625        return packageCid.substring(0, idx);
9626    }
9627
9628    // Utility method used to create code paths based on package name and available index.
9629    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9630        String idxStr = "";
9631        int idx = 1;
9632        // Fall back to default value of idx=1 if prefix is not
9633        // part of oldCodePath
9634        if (oldCodePath != null) {
9635            String subStr = oldCodePath;
9636            // Drop the suffix right away
9637            if (suffix != null && subStr.endsWith(suffix)) {
9638                subStr = subStr.substring(0, subStr.length() - suffix.length());
9639            }
9640            // If oldCodePath already contains prefix find out the
9641            // ending index to either increment or decrement.
9642            int sidx = subStr.lastIndexOf(prefix);
9643            if (sidx != -1) {
9644                subStr = subStr.substring(sidx + prefix.length());
9645                if (subStr != null) {
9646                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9647                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9648                    }
9649                    try {
9650                        idx = Integer.parseInt(subStr);
9651                        if (idx <= 1) {
9652                            idx++;
9653                        } else {
9654                            idx--;
9655                        }
9656                    } catch(NumberFormatException e) {
9657                    }
9658                }
9659            }
9660        }
9661        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9662        return prefix + idxStr;
9663    }
9664
9665    private File getNextCodePath(String packageName) {
9666        int suffix = 1;
9667        File result;
9668        do {
9669            result = new File(mAppInstallDir, packageName + "-" + suffix);
9670            suffix++;
9671        } while (result.exists());
9672        return result;
9673    }
9674
9675    // Utility method used to ignore ADD/REMOVE events
9676    // by directory observer.
9677    private static boolean ignoreCodePath(String fullPathStr) {
9678        String apkName = deriveCodePathName(fullPathStr);
9679        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9680        if (idx != -1 && ((idx+1) < apkName.length())) {
9681            // Make sure the package ends with a numeral
9682            String version = apkName.substring(idx+1);
9683            try {
9684                Integer.parseInt(version);
9685                return true;
9686            } catch (NumberFormatException e) {}
9687        }
9688        return false;
9689    }
9690
9691    // Utility method that returns the relative package path with respect
9692    // to the installation directory. Like say for /data/data/com.test-1.apk
9693    // string com.test-1 is returned.
9694    static String deriveCodePathName(String codePath) {
9695        if (codePath == null) {
9696            return null;
9697        }
9698        final File codeFile = new File(codePath);
9699        final String name = codeFile.getName();
9700        if (codeFile.isDirectory()) {
9701            return name;
9702        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9703            final int lastDot = name.lastIndexOf('.');
9704            return name.substring(0, lastDot);
9705        } else {
9706            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9707            return null;
9708        }
9709    }
9710
9711    class PackageInstalledInfo {
9712        String name;
9713        int uid;
9714        // The set of users that originally had this package installed.
9715        int[] origUsers;
9716        // The set of users that now have this package installed.
9717        int[] newUsers;
9718        PackageParser.Package pkg;
9719        int returnCode;
9720        String returnMsg;
9721        PackageRemovedInfo removedInfo;
9722
9723        public void setError(int code, String msg) {
9724            returnCode = code;
9725            returnMsg = msg;
9726            Slog.w(TAG, msg);
9727        }
9728
9729        public void setError(String msg, PackageParserException e) {
9730            returnCode = e.error;
9731            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9732            Slog.w(TAG, msg, e);
9733        }
9734
9735        public void setError(String msg, PackageManagerException e) {
9736            returnCode = e.error;
9737            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9738            Slog.w(TAG, msg, e);
9739        }
9740
9741        // In some error cases we want to convey more info back to the observer
9742        String origPackage;
9743        String origPermission;
9744    }
9745
9746    /*
9747     * Install a non-existing package.
9748     */
9749    private void installNewPackageLI(PackageParser.Package pkg,
9750            int parseFlags, int scanFlags, UserHandle user,
9751            String installerPackageName, PackageInstalledInfo res) {
9752        // Remember this for later, in case we need to rollback this install
9753        String pkgName = pkg.packageName;
9754
9755        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9756        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9757        synchronized(mPackages) {
9758            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9759                // A package with the same name is already installed, though
9760                // it has been renamed to an older name.  The package we
9761                // are trying to install should be installed as an update to
9762                // the existing one, but that has not been requested, so bail.
9763                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9764                        + " without first uninstalling package running as "
9765                        + mSettings.mRenamedPackages.get(pkgName));
9766                return;
9767            }
9768            if (mPackages.containsKey(pkgName)) {
9769                // Don't allow installation over an existing package with the same name.
9770                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9771                        + " without first uninstalling.");
9772                return;
9773            }
9774        }
9775
9776        try {
9777            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9778                    System.currentTimeMillis(), user);
9779
9780            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9781            // delete the partially installed application. the data directory will have to be
9782            // restored if it was already existing
9783            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9784                // remove package from internal structures.  Note that we want deletePackageX to
9785                // delete the package data and cache directories that it created in
9786                // scanPackageLocked, unless those directories existed before we even tried to
9787                // install.
9788                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9789                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9790                                res.removedInfo, true);
9791            }
9792
9793        } catch (PackageManagerException e) {
9794            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9795        }
9796    }
9797
9798    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9799        // Upgrade keysets are being used.  Determine if new package has a superset of the
9800        // required keys.
9801        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9802        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9803        for (int i = 0; i < upgradeKeySets.length; i++) {
9804            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9805            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9806                return true;
9807            }
9808        }
9809        return false;
9810    }
9811
9812    private void replacePackageLI(PackageParser.Package pkg,
9813            int parseFlags, int scanFlags, UserHandle user,
9814            String installerPackageName, PackageInstalledInfo res) {
9815        PackageParser.Package oldPackage;
9816        String pkgName = pkg.packageName;
9817        int[] allUsers;
9818        boolean[] perUserInstalled;
9819
9820        // First find the old package info and check signatures
9821        synchronized(mPackages) {
9822            oldPackage = mPackages.get(pkgName);
9823            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9824            PackageSetting ps = mSettings.mPackages.get(pkgName);
9825            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9826                // default to original signature matching
9827                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9828                    != PackageManager.SIGNATURE_MATCH) {
9829                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9830                            "New package has a different signature: " + pkgName);
9831                    return;
9832                }
9833            } else {
9834                if(!checkUpgradeKeySetLP(ps, pkg)) {
9835                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9836                            "New package not signed by keys specified by upgrade-keysets: "
9837                            + pkgName);
9838                    return;
9839                }
9840            }
9841
9842            // In case of rollback, remember per-user/profile install state
9843            allUsers = sUserManager.getUserIds();
9844            perUserInstalled = new boolean[allUsers.length];
9845            for (int i = 0; i < allUsers.length; i++) {
9846                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9847            }
9848        }
9849
9850        boolean sysPkg = (isSystemApp(oldPackage));
9851        if (sysPkg) {
9852            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9853                    user, allUsers, perUserInstalled, installerPackageName, res);
9854        } else {
9855            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9856                    user, allUsers, perUserInstalled, installerPackageName, res);
9857        }
9858    }
9859
9860    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9861            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9862            int[] allUsers, boolean[] perUserInstalled,
9863            String installerPackageName, PackageInstalledInfo res) {
9864        String pkgName = deletedPackage.packageName;
9865        boolean deletedPkg = true;
9866        boolean updatedSettings = false;
9867
9868        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9869                + deletedPackage);
9870        long origUpdateTime;
9871        if (pkg.mExtras != null) {
9872            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9873        } else {
9874            origUpdateTime = 0;
9875        }
9876
9877        // First delete the existing package while retaining the data directory
9878        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9879                res.removedInfo, true)) {
9880            // If the existing package wasn't successfully deleted
9881            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9882            deletedPkg = false;
9883        } else {
9884            // Successfully deleted the old package; proceed with replace.
9885
9886            // If deleted package lived in a container, give users a chance to
9887            // relinquish resources before killing.
9888            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9889                if (DEBUG_INSTALL) {
9890                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9891                }
9892                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9893                final ArrayList<String> pkgList = new ArrayList<String>(1);
9894                pkgList.add(deletedPackage.applicationInfo.packageName);
9895                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9896            }
9897
9898            deleteCodeCacheDirsLI(pkgName);
9899            try {
9900                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9901                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9902                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9903                updatedSettings = true;
9904            } catch (PackageManagerException e) {
9905                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9906            }
9907        }
9908
9909        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9910            // remove package from internal structures.  Note that we want deletePackageX to
9911            // delete the package data and cache directories that it created in
9912            // scanPackageLocked, unless those directories existed before we even tried to
9913            // install.
9914            if(updatedSettings) {
9915                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9916                deletePackageLI(
9917                        pkgName, null, true, allUsers, perUserInstalled,
9918                        PackageManager.DELETE_KEEP_DATA,
9919                                res.removedInfo, true);
9920            }
9921            // Since we failed to install the new package we need to restore the old
9922            // package that we deleted.
9923            if (deletedPkg) {
9924                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9925                File restoreFile = new File(deletedPackage.codePath);
9926                // Parse old package
9927                boolean oldOnSd = isExternal(deletedPackage);
9928                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9929                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9930                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9931                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9932                try {
9933                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9934                } catch (PackageManagerException e) {
9935                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9936                            + e.getMessage());
9937                    return;
9938                }
9939                // Restore of old package succeeded. Update permissions.
9940                // writer
9941                synchronized (mPackages) {
9942                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9943                            UPDATE_PERMISSIONS_ALL);
9944                    // can downgrade to reader
9945                    mSettings.writeLPr();
9946                }
9947                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9948            }
9949        }
9950    }
9951
9952    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9953            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9954            int[] allUsers, boolean[] perUserInstalled,
9955            String installerPackageName, PackageInstalledInfo res) {
9956        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9957                + ", old=" + deletedPackage);
9958        boolean updatedSettings = false;
9959        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
9960        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9961            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9962        }
9963        String packageName = deletedPackage.packageName;
9964        if (packageName == null) {
9965            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9966                    "Attempt to delete null packageName.");
9967            return;
9968        }
9969        PackageParser.Package oldPkg;
9970        PackageSetting oldPkgSetting;
9971        // reader
9972        synchronized (mPackages) {
9973            oldPkg = mPackages.get(packageName);
9974            oldPkgSetting = mSettings.mPackages.get(packageName);
9975            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9976                    (oldPkgSetting == null)) {
9977                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9978                        "Couldn't find package:" + packageName + " information");
9979                return;
9980            }
9981        }
9982
9983        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9984
9985        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9986        res.removedInfo.removedPackage = packageName;
9987        // Remove existing system package
9988        removePackageLI(oldPkgSetting, true);
9989        // writer
9990        synchronized (mPackages) {
9991            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9992                // We didn't need to disable the .apk as a current system package,
9993                // which means we are replacing another update that is already
9994                // installed.  We need to make sure to delete the older one's .apk.
9995                res.removedInfo.args = createInstallArgsForExisting(0,
9996                        deletedPackage.applicationInfo.getCodePath(),
9997                        deletedPackage.applicationInfo.getResourcePath(),
9998                        deletedPackage.applicationInfo.nativeLibraryRootDir,
9999                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10000            } else {
10001                res.removedInfo.args = null;
10002            }
10003        }
10004
10005        // Successfully disabled the old package. Now proceed with re-installation
10006        deleteCodeCacheDirsLI(packageName);
10007
10008        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10009        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10010
10011        PackageParser.Package newPackage = null;
10012        try {
10013            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10014            if (newPackage.mExtras != null) {
10015                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10016                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10017                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10018
10019                // is the update attempting to change shared user? that isn't going to work...
10020                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10021                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10022                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10023                            + " to " + newPkgSetting.sharedUser);
10024                    updatedSettings = true;
10025                }
10026            }
10027
10028            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10029                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10030                updatedSettings = true;
10031            }
10032
10033        } catch (PackageManagerException e) {
10034            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10035        }
10036
10037        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10038            // Re installation failed. Restore old information
10039            // Remove new pkg information
10040            if (newPackage != null) {
10041                removeInstalledPackageLI(newPackage, true);
10042            }
10043            // Add back the old system package
10044            try {
10045                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10046            } catch (PackageManagerException e) {
10047                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10048            }
10049            // Restore the old system information in Settings
10050            synchronized(mPackages) {
10051                if (updatedSettings) {
10052                    mSettings.enableSystemPackageLPw(packageName);
10053                    mSettings.setInstallerPackageName(packageName,
10054                            oldPkgSetting.installerPackageName);
10055                }
10056                mSettings.writeLPr();
10057            }
10058        }
10059    }
10060
10061    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10062            int[] allUsers, boolean[] perUserInstalled,
10063            PackageInstalledInfo res) {
10064        String pkgName = newPackage.packageName;
10065        synchronized (mPackages) {
10066            //write settings. the installStatus will be incomplete at this stage.
10067            //note that the new package setting would have already been
10068            //added to mPackages. It hasn't been persisted yet.
10069            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10070            mSettings.writeLPr();
10071        }
10072
10073        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10074
10075        synchronized (mPackages) {
10076            updatePermissionsLPw(newPackage.packageName, newPackage,
10077                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10078                            ? UPDATE_PERMISSIONS_ALL : 0));
10079            // For system-bundled packages, we assume that installing an upgraded version
10080            // of the package implies that the user actually wants to run that new code,
10081            // so we enable the package.
10082            if (isSystemApp(newPackage)) {
10083                // NB: implicit assumption that system package upgrades apply to all users
10084                if (DEBUG_INSTALL) {
10085                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10086                }
10087                PackageSetting ps = mSettings.mPackages.get(pkgName);
10088                if (ps != null) {
10089                    if (res.origUsers != null) {
10090                        for (int userHandle : res.origUsers) {
10091                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10092                                    userHandle, installerPackageName);
10093                        }
10094                    }
10095                    // Also convey the prior install/uninstall state
10096                    if (allUsers != null && perUserInstalled != null) {
10097                        for (int i = 0; i < allUsers.length; i++) {
10098                            if (DEBUG_INSTALL) {
10099                                Slog.d(TAG, "    user " + allUsers[i]
10100                                        + " => " + perUserInstalled[i]);
10101                            }
10102                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10103                        }
10104                        // these install state changes will be persisted in the
10105                        // upcoming call to mSettings.writeLPr().
10106                    }
10107                }
10108            }
10109            res.name = pkgName;
10110            res.uid = newPackage.applicationInfo.uid;
10111            res.pkg = newPackage;
10112            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10113            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10114            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10115            //to update install status
10116            mSettings.writeLPr();
10117        }
10118    }
10119
10120    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10121        final int installFlags = args.installFlags;
10122        String installerPackageName = args.installerPackageName;
10123        File tmpPackageFile = new File(args.getCodePath());
10124        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10125        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10126        boolean replace = false;
10127        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10128        // Result object to be returned
10129        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10130
10131        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10132        // Retrieve PackageSettings and parse package
10133        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10134                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10135                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10136        PackageParser pp = new PackageParser();
10137        pp.setSeparateProcesses(mSeparateProcesses);
10138        pp.setDisplayMetrics(mMetrics);
10139
10140        final PackageParser.Package pkg;
10141        try {
10142            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10143        } catch (PackageParserException e) {
10144            res.setError("Failed parse during installPackageLI", e);
10145            return;
10146        }
10147
10148        // Mark that we have an install time CPU ABI override.
10149        pkg.cpuAbiOverride = args.abiOverride;
10150
10151        String pkgName = res.name = pkg.packageName;
10152        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10153            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10154                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10155                return;
10156            }
10157        }
10158
10159        try {
10160            pp.collectCertificates(pkg, parseFlags);
10161            pp.collectManifestDigest(pkg);
10162        } catch (PackageParserException e) {
10163            res.setError("Failed collect during installPackageLI", e);
10164            return;
10165        }
10166
10167        /* If the installer passed in a manifest digest, compare it now. */
10168        if (args.manifestDigest != null) {
10169            if (DEBUG_INSTALL) {
10170                final String parsedManifest = pkg.manifestDigest == null ? "null"
10171                        : pkg.manifestDigest.toString();
10172                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10173                        + parsedManifest);
10174            }
10175
10176            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10177                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10178                return;
10179            }
10180        } else if (DEBUG_INSTALL) {
10181            final String parsedManifest = pkg.manifestDigest == null
10182                    ? "null" : pkg.manifestDigest.toString();
10183            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10184        }
10185
10186        // Get rid of all references to package scan path via parser.
10187        pp = null;
10188        String oldCodePath = null;
10189        boolean systemApp = false;
10190        synchronized (mPackages) {
10191            // Check whether the newly-scanned package wants to define an already-defined perm
10192            int N = pkg.permissions.size();
10193            for (int i = N-1; i >= 0; i--) {
10194                PackageParser.Permission perm = pkg.permissions.get(i);
10195                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10196                if (bp != null) {
10197                    // If the defining package is signed with our cert, it's okay.  This
10198                    // also includes the "updating the same package" case, of course.
10199                    // "updating same package" could also involve key-rotation.
10200                    final boolean sigsOk;
10201                    if (!bp.sourcePackage.equals(pkg.packageName)
10202                            || !(bp.packageSetting instanceof PackageSetting)
10203                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10204                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10205                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10206                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10207                    } else {
10208                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10209                    }
10210                    if (!sigsOk) {
10211                        // If the owning package is the system itself, we log but allow
10212                        // install to proceed; we fail the install on all other permission
10213                        // redefinitions.
10214                        if (!bp.sourcePackage.equals("android")) {
10215                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10216                                    + pkg.packageName + " attempting to redeclare permission "
10217                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10218                            res.origPermission = perm.info.name;
10219                            res.origPackage = bp.sourcePackage;
10220                            return;
10221                        } else {
10222                            Slog.w(TAG, "Package " + pkg.packageName
10223                                    + " attempting to redeclare system permission "
10224                                    + perm.info.name + "; ignoring new declaration");
10225                            pkg.permissions.remove(i);
10226                        }
10227                    }
10228                }
10229            }
10230
10231            // Check if installing already existing package
10232            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10233                String oldName = mSettings.mRenamedPackages.get(pkgName);
10234                if (pkg.mOriginalPackages != null
10235                        && pkg.mOriginalPackages.contains(oldName)
10236                        && mPackages.containsKey(oldName)) {
10237                    // This package is derived from an original package,
10238                    // and this device has been updating from that original
10239                    // name.  We must continue using the original name, so
10240                    // rename the new package here.
10241                    pkg.setPackageName(oldName);
10242                    pkgName = pkg.packageName;
10243                    replace = true;
10244                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10245                            + oldName + " pkgName=" + pkgName);
10246                } else if (mPackages.containsKey(pkgName)) {
10247                    // This package, under its official name, already exists
10248                    // on the device; we should replace it.
10249                    replace = true;
10250                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10251                }
10252            }
10253            PackageSetting ps = mSettings.mPackages.get(pkgName);
10254            if (ps != null) {
10255                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10256                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10257                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10258                    systemApp = (ps.pkg.applicationInfo.flags &
10259                            ApplicationInfo.FLAG_SYSTEM) != 0;
10260                }
10261                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10262            }
10263        }
10264
10265        if (systemApp && onSd) {
10266            // Disable updates to system apps on sdcard
10267            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10268                    "Cannot install updates to system apps on sdcard");
10269            return;
10270        }
10271
10272        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10273            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10274            return;
10275        }
10276
10277        if (replace) {
10278            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10279                    installerPackageName, res);
10280        } else {
10281            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10282                    args.user, installerPackageName, res);
10283        }
10284        synchronized (mPackages) {
10285            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10286            if (ps != null) {
10287                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10288            }
10289        }
10290    }
10291
10292    private static boolean isForwardLocked(PackageParser.Package pkg) {
10293        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10294    }
10295
10296    private static boolean isForwardLocked(ApplicationInfo info) {
10297        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10298    }
10299
10300    private boolean isForwardLocked(PackageSetting ps) {
10301        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10302    }
10303
10304    private static boolean isMultiArch(PackageSetting ps) {
10305        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10306    }
10307
10308    private static boolean isMultiArch(ApplicationInfo info) {
10309        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10310    }
10311
10312    private static boolean isExternal(PackageParser.Package pkg) {
10313        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10314    }
10315
10316    private static boolean isExternal(PackageSetting ps) {
10317        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10318    }
10319
10320    private static boolean isExternal(ApplicationInfo info) {
10321        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10322    }
10323
10324    private static boolean isSystemApp(PackageParser.Package pkg) {
10325        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10326    }
10327
10328    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10329        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10330    }
10331
10332    private static boolean isSystemApp(ApplicationInfo info) {
10333        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10334    }
10335
10336    private static boolean isSystemApp(PackageSetting ps) {
10337        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10338    }
10339
10340    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10341        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10342    }
10343
10344    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10345        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10346    }
10347
10348    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10349        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10350    }
10351
10352    private int packageFlagsToInstallFlags(PackageSetting ps) {
10353        int installFlags = 0;
10354        if (isExternal(ps)) {
10355            installFlags |= PackageManager.INSTALL_EXTERNAL;
10356        }
10357        if (isForwardLocked(ps)) {
10358            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10359        }
10360        return installFlags;
10361    }
10362
10363    private void deleteTempPackageFiles() {
10364        final FilenameFilter filter = new FilenameFilter() {
10365            public boolean accept(File dir, String name) {
10366                return name.startsWith("vmdl") && name.endsWith(".tmp");
10367            }
10368        };
10369        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10370            file.delete();
10371        }
10372    }
10373
10374    @Override
10375    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10376            int flags) {
10377        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10378                flags);
10379    }
10380
10381    @Override
10382    public void deletePackage(final String packageName,
10383            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10384        mContext.enforceCallingOrSelfPermission(
10385                android.Manifest.permission.DELETE_PACKAGES, null);
10386        final int uid = Binder.getCallingUid();
10387        if (UserHandle.getUserId(uid) != userId) {
10388            mContext.enforceCallingPermission(
10389                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10390                    "deletePackage for user " + userId);
10391        }
10392        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10393            try {
10394                observer.onPackageDeleted(packageName,
10395                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10396            } catch (RemoteException re) {
10397            }
10398            return;
10399        }
10400
10401        boolean uninstallBlocked = false;
10402        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10403            int[] users = sUserManager.getUserIds();
10404            for (int i = 0; i < users.length; ++i) {
10405                if (getBlockUninstallForUser(packageName, users[i])) {
10406                    uninstallBlocked = true;
10407                    break;
10408                }
10409            }
10410        } else {
10411            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10412        }
10413        if (uninstallBlocked) {
10414            try {
10415                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10416                        null);
10417            } catch (RemoteException re) {
10418            }
10419            return;
10420        }
10421
10422        if (DEBUG_REMOVE) {
10423            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10424        }
10425        // Queue up an async operation since the package deletion may take a little while.
10426        mHandler.post(new Runnable() {
10427            public void run() {
10428                mHandler.removeCallbacks(this);
10429                final int returnCode = deletePackageX(packageName, userId, flags);
10430                if (observer != null) {
10431                    try {
10432                        observer.onPackageDeleted(packageName, returnCode, null);
10433                    } catch (RemoteException e) {
10434                        Log.i(TAG, "Observer no longer exists.");
10435                    } //end catch
10436                } //end if
10437            } //end run
10438        });
10439    }
10440
10441    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10442        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10443                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10444        try {
10445            if (dpm != null) {
10446                if (dpm.isDeviceOwner(packageName)) {
10447                    return true;
10448                }
10449                int[] users;
10450                if (userId == UserHandle.USER_ALL) {
10451                    users = sUserManager.getUserIds();
10452                } else {
10453                    users = new int[]{userId};
10454                }
10455                for (int i = 0; i < users.length; ++i) {
10456                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10457                        return true;
10458                    }
10459                }
10460            }
10461        } catch (RemoteException e) {
10462        }
10463        return false;
10464    }
10465
10466    /**
10467     *  This method is an internal method that could be get invoked either
10468     *  to delete an installed package or to clean up a failed installation.
10469     *  After deleting an installed package, a broadcast is sent to notify any
10470     *  listeners that the package has been installed. For cleaning up a failed
10471     *  installation, the broadcast is not necessary since the package's
10472     *  installation wouldn't have sent the initial broadcast either
10473     *  The key steps in deleting a package are
10474     *  deleting the package information in internal structures like mPackages,
10475     *  deleting the packages base directories through installd
10476     *  updating mSettings to reflect current status
10477     *  persisting settings for later use
10478     *  sending a broadcast if necessary
10479     */
10480    private int deletePackageX(String packageName, int userId, int flags) {
10481        final PackageRemovedInfo info = new PackageRemovedInfo();
10482        final boolean res;
10483
10484        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10485                ? UserHandle.ALL : new UserHandle(userId);
10486
10487        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10488            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10489            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10490        }
10491
10492        boolean removedForAllUsers = false;
10493        boolean systemUpdate = false;
10494
10495        // for the uninstall-updates case and restricted profiles, remember the per-
10496        // userhandle installed state
10497        int[] allUsers;
10498        boolean[] perUserInstalled;
10499        synchronized (mPackages) {
10500            PackageSetting ps = mSettings.mPackages.get(packageName);
10501            allUsers = sUserManager.getUserIds();
10502            perUserInstalled = new boolean[allUsers.length];
10503            for (int i = 0; i < allUsers.length; i++) {
10504                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10505            }
10506        }
10507
10508        synchronized (mInstallLock) {
10509            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10510            res = deletePackageLI(packageName, removeForUser,
10511                    true, allUsers, perUserInstalled,
10512                    flags | REMOVE_CHATTY, info, true);
10513            systemUpdate = info.isRemovedPackageSystemUpdate;
10514            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10515                removedForAllUsers = true;
10516            }
10517            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10518                    + " removedForAllUsers=" + removedForAllUsers);
10519        }
10520
10521        if (res) {
10522            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10523
10524            // If the removed package was a system update, the old system package
10525            // was re-enabled; we need to broadcast this information
10526            if (systemUpdate) {
10527                Bundle extras = new Bundle(1);
10528                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10529                        ? info.removedAppId : info.uid);
10530                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10531
10532                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10533                        extras, null, null, null);
10534                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10535                        extras, null, null, null);
10536                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10537                        null, packageName, null, null);
10538            }
10539        }
10540        // Force a gc here.
10541        Runtime.getRuntime().gc();
10542        // Delete the resources here after sending the broadcast to let
10543        // other processes clean up before deleting resources.
10544        if (info.args != null) {
10545            synchronized (mInstallLock) {
10546                info.args.doPostDeleteLI(true);
10547            }
10548        }
10549
10550        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10551    }
10552
10553    static class PackageRemovedInfo {
10554        String removedPackage;
10555        int uid = -1;
10556        int removedAppId = -1;
10557        int[] removedUsers = null;
10558        boolean isRemovedPackageSystemUpdate = false;
10559        // Clean up resources deleted packages.
10560        InstallArgs args = null;
10561
10562        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10563            Bundle extras = new Bundle(1);
10564            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10565            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10566            if (replacing) {
10567                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10568            }
10569            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10570            if (removedPackage != null) {
10571                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10572                        extras, null, null, removedUsers);
10573                if (fullRemove && !replacing) {
10574                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10575                            extras, null, null, removedUsers);
10576                }
10577            }
10578            if (removedAppId >= 0) {
10579                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10580                        removedUsers);
10581            }
10582        }
10583    }
10584
10585    /*
10586     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10587     * flag is not set, the data directory is removed as well.
10588     * make sure this flag is set for partially installed apps. If not its meaningless to
10589     * delete a partially installed application.
10590     */
10591    private void removePackageDataLI(PackageSetting ps,
10592            int[] allUserHandles, boolean[] perUserInstalled,
10593            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10594        String packageName = ps.name;
10595        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10596        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10597        // Retrieve object to delete permissions for shared user later on
10598        final PackageSetting deletedPs;
10599        // reader
10600        synchronized (mPackages) {
10601            deletedPs = mSettings.mPackages.get(packageName);
10602            if (outInfo != null) {
10603                outInfo.removedPackage = packageName;
10604                outInfo.removedUsers = deletedPs != null
10605                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10606                        : null;
10607            }
10608        }
10609        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10610            removeDataDirsLI(packageName);
10611            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10612        }
10613        // writer
10614        synchronized (mPackages) {
10615            if (deletedPs != null) {
10616                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10617                    if (outInfo != null) {
10618                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10619                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10620                    }
10621                    if (deletedPs != null) {
10622                        updatePermissionsLPw(deletedPs.name, null, 0);
10623                        if (deletedPs.sharedUser != null) {
10624                            // remove permissions associated with package
10625                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10626                        }
10627                    }
10628                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10629                }
10630                // make sure to preserve per-user disabled state if this removal was just
10631                // a downgrade of a system app to the factory package
10632                if (allUserHandles != null && perUserInstalled != null) {
10633                    if (DEBUG_REMOVE) {
10634                        Slog.d(TAG, "Propagating install state across downgrade");
10635                    }
10636                    for (int i = 0; i < allUserHandles.length; i++) {
10637                        if (DEBUG_REMOVE) {
10638                            Slog.d(TAG, "    user " + allUserHandles[i]
10639                                    + " => " + perUserInstalled[i]);
10640                        }
10641                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10642                    }
10643                }
10644            }
10645            // can downgrade to reader
10646            if (writeSettings) {
10647                // Save settings now
10648                mSettings.writeLPr();
10649            }
10650        }
10651        if (outInfo != null) {
10652            // A user ID was deleted here. Go through all users and remove it
10653            // from KeyStore.
10654            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10655        }
10656    }
10657
10658    static boolean locationIsPrivileged(File path) {
10659        try {
10660            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10661                    .getCanonicalPath();
10662            return path.getCanonicalPath().startsWith(privilegedAppDir);
10663        } catch (IOException e) {
10664            Slog.e(TAG, "Unable to access code path " + path);
10665        }
10666        return false;
10667    }
10668
10669    /*
10670     * Tries to delete system package.
10671     */
10672    private boolean deleteSystemPackageLI(PackageSetting newPs,
10673            int[] allUserHandles, boolean[] perUserInstalled,
10674            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10675        final boolean applyUserRestrictions
10676                = (allUserHandles != null) && (perUserInstalled != null);
10677        PackageSetting disabledPs = null;
10678        // Confirm if the system package has been updated
10679        // An updated system app can be deleted. This will also have to restore
10680        // the system pkg from system partition
10681        // reader
10682        synchronized (mPackages) {
10683            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10684        }
10685        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10686                + " disabledPs=" + disabledPs);
10687        if (disabledPs == null) {
10688            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10689            return false;
10690        } else if (DEBUG_REMOVE) {
10691            Slog.d(TAG, "Deleting system pkg from data partition");
10692        }
10693        if (DEBUG_REMOVE) {
10694            if (applyUserRestrictions) {
10695                Slog.d(TAG, "Remembering install states:");
10696                for (int i = 0; i < allUserHandles.length; i++) {
10697                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10698                }
10699            }
10700        }
10701        // Delete the updated package
10702        outInfo.isRemovedPackageSystemUpdate = true;
10703        if (disabledPs.versionCode < newPs.versionCode) {
10704            // Delete data for downgrades
10705            flags &= ~PackageManager.DELETE_KEEP_DATA;
10706        } else {
10707            // Preserve data by setting flag
10708            flags |= PackageManager.DELETE_KEEP_DATA;
10709        }
10710        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10711                allUserHandles, perUserInstalled, outInfo, writeSettings);
10712        if (!ret) {
10713            return false;
10714        }
10715        // writer
10716        synchronized (mPackages) {
10717            // Reinstate the old system package
10718            mSettings.enableSystemPackageLPw(newPs.name);
10719            // Remove any native libraries from the upgraded package.
10720            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10721        }
10722        // Install the system package
10723        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10724        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10725        if (locationIsPrivileged(disabledPs.codePath)) {
10726            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10727        }
10728
10729        final PackageParser.Package newPkg;
10730        try {
10731            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10732        } catch (PackageManagerException e) {
10733            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10734            return false;
10735        }
10736
10737        // writer
10738        synchronized (mPackages) {
10739            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10740            updatePermissionsLPw(newPkg.packageName, newPkg,
10741                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10742            if (applyUserRestrictions) {
10743                if (DEBUG_REMOVE) {
10744                    Slog.d(TAG, "Propagating install state across reinstall");
10745                }
10746                for (int i = 0; i < allUserHandles.length; i++) {
10747                    if (DEBUG_REMOVE) {
10748                        Slog.d(TAG, "    user " + allUserHandles[i]
10749                                + " => " + perUserInstalled[i]);
10750                    }
10751                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10752                }
10753                // Regardless of writeSettings we need to ensure that this restriction
10754                // state propagation is persisted
10755                mSettings.writeAllUsersPackageRestrictionsLPr();
10756            }
10757            // can downgrade to reader here
10758            if (writeSettings) {
10759                mSettings.writeLPr();
10760            }
10761        }
10762        return true;
10763    }
10764
10765    private boolean deleteInstalledPackageLI(PackageSetting ps,
10766            boolean deleteCodeAndResources, int flags,
10767            int[] allUserHandles, boolean[] perUserInstalled,
10768            PackageRemovedInfo outInfo, boolean writeSettings) {
10769        if (outInfo != null) {
10770            outInfo.uid = ps.appId;
10771        }
10772
10773        // Delete package data from internal structures and also remove data if flag is set
10774        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10775
10776        // Delete application code and resources
10777        if (deleteCodeAndResources && (outInfo != null)) {
10778            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10779                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10780                    getAppDexInstructionSets(ps));
10781            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10782        }
10783        return true;
10784    }
10785
10786    @Override
10787    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10788            int userId) {
10789        mContext.enforceCallingOrSelfPermission(
10790                android.Manifest.permission.DELETE_PACKAGES, null);
10791        synchronized (mPackages) {
10792            PackageSetting ps = mSettings.mPackages.get(packageName);
10793            if (ps == null) {
10794                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10795                return false;
10796            }
10797            if (!ps.getInstalled(userId)) {
10798                // Can't block uninstall for an app that is not installed or enabled.
10799                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10800                return false;
10801            }
10802            ps.setBlockUninstall(blockUninstall, userId);
10803            mSettings.writePackageRestrictionsLPr(userId);
10804        }
10805        return true;
10806    }
10807
10808    @Override
10809    public boolean getBlockUninstallForUser(String packageName, int userId) {
10810        synchronized (mPackages) {
10811            PackageSetting ps = mSettings.mPackages.get(packageName);
10812            if (ps == null) {
10813                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10814                return false;
10815            }
10816            return ps.getBlockUninstall(userId);
10817        }
10818    }
10819
10820    /*
10821     * This method handles package deletion in general
10822     */
10823    private boolean deletePackageLI(String packageName, UserHandle user,
10824            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10825            int flags, PackageRemovedInfo outInfo,
10826            boolean writeSettings) {
10827        if (packageName == null) {
10828            Slog.w(TAG, "Attempt to delete null packageName.");
10829            return false;
10830        }
10831        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10832        PackageSetting ps;
10833        boolean dataOnly = false;
10834        int removeUser = -1;
10835        int appId = -1;
10836        synchronized (mPackages) {
10837            ps = mSettings.mPackages.get(packageName);
10838            if (ps == null) {
10839                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10840                return false;
10841            }
10842            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10843                    && user.getIdentifier() != UserHandle.USER_ALL) {
10844                // The caller is asking that the package only be deleted for a single
10845                // user.  To do this, we just mark its uninstalled state and delete
10846                // its data.  If this is a system app, we only allow this to happen if
10847                // they have set the special DELETE_SYSTEM_APP which requests different
10848                // semantics than normal for uninstalling system apps.
10849                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10850                ps.setUserState(user.getIdentifier(),
10851                        COMPONENT_ENABLED_STATE_DEFAULT,
10852                        false, //installed
10853                        true,  //stopped
10854                        true,  //notLaunched
10855                        false, //hidden
10856                        null, null, null,
10857                        false // blockUninstall
10858                        );
10859                if (!isSystemApp(ps)) {
10860                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10861                        // Other user still have this package installed, so all
10862                        // we need to do is clear this user's data and save that
10863                        // it is uninstalled.
10864                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10865                        removeUser = user.getIdentifier();
10866                        appId = ps.appId;
10867                        mSettings.writePackageRestrictionsLPr(removeUser);
10868                    } else {
10869                        // We need to set it back to 'installed' so the uninstall
10870                        // broadcasts will be sent correctly.
10871                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10872                        ps.setInstalled(true, user.getIdentifier());
10873                    }
10874                } else {
10875                    // This is a system app, so we assume that the
10876                    // other users still have this package installed, so all
10877                    // we need to do is clear this user's data and save that
10878                    // it is uninstalled.
10879                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10880                    removeUser = user.getIdentifier();
10881                    appId = ps.appId;
10882                    mSettings.writePackageRestrictionsLPr(removeUser);
10883                }
10884            }
10885        }
10886
10887        if (removeUser >= 0) {
10888            // From above, we determined that we are deleting this only
10889            // for a single user.  Continue the work here.
10890            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10891            if (outInfo != null) {
10892                outInfo.removedPackage = packageName;
10893                outInfo.removedAppId = appId;
10894                outInfo.removedUsers = new int[] {removeUser};
10895            }
10896            mInstaller.clearUserData(packageName, removeUser);
10897            removeKeystoreDataIfNeeded(removeUser, appId);
10898            schedulePackageCleaning(packageName, removeUser, false);
10899            return true;
10900        }
10901
10902        if (dataOnly) {
10903            // Delete application data first
10904            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10905            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10906            return true;
10907        }
10908
10909        boolean ret = false;
10910        if (isSystemApp(ps)) {
10911            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10912            // When an updated system application is deleted we delete the existing resources as well and
10913            // fall back to existing code in system partition
10914            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10915                    flags, outInfo, writeSettings);
10916        } else {
10917            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10918            // Kill application pre-emptively especially for apps on sd.
10919            killApplication(packageName, ps.appId, "uninstall pkg");
10920            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10921                    allUserHandles, perUserInstalled,
10922                    outInfo, writeSettings);
10923        }
10924
10925        return ret;
10926    }
10927
10928    private final class ClearStorageConnection implements ServiceConnection {
10929        IMediaContainerService mContainerService;
10930
10931        @Override
10932        public void onServiceConnected(ComponentName name, IBinder service) {
10933            synchronized (this) {
10934                mContainerService = IMediaContainerService.Stub.asInterface(service);
10935                notifyAll();
10936            }
10937        }
10938
10939        @Override
10940        public void onServiceDisconnected(ComponentName name) {
10941        }
10942    }
10943
10944    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10945        final boolean mounted;
10946        if (Environment.isExternalStorageEmulated()) {
10947            mounted = true;
10948        } else {
10949            final String status = Environment.getExternalStorageState();
10950
10951            mounted = status.equals(Environment.MEDIA_MOUNTED)
10952                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10953        }
10954
10955        if (!mounted) {
10956            return;
10957        }
10958
10959        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10960        int[] users;
10961        if (userId == UserHandle.USER_ALL) {
10962            users = sUserManager.getUserIds();
10963        } else {
10964            users = new int[] { userId };
10965        }
10966        final ClearStorageConnection conn = new ClearStorageConnection();
10967        if (mContext.bindServiceAsUser(
10968                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10969            try {
10970                for (int curUser : users) {
10971                    long timeout = SystemClock.uptimeMillis() + 5000;
10972                    synchronized (conn) {
10973                        long now = SystemClock.uptimeMillis();
10974                        while (conn.mContainerService == null && now < timeout) {
10975                            try {
10976                                conn.wait(timeout - now);
10977                            } catch (InterruptedException e) {
10978                            }
10979                        }
10980                    }
10981                    if (conn.mContainerService == null) {
10982                        return;
10983                    }
10984
10985                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10986                    clearDirectory(conn.mContainerService,
10987                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10988                    if (allData) {
10989                        clearDirectory(conn.mContainerService,
10990                                userEnv.buildExternalStorageAppDataDirs(packageName));
10991                        clearDirectory(conn.mContainerService,
10992                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10993                    }
10994                }
10995            } finally {
10996                mContext.unbindService(conn);
10997            }
10998        }
10999    }
11000
11001    @Override
11002    public void clearApplicationUserData(final String packageName,
11003            final IPackageDataObserver observer, final int userId) {
11004        mContext.enforceCallingOrSelfPermission(
11005                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11006        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11007        // Queue up an async operation since the package deletion may take a little while.
11008        mHandler.post(new Runnable() {
11009            public void run() {
11010                mHandler.removeCallbacks(this);
11011                final boolean succeeded;
11012                synchronized (mInstallLock) {
11013                    succeeded = clearApplicationUserDataLI(packageName, userId);
11014                }
11015                clearExternalStorageDataSync(packageName, userId, true);
11016                if (succeeded) {
11017                    // invoke DeviceStorageMonitor's update method to clear any notifications
11018                    DeviceStorageMonitorInternal
11019                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11020                    if (dsm != null) {
11021                        dsm.checkMemory();
11022                    }
11023                }
11024                if(observer != null) {
11025                    try {
11026                        observer.onRemoveCompleted(packageName, succeeded);
11027                    } catch (RemoteException e) {
11028                        Log.i(TAG, "Observer no longer exists.");
11029                    }
11030                } //end if observer
11031            } //end run
11032        });
11033    }
11034
11035    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11036        if (packageName == null) {
11037            Slog.w(TAG, "Attempt to delete null packageName.");
11038            return false;
11039        }
11040
11041        // Try finding details about the requested package
11042        PackageParser.Package pkg;
11043        synchronized (mPackages) {
11044            pkg = mPackages.get(packageName);
11045            if (pkg == null) {
11046                final PackageSetting ps = mSettings.mPackages.get(packageName);
11047                if (ps != null) {
11048                    pkg = ps.pkg;
11049                }
11050            }
11051        }
11052
11053        if (pkg == null) {
11054            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11055        }
11056
11057        // Always delete data directories for package, even if we found no other
11058        // record of app. This helps users recover from UID mismatches without
11059        // resorting to a full data wipe.
11060        int retCode = mInstaller.clearUserData(packageName, userId);
11061        if (retCode < 0) {
11062            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11063            return false;
11064        }
11065
11066        if (pkg == null) {
11067            return false;
11068        }
11069
11070        if (pkg != null && pkg.applicationInfo != null) {
11071            final int appId = pkg.applicationInfo.uid;
11072            removeKeystoreDataIfNeeded(userId, appId);
11073        }
11074
11075        // Create a native library symlink only if we have native libraries
11076        // and if the native libraries are 32 bit libraries. We do not provide
11077        // this symlink for 64 bit libraries.
11078        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11079                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11080            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11081            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11082                Slog.w(TAG, "Failed linking native library dir");
11083                return false;
11084            }
11085        }
11086
11087        return true;
11088    }
11089
11090    /**
11091     * Remove entries from the keystore daemon. Will only remove it if the
11092     * {@code appId} is valid.
11093     */
11094    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11095        if (appId < 0) {
11096            return;
11097        }
11098
11099        final KeyStore keyStore = KeyStore.getInstance();
11100        if (keyStore != null) {
11101            if (userId == UserHandle.USER_ALL) {
11102                for (final int individual : sUserManager.getUserIds()) {
11103                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11104                }
11105            } else {
11106                keyStore.clearUid(UserHandle.getUid(userId, appId));
11107            }
11108        } else {
11109            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11110        }
11111    }
11112
11113    @Override
11114    public void deleteApplicationCacheFiles(final String packageName,
11115            final IPackageDataObserver observer) {
11116        mContext.enforceCallingOrSelfPermission(
11117                android.Manifest.permission.DELETE_CACHE_FILES, null);
11118        // Queue up an async operation since the package deletion may take a little while.
11119        final int userId = UserHandle.getCallingUserId();
11120        mHandler.post(new Runnable() {
11121            public void run() {
11122                mHandler.removeCallbacks(this);
11123                final boolean succeded;
11124                synchronized (mInstallLock) {
11125                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11126                }
11127                clearExternalStorageDataSync(packageName, userId, false);
11128                if(observer != null) {
11129                    try {
11130                        observer.onRemoveCompleted(packageName, succeded);
11131                    } catch (RemoteException e) {
11132                        Log.i(TAG, "Observer no longer exists.");
11133                    }
11134                } //end if observer
11135            } //end run
11136        });
11137    }
11138
11139    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11140        if (packageName == null) {
11141            Slog.w(TAG, "Attempt to delete null packageName.");
11142            return false;
11143        }
11144        PackageParser.Package p;
11145        synchronized (mPackages) {
11146            p = mPackages.get(packageName);
11147        }
11148        if (p == null) {
11149            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11150            return false;
11151        }
11152        final ApplicationInfo applicationInfo = p.applicationInfo;
11153        if (applicationInfo == null) {
11154            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11155            return false;
11156        }
11157        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11158        if (retCode < 0) {
11159            Slog.w(TAG, "Couldn't remove cache files for package: "
11160                       + packageName + " u" + userId);
11161            return false;
11162        }
11163        return true;
11164    }
11165
11166    @Override
11167    public void getPackageSizeInfo(final String packageName, int userHandle,
11168            final IPackageStatsObserver observer) {
11169        mContext.enforceCallingOrSelfPermission(
11170                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11171        if (packageName == null) {
11172            throw new IllegalArgumentException("Attempt to get size of null packageName");
11173        }
11174
11175        PackageStats stats = new PackageStats(packageName, userHandle);
11176
11177        /*
11178         * Queue up an async operation since the package measurement may take a
11179         * little while.
11180         */
11181        Message msg = mHandler.obtainMessage(INIT_COPY);
11182        msg.obj = new MeasureParams(stats, observer);
11183        mHandler.sendMessage(msg);
11184    }
11185
11186    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11187            PackageStats pStats) {
11188        if (packageName == null) {
11189            Slog.w(TAG, "Attempt to get size of null packageName.");
11190            return false;
11191        }
11192        PackageParser.Package p;
11193        boolean dataOnly = false;
11194        String libDirRoot = null;
11195        String asecPath = null;
11196        PackageSetting ps = null;
11197        synchronized (mPackages) {
11198            p = mPackages.get(packageName);
11199            ps = mSettings.mPackages.get(packageName);
11200            if(p == null) {
11201                dataOnly = true;
11202                if((ps == null) || (ps.pkg == null)) {
11203                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11204                    return false;
11205                }
11206                p = ps.pkg;
11207            }
11208            if (ps != null) {
11209                libDirRoot = ps.legacyNativeLibraryPathString;
11210            }
11211            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11212                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11213                if (secureContainerId != null) {
11214                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11215                }
11216            }
11217        }
11218        String publicSrcDir = null;
11219        if(!dataOnly) {
11220            final ApplicationInfo applicationInfo = p.applicationInfo;
11221            if (applicationInfo == null) {
11222                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11223                return false;
11224            }
11225            if (isForwardLocked(p)) {
11226                publicSrcDir = applicationInfo.getBaseResourcePath();
11227            }
11228        }
11229        // TODO: extend to measure size of split APKs
11230        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11231        // not just the first level.
11232        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11233        // just the primary.
11234        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11235        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11236                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11237        if (res < 0) {
11238            return false;
11239        }
11240
11241        // Fix-up for forward-locked applications in ASEC containers.
11242        if (!isExternal(p)) {
11243            pStats.codeSize += pStats.externalCodeSize;
11244            pStats.externalCodeSize = 0L;
11245        }
11246
11247        return true;
11248    }
11249
11250
11251    @Override
11252    public void addPackageToPreferred(String packageName) {
11253        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11254    }
11255
11256    @Override
11257    public void removePackageFromPreferred(String packageName) {
11258        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11259    }
11260
11261    @Override
11262    public List<PackageInfo> getPreferredPackages(int flags) {
11263        return new ArrayList<PackageInfo>();
11264    }
11265
11266    private int getUidTargetSdkVersionLockedLPr(int uid) {
11267        Object obj = mSettings.getUserIdLPr(uid);
11268        if (obj instanceof SharedUserSetting) {
11269            final SharedUserSetting sus = (SharedUserSetting) obj;
11270            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11271            final Iterator<PackageSetting> it = sus.packages.iterator();
11272            while (it.hasNext()) {
11273                final PackageSetting ps = it.next();
11274                if (ps.pkg != null) {
11275                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11276                    if (v < vers) vers = v;
11277                }
11278            }
11279            return vers;
11280        } else if (obj instanceof PackageSetting) {
11281            final PackageSetting ps = (PackageSetting) obj;
11282            if (ps.pkg != null) {
11283                return ps.pkg.applicationInfo.targetSdkVersion;
11284            }
11285        }
11286        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11287    }
11288
11289    @Override
11290    public void addPreferredActivity(IntentFilter filter, int match,
11291            ComponentName[] set, ComponentName activity, int userId) {
11292        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11293                "Adding preferred");
11294    }
11295
11296    private void addPreferredActivityInternal(IntentFilter filter, int match,
11297            ComponentName[] set, ComponentName activity, boolean always, int userId,
11298            String opname) {
11299        // writer
11300        int callingUid = Binder.getCallingUid();
11301        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11302        if (filter.countActions() == 0) {
11303            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11304            return;
11305        }
11306        synchronized (mPackages) {
11307            if (mContext.checkCallingOrSelfPermission(
11308                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11309                    != PackageManager.PERMISSION_GRANTED) {
11310                if (getUidTargetSdkVersionLockedLPr(callingUid)
11311                        < Build.VERSION_CODES.FROYO) {
11312                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11313                            + callingUid);
11314                    return;
11315                }
11316                mContext.enforceCallingOrSelfPermission(
11317                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11318            }
11319
11320            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11321            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11322                    + userId + ":");
11323            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11324            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11325            mSettings.writePackageRestrictionsLPr(userId);
11326        }
11327    }
11328
11329    @Override
11330    public void replacePreferredActivity(IntentFilter filter, int match,
11331            ComponentName[] set, ComponentName activity, int userId) {
11332        if (filter.countActions() != 1) {
11333            throw new IllegalArgumentException(
11334                    "replacePreferredActivity expects filter to have only 1 action.");
11335        }
11336        if (filter.countDataAuthorities() != 0
11337                || filter.countDataPaths() != 0
11338                || filter.countDataSchemes() > 1
11339                || filter.countDataTypes() != 0) {
11340            throw new IllegalArgumentException(
11341                    "replacePreferredActivity expects filter to have no data authorities, " +
11342                    "paths, or types; and at most one scheme.");
11343        }
11344
11345        final int callingUid = Binder.getCallingUid();
11346        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11347        synchronized (mPackages) {
11348            if (mContext.checkCallingOrSelfPermission(
11349                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11350                    != PackageManager.PERMISSION_GRANTED) {
11351                if (getUidTargetSdkVersionLockedLPr(callingUid)
11352                        < Build.VERSION_CODES.FROYO) {
11353                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11354                            + Binder.getCallingUid());
11355                    return;
11356                }
11357                mContext.enforceCallingOrSelfPermission(
11358                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11359            }
11360
11361            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11362            if (pir != null) {
11363                // Get all of the existing entries that exactly match this filter.
11364                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11365                if (existing != null && existing.size() == 1) {
11366                    PreferredActivity cur = existing.get(0);
11367                    if (DEBUG_PREFERRED) {
11368                        Slog.i(TAG, "Checking replace of preferred:");
11369                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11370                        if (!cur.mPref.mAlways) {
11371                            Slog.i(TAG, "  -- CUR; not mAlways!");
11372                        } else {
11373                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11374                            Slog.i(TAG, "  -- CUR: mSet="
11375                                    + Arrays.toString(cur.mPref.mSetComponents));
11376                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11377                            Slog.i(TAG, "  -- NEW: mMatch="
11378                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11379                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11380                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11381                        }
11382                    }
11383                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11384                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11385                            && cur.mPref.sameSet(set)) {
11386                        // Setting the preferred activity to what it happens to be already
11387                        if (DEBUG_PREFERRED) {
11388                            Slog.i(TAG, "Replacing with same preferred activity "
11389                                    + cur.mPref.mShortComponent + " for user "
11390                                    + userId + ":");
11391                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11392                        }
11393                        return;
11394                    }
11395                }
11396
11397                if (existing != null) {
11398                    if (DEBUG_PREFERRED) {
11399                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11400                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11401                    }
11402                    for (int i = 0; i < existing.size(); i++) {
11403                        PreferredActivity pa = existing.get(i);
11404                        if (DEBUG_PREFERRED) {
11405                            Slog.i(TAG, "Removing existing preferred activity "
11406                                    + pa.mPref.mComponent + ":");
11407                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11408                        }
11409                        pir.removeFilter(pa);
11410                    }
11411                }
11412            }
11413            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11414                    "Replacing preferred");
11415        }
11416    }
11417
11418    @Override
11419    public void clearPackagePreferredActivities(String packageName) {
11420        final int uid = Binder.getCallingUid();
11421        // writer
11422        synchronized (mPackages) {
11423            PackageParser.Package pkg = mPackages.get(packageName);
11424            if (pkg == null || pkg.applicationInfo.uid != uid) {
11425                if (mContext.checkCallingOrSelfPermission(
11426                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11427                        != PackageManager.PERMISSION_GRANTED) {
11428                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11429                            < Build.VERSION_CODES.FROYO) {
11430                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11431                                + Binder.getCallingUid());
11432                        return;
11433                    }
11434                    mContext.enforceCallingOrSelfPermission(
11435                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11436                }
11437            }
11438
11439            int user = UserHandle.getCallingUserId();
11440            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11441                mSettings.writePackageRestrictionsLPr(user);
11442                scheduleWriteSettingsLocked();
11443            }
11444        }
11445    }
11446
11447    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11448    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11449        ArrayList<PreferredActivity> removed = null;
11450        boolean changed = false;
11451        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11452            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11453            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11454            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11455                continue;
11456            }
11457            Iterator<PreferredActivity> it = pir.filterIterator();
11458            while (it.hasNext()) {
11459                PreferredActivity pa = it.next();
11460                // Mark entry for removal only if it matches the package name
11461                // and the entry is of type "always".
11462                if (packageName == null ||
11463                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11464                                && pa.mPref.mAlways)) {
11465                    if (removed == null) {
11466                        removed = new ArrayList<PreferredActivity>();
11467                    }
11468                    removed.add(pa);
11469                }
11470            }
11471            if (removed != null) {
11472                for (int j=0; j<removed.size(); j++) {
11473                    PreferredActivity pa = removed.get(j);
11474                    pir.removeFilter(pa);
11475                }
11476                changed = true;
11477            }
11478        }
11479        return changed;
11480    }
11481
11482    @Override
11483    public void resetPreferredActivities(int userId) {
11484        /* TODO: Actually use userId. Why is it being passed in? */
11485        mContext.enforceCallingOrSelfPermission(
11486                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11487        // writer
11488        synchronized (mPackages) {
11489            int user = UserHandle.getCallingUserId();
11490            clearPackagePreferredActivitiesLPw(null, user);
11491            mSettings.readDefaultPreferredAppsLPw(this, user);
11492            mSettings.writePackageRestrictionsLPr(user);
11493            scheduleWriteSettingsLocked();
11494        }
11495    }
11496
11497    @Override
11498    public int getPreferredActivities(List<IntentFilter> outFilters,
11499            List<ComponentName> outActivities, String packageName) {
11500
11501        int num = 0;
11502        final int userId = UserHandle.getCallingUserId();
11503        // reader
11504        synchronized (mPackages) {
11505            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11506            if (pir != null) {
11507                final Iterator<PreferredActivity> it = pir.filterIterator();
11508                while (it.hasNext()) {
11509                    final PreferredActivity pa = it.next();
11510                    if (packageName == null
11511                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11512                                    && pa.mPref.mAlways)) {
11513                        if (outFilters != null) {
11514                            outFilters.add(new IntentFilter(pa));
11515                        }
11516                        if (outActivities != null) {
11517                            outActivities.add(pa.mPref.mComponent);
11518                        }
11519                    }
11520                }
11521            }
11522        }
11523
11524        return num;
11525    }
11526
11527    @Override
11528    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11529            int userId) {
11530        int callingUid = Binder.getCallingUid();
11531        if (callingUid != Process.SYSTEM_UID) {
11532            throw new SecurityException(
11533                    "addPersistentPreferredActivity can only be run by the system");
11534        }
11535        if (filter.countActions() == 0) {
11536            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11537            return;
11538        }
11539        synchronized (mPackages) {
11540            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11541                    " :");
11542            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11543            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11544                    new PersistentPreferredActivity(filter, activity));
11545            mSettings.writePackageRestrictionsLPr(userId);
11546        }
11547    }
11548
11549    @Override
11550    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11551        int callingUid = Binder.getCallingUid();
11552        if (callingUid != Process.SYSTEM_UID) {
11553            throw new SecurityException(
11554                    "clearPackagePersistentPreferredActivities can only be run by the system");
11555        }
11556        ArrayList<PersistentPreferredActivity> removed = null;
11557        boolean changed = false;
11558        synchronized (mPackages) {
11559            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11560                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11561                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11562                        .valueAt(i);
11563                if (userId != thisUserId) {
11564                    continue;
11565                }
11566                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11567                while (it.hasNext()) {
11568                    PersistentPreferredActivity ppa = it.next();
11569                    // Mark entry for removal only if it matches the package name.
11570                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11571                        if (removed == null) {
11572                            removed = new ArrayList<PersistentPreferredActivity>();
11573                        }
11574                        removed.add(ppa);
11575                    }
11576                }
11577                if (removed != null) {
11578                    for (int j=0; j<removed.size(); j++) {
11579                        PersistentPreferredActivity ppa = removed.get(j);
11580                        ppir.removeFilter(ppa);
11581                    }
11582                    changed = true;
11583                }
11584            }
11585
11586            if (changed) {
11587                mSettings.writePackageRestrictionsLPr(userId);
11588            }
11589        }
11590    }
11591
11592    @Override
11593    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11594            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11595        mContext.enforceCallingOrSelfPermission(
11596                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11597        int callingUid = Binder.getCallingUid();
11598        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11599        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11600        if (intentFilter.countActions() == 0) {
11601            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11602            return;
11603        }
11604        synchronized (mPackages) {
11605            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11606                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11607            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11608            mSettings.writePackageRestrictionsLPr(sourceUserId);
11609        }
11610    }
11611
11612    @Override
11613    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11614            int ownerUserId) {
11615        mContext.enforceCallingOrSelfPermission(
11616                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11617        int callingUid = Binder.getCallingUid();
11618        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11619        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11620        int callingUserId = UserHandle.getUserId(callingUid);
11621        synchronized (mPackages) {
11622            CrossProfileIntentResolver resolver =
11623                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11624            HashSet<CrossProfileIntentFilter> set =
11625                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11626            for (CrossProfileIntentFilter filter : set) {
11627                if (filter.getOwnerPackage().equals(ownerPackage)
11628                        && filter.getOwnerUserId() == callingUserId) {
11629                    resolver.removeFilter(filter);
11630                }
11631            }
11632            mSettings.writePackageRestrictionsLPr(sourceUserId);
11633        }
11634    }
11635
11636    // Enforcing that callingUid is owning pkg on userId
11637    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11638        // The system owns everything.
11639        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11640            return;
11641        }
11642        int callingUserId = UserHandle.getUserId(callingUid);
11643        if (callingUserId != userId) {
11644            throw new SecurityException("calling uid " + callingUid
11645                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11646                    + callingUserId);
11647        }
11648        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11649        if (pi == null) {
11650            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11651                    + callingUserId);
11652        }
11653        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11654            throw new SecurityException("Calling uid " + callingUid
11655                    + " does not own package " + pkg);
11656        }
11657    }
11658
11659    @Override
11660    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11661        Intent intent = new Intent(Intent.ACTION_MAIN);
11662        intent.addCategory(Intent.CATEGORY_HOME);
11663
11664        final int callingUserId = UserHandle.getCallingUserId();
11665        List<ResolveInfo> list = queryIntentActivities(intent, null,
11666                PackageManager.GET_META_DATA, callingUserId);
11667        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11668                true, false, false, callingUserId);
11669
11670        allHomeCandidates.clear();
11671        if (list != null) {
11672            for (ResolveInfo ri : list) {
11673                allHomeCandidates.add(ri);
11674            }
11675        }
11676        return (preferred == null || preferred.activityInfo == null)
11677                ? null
11678                : new ComponentName(preferred.activityInfo.packageName,
11679                        preferred.activityInfo.name);
11680    }
11681
11682    @Override
11683    public void setApplicationEnabledSetting(String appPackageName,
11684            int newState, int flags, int userId, String callingPackage) {
11685        if (!sUserManager.exists(userId)) return;
11686        if (callingPackage == null) {
11687            callingPackage = Integer.toString(Binder.getCallingUid());
11688        }
11689        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11690    }
11691
11692    @Override
11693    public void setComponentEnabledSetting(ComponentName componentName,
11694            int newState, int flags, int userId) {
11695        if (!sUserManager.exists(userId)) return;
11696        setEnabledSetting(componentName.getPackageName(),
11697                componentName.getClassName(), newState, flags, userId, null);
11698    }
11699
11700    private void setEnabledSetting(final String packageName, String className, int newState,
11701            final int flags, int userId, String callingPackage) {
11702        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11703              || newState == COMPONENT_ENABLED_STATE_ENABLED
11704              || newState == COMPONENT_ENABLED_STATE_DISABLED
11705              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11706              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11707            throw new IllegalArgumentException("Invalid new component state: "
11708                    + newState);
11709        }
11710        PackageSetting pkgSetting;
11711        final int uid = Binder.getCallingUid();
11712        final int permission = mContext.checkCallingOrSelfPermission(
11713                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11714        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11715        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11716        boolean sendNow = false;
11717        boolean isApp = (className == null);
11718        String componentName = isApp ? packageName : className;
11719        int packageUid = -1;
11720        ArrayList<String> components;
11721
11722        // writer
11723        synchronized (mPackages) {
11724            pkgSetting = mSettings.mPackages.get(packageName);
11725            if (pkgSetting == null) {
11726                if (className == null) {
11727                    throw new IllegalArgumentException(
11728                            "Unknown package: " + packageName);
11729                }
11730                throw new IllegalArgumentException(
11731                        "Unknown component: " + packageName
11732                        + "/" + className);
11733            }
11734            // Allow root and verify that userId is not being specified by a different user
11735            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11736                throw new SecurityException(
11737                        "Permission Denial: attempt to change component state from pid="
11738                        + Binder.getCallingPid()
11739                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11740            }
11741            if (className == null) {
11742                // We're dealing with an application/package level state change
11743                if (pkgSetting.getEnabled(userId) == newState) {
11744                    // Nothing to do
11745                    return;
11746                }
11747                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11748                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11749                    // Don't care about who enables an app.
11750                    callingPackage = null;
11751                }
11752                pkgSetting.setEnabled(newState, userId, callingPackage);
11753                // pkgSetting.pkg.mSetEnabled = newState;
11754            } else {
11755                // We're dealing with a component level state change
11756                // First, verify that this is a valid class name.
11757                PackageParser.Package pkg = pkgSetting.pkg;
11758                if (pkg == null || !pkg.hasComponentClassName(className)) {
11759                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11760                        throw new IllegalArgumentException("Component class " + className
11761                                + " does not exist in " + packageName);
11762                    } else {
11763                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11764                                + className + " does not exist in " + packageName);
11765                    }
11766                }
11767                switch (newState) {
11768                case COMPONENT_ENABLED_STATE_ENABLED:
11769                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11770                        return;
11771                    }
11772                    break;
11773                case COMPONENT_ENABLED_STATE_DISABLED:
11774                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11775                        return;
11776                    }
11777                    break;
11778                case COMPONENT_ENABLED_STATE_DEFAULT:
11779                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11780                        return;
11781                    }
11782                    break;
11783                default:
11784                    Slog.e(TAG, "Invalid new component state: " + newState);
11785                    return;
11786                }
11787            }
11788            mSettings.writePackageRestrictionsLPr(userId);
11789            components = mPendingBroadcasts.get(userId, packageName);
11790            final boolean newPackage = components == null;
11791            if (newPackage) {
11792                components = new ArrayList<String>();
11793            }
11794            if (!components.contains(componentName)) {
11795                components.add(componentName);
11796            }
11797            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11798                sendNow = true;
11799                // Purge entry from pending broadcast list if another one exists already
11800                // since we are sending one right away.
11801                mPendingBroadcasts.remove(userId, packageName);
11802            } else {
11803                if (newPackage) {
11804                    mPendingBroadcasts.put(userId, packageName, components);
11805                }
11806                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11807                    // Schedule a message
11808                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11809                }
11810            }
11811        }
11812
11813        long callingId = Binder.clearCallingIdentity();
11814        try {
11815            if (sendNow) {
11816                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11817                sendPackageChangedBroadcast(packageName,
11818                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11819            }
11820        } finally {
11821            Binder.restoreCallingIdentity(callingId);
11822        }
11823    }
11824
11825    private void sendPackageChangedBroadcast(String packageName,
11826            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11827        if (DEBUG_INSTALL)
11828            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11829                    + componentNames);
11830        Bundle extras = new Bundle(4);
11831        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11832        String nameList[] = new String[componentNames.size()];
11833        componentNames.toArray(nameList);
11834        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11835        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11836        extras.putInt(Intent.EXTRA_UID, packageUid);
11837        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11838                new int[] {UserHandle.getUserId(packageUid)});
11839    }
11840
11841    @Override
11842    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11843        if (!sUserManager.exists(userId)) return;
11844        final int uid = Binder.getCallingUid();
11845        final int permission = mContext.checkCallingOrSelfPermission(
11846                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11847        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11848        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11849        // writer
11850        synchronized (mPackages) {
11851            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11852                    uid, userId)) {
11853                scheduleWritePackageRestrictionsLocked(userId);
11854            }
11855        }
11856    }
11857
11858    @Override
11859    public String getInstallerPackageName(String packageName) {
11860        // reader
11861        synchronized (mPackages) {
11862            return mSettings.getInstallerPackageNameLPr(packageName);
11863        }
11864    }
11865
11866    @Override
11867    public int getApplicationEnabledSetting(String packageName, int userId) {
11868        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11869        int uid = Binder.getCallingUid();
11870        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11871        // reader
11872        synchronized (mPackages) {
11873            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11874        }
11875    }
11876
11877    @Override
11878    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11879        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11880        int uid = Binder.getCallingUid();
11881        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11882        // reader
11883        synchronized (mPackages) {
11884            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11885        }
11886    }
11887
11888    @Override
11889    public void enterSafeMode() {
11890        enforceSystemOrRoot("Only the system can request entering safe mode");
11891
11892        if (!mSystemReady) {
11893            mSafeMode = true;
11894        }
11895    }
11896
11897    @Override
11898    public void systemReady() {
11899        mSystemReady = true;
11900
11901        // Read the compatibilty setting when the system is ready.
11902        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11903                mContext.getContentResolver(),
11904                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11905        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11906        if (DEBUG_SETTINGS) {
11907            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11908        }
11909
11910        synchronized (mPackages) {
11911            // Verify that all of the preferred activity components actually
11912            // exist.  It is possible for applications to be updated and at
11913            // that point remove a previously declared activity component that
11914            // had been set as a preferred activity.  We try to clean this up
11915            // the next time we encounter that preferred activity, but it is
11916            // possible for the user flow to never be able to return to that
11917            // situation so here we do a sanity check to make sure we haven't
11918            // left any junk around.
11919            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11920            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11921                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11922                removed.clear();
11923                for (PreferredActivity pa : pir.filterSet()) {
11924                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11925                        removed.add(pa);
11926                    }
11927                }
11928                if (removed.size() > 0) {
11929                    for (int r=0; r<removed.size(); r++) {
11930                        PreferredActivity pa = removed.get(r);
11931                        Slog.w(TAG, "Removing dangling preferred activity: "
11932                                + pa.mPref.mComponent);
11933                        pir.removeFilter(pa);
11934                    }
11935                    mSettings.writePackageRestrictionsLPr(
11936                            mSettings.mPreferredActivities.keyAt(i));
11937                }
11938            }
11939        }
11940        sUserManager.systemReady();
11941
11942        // Kick off any messages waiting for system ready
11943        if (mPostSystemReadyMessages != null) {
11944            for (Message msg : mPostSystemReadyMessages) {
11945                msg.sendToTarget();
11946            }
11947            mPostSystemReadyMessages = null;
11948        }
11949    }
11950
11951    @Override
11952    public boolean isSafeMode() {
11953        return mSafeMode;
11954    }
11955
11956    @Override
11957    public boolean hasSystemUidErrors() {
11958        return mHasSystemUidErrors;
11959    }
11960
11961    static String arrayToString(int[] array) {
11962        StringBuffer buf = new StringBuffer(128);
11963        buf.append('[');
11964        if (array != null) {
11965            for (int i=0; i<array.length; i++) {
11966                if (i > 0) buf.append(", ");
11967                buf.append(array[i]);
11968            }
11969        }
11970        buf.append(']');
11971        return buf.toString();
11972    }
11973
11974    static class DumpState {
11975        public static final int DUMP_LIBS = 1 << 0;
11976        public static final int DUMP_FEATURES = 1 << 1;
11977        public static final int DUMP_RESOLVERS = 1 << 2;
11978        public static final int DUMP_PERMISSIONS = 1 << 3;
11979        public static final int DUMP_PACKAGES = 1 << 4;
11980        public static final int DUMP_SHARED_USERS = 1 << 5;
11981        public static final int DUMP_MESSAGES = 1 << 6;
11982        public static final int DUMP_PROVIDERS = 1 << 7;
11983        public static final int DUMP_VERIFIERS = 1 << 8;
11984        public static final int DUMP_PREFERRED = 1 << 9;
11985        public static final int DUMP_PREFERRED_XML = 1 << 10;
11986        public static final int DUMP_KEYSETS = 1 << 11;
11987        public static final int DUMP_VERSION = 1 << 12;
11988        public static final int DUMP_INSTALLS = 1 << 13;
11989
11990        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11991
11992        private int mTypes;
11993
11994        private int mOptions;
11995
11996        private boolean mTitlePrinted;
11997
11998        private SharedUserSetting mSharedUser;
11999
12000        public boolean isDumping(int type) {
12001            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12002                return true;
12003            }
12004
12005            return (mTypes & type) != 0;
12006        }
12007
12008        public void setDump(int type) {
12009            mTypes |= type;
12010        }
12011
12012        public boolean isOptionEnabled(int option) {
12013            return (mOptions & option) != 0;
12014        }
12015
12016        public void setOptionEnabled(int option) {
12017            mOptions |= option;
12018        }
12019
12020        public boolean onTitlePrinted() {
12021            final boolean printed = mTitlePrinted;
12022            mTitlePrinted = true;
12023            return printed;
12024        }
12025
12026        public boolean getTitlePrinted() {
12027            return mTitlePrinted;
12028        }
12029
12030        public void setTitlePrinted(boolean enabled) {
12031            mTitlePrinted = enabled;
12032        }
12033
12034        public SharedUserSetting getSharedUser() {
12035            return mSharedUser;
12036        }
12037
12038        public void setSharedUser(SharedUserSetting user) {
12039            mSharedUser = user;
12040        }
12041    }
12042
12043    @Override
12044    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12045        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12046                != PackageManager.PERMISSION_GRANTED) {
12047            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12048                    + Binder.getCallingPid()
12049                    + ", uid=" + Binder.getCallingUid()
12050                    + " without permission "
12051                    + android.Manifest.permission.DUMP);
12052            return;
12053        }
12054
12055        DumpState dumpState = new DumpState();
12056        boolean fullPreferred = false;
12057        boolean checkin = false;
12058
12059        String packageName = null;
12060
12061        int opti = 0;
12062        while (opti < args.length) {
12063            String opt = args[opti];
12064            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12065                break;
12066            }
12067            opti++;
12068            if ("-a".equals(opt)) {
12069                // Right now we only know how to print all.
12070            } else if ("-h".equals(opt)) {
12071                pw.println("Package manager dump options:");
12072                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12073                pw.println("    --checkin: dump for a checkin");
12074                pw.println("    -f: print details of intent filters");
12075                pw.println("    -h: print this help");
12076                pw.println("  cmd may be one of:");
12077                pw.println("    l[ibraries]: list known shared libraries");
12078                pw.println("    f[ibraries]: list device features");
12079                pw.println("    k[eysets]: print known keysets");
12080                pw.println("    r[esolvers]: dump intent resolvers");
12081                pw.println("    perm[issions]: dump permissions");
12082                pw.println("    pref[erred]: print preferred package settings");
12083                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12084                pw.println("    prov[iders]: dump content providers");
12085                pw.println("    p[ackages]: dump installed packages");
12086                pw.println("    s[hared-users]: dump shared user IDs");
12087                pw.println("    m[essages]: print collected runtime messages");
12088                pw.println("    v[erifiers]: print package verifier info");
12089                pw.println("    version: print database version info");
12090                pw.println("    write: write current settings now");
12091                pw.println("    <package.name>: info about given package");
12092                pw.println("    installs: details about install sessions");
12093                return;
12094            } else if ("--checkin".equals(opt)) {
12095                checkin = true;
12096            } else if ("-f".equals(opt)) {
12097                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12098            } else {
12099                pw.println("Unknown argument: " + opt + "; use -h for help");
12100            }
12101        }
12102
12103        // Is the caller requesting to dump a particular piece of data?
12104        if (opti < args.length) {
12105            String cmd = args[opti];
12106            opti++;
12107            // Is this a package name?
12108            if ("android".equals(cmd) || cmd.contains(".")) {
12109                packageName = cmd;
12110                // When dumping a single package, we always dump all of its
12111                // filter information since the amount of data will be reasonable.
12112                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12113            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12114                dumpState.setDump(DumpState.DUMP_LIBS);
12115            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12116                dumpState.setDump(DumpState.DUMP_FEATURES);
12117            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12118                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12119            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12120                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12121            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12122                dumpState.setDump(DumpState.DUMP_PREFERRED);
12123            } else if ("preferred-xml".equals(cmd)) {
12124                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12125                if (opti < args.length && "--full".equals(args[opti])) {
12126                    fullPreferred = true;
12127                    opti++;
12128                }
12129            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12130                dumpState.setDump(DumpState.DUMP_PACKAGES);
12131            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12132                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12133            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12134                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12135            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12136                dumpState.setDump(DumpState.DUMP_MESSAGES);
12137            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12138                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12139            } else if ("version".equals(cmd)) {
12140                dumpState.setDump(DumpState.DUMP_VERSION);
12141            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12142                dumpState.setDump(DumpState.DUMP_KEYSETS);
12143            } else if ("installs".equals(cmd)) {
12144                dumpState.setDump(DumpState.DUMP_INSTALLS);
12145            } else if ("write".equals(cmd)) {
12146                synchronized (mPackages) {
12147                    mSettings.writeLPr();
12148                    pw.println("Settings written.");
12149                    return;
12150                }
12151            }
12152        }
12153
12154        if (checkin) {
12155            pw.println("vers,1");
12156        }
12157
12158        // reader
12159        synchronized (mPackages) {
12160            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12161                if (!checkin) {
12162                    if (dumpState.onTitlePrinted())
12163                        pw.println();
12164                    pw.println("Database versions:");
12165                    pw.print("  SDK Version:");
12166                    pw.print(" internal=");
12167                    pw.print(mSettings.mInternalSdkPlatform);
12168                    pw.print(" external=");
12169                    pw.println(mSettings.mExternalSdkPlatform);
12170                    pw.print("  DB Version:");
12171                    pw.print(" internal=");
12172                    pw.print(mSettings.mInternalDatabaseVersion);
12173                    pw.print(" external=");
12174                    pw.println(mSettings.mExternalDatabaseVersion);
12175                }
12176            }
12177
12178            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12179                if (!checkin) {
12180                    if (dumpState.onTitlePrinted())
12181                        pw.println();
12182                    pw.println("Verifiers:");
12183                    pw.print("  Required: ");
12184                    pw.print(mRequiredVerifierPackage);
12185                    pw.print(" (uid=");
12186                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12187                    pw.println(")");
12188                } else if (mRequiredVerifierPackage != null) {
12189                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12190                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12191                }
12192            }
12193
12194            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12195                boolean printedHeader = false;
12196                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12197                while (it.hasNext()) {
12198                    String name = it.next();
12199                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12200                    if (!checkin) {
12201                        if (!printedHeader) {
12202                            if (dumpState.onTitlePrinted())
12203                                pw.println();
12204                            pw.println("Libraries:");
12205                            printedHeader = true;
12206                        }
12207                        pw.print("  ");
12208                    } else {
12209                        pw.print("lib,");
12210                    }
12211                    pw.print(name);
12212                    if (!checkin) {
12213                        pw.print(" -> ");
12214                    }
12215                    if (ent.path != null) {
12216                        if (!checkin) {
12217                            pw.print("(jar) ");
12218                            pw.print(ent.path);
12219                        } else {
12220                            pw.print(",jar,");
12221                            pw.print(ent.path);
12222                        }
12223                    } else {
12224                        if (!checkin) {
12225                            pw.print("(apk) ");
12226                            pw.print(ent.apk);
12227                        } else {
12228                            pw.print(",apk,");
12229                            pw.print(ent.apk);
12230                        }
12231                    }
12232                    pw.println();
12233                }
12234            }
12235
12236            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12237                if (dumpState.onTitlePrinted())
12238                    pw.println();
12239                if (!checkin) {
12240                    pw.println("Features:");
12241                }
12242                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12243                while (it.hasNext()) {
12244                    String name = it.next();
12245                    if (!checkin) {
12246                        pw.print("  ");
12247                    } else {
12248                        pw.print("feat,");
12249                    }
12250                    pw.println(name);
12251                }
12252            }
12253
12254            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12255                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12256                        : "Activity Resolver Table:", "  ", packageName,
12257                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12258                    dumpState.setTitlePrinted(true);
12259                }
12260                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12261                        : "Receiver Resolver Table:", "  ", packageName,
12262                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12263                    dumpState.setTitlePrinted(true);
12264                }
12265                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12266                        : "Service Resolver Table:", "  ", packageName,
12267                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12268                    dumpState.setTitlePrinted(true);
12269                }
12270                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12271                        : "Provider Resolver Table:", "  ", packageName,
12272                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12273                    dumpState.setTitlePrinted(true);
12274                }
12275            }
12276
12277            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12278                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12279                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12280                    int user = mSettings.mPreferredActivities.keyAt(i);
12281                    if (pir.dump(pw,
12282                            dumpState.getTitlePrinted()
12283                                ? "\nPreferred Activities User " + user + ":"
12284                                : "Preferred Activities User " + user + ":", "  ",
12285                            packageName, true)) {
12286                        dumpState.setTitlePrinted(true);
12287                    }
12288                }
12289            }
12290
12291            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12292                pw.flush();
12293                FileOutputStream fout = new FileOutputStream(fd);
12294                BufferedOutputStream str = new BufferedOutputStream(fout);
12295                XmlSerializer serializer = new FastXmlSerializer();
12296                try {
12297                    serializer.setOutput(str, "utf-8");
12298                    serializer.startDocument(null, true);
12299                    serializer.setFeature(
12300                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12301                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12302                    serializer.endDocument();
12303                    serializer.flush();
12304                } catch (IllegalArgumentException e) {
12305                    pw.println("Failed writing: " + e);
12306                } catch (IllegalStateException e) {
12307                    pw.println("Failed writing: " + e);
12308                } catch (IOException e) {
12309                    pw.println("Failed writing: " + e);
12310                }
12311            }
12312
12313            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12314                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12315                if (packageName == null) {
12316                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12317                        if (iperm == 0) {
12318                            if (dumpState.onTitlePrinted())
12319                                pw.println();
12320                            pw.println("AppOp Permissions:");
12321                        }
12322                        pw.print("  AppOp Permission ");
12323                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12324                        pw.println(":");
12325                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12326                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12327                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12328                        }
12329                    }
12330                }
12331            }
12332
12333            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12334                boolean printedSomething = false;
12335                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12336                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12337                        continue;
12338                    }
12339                    if (!printedSomething) {
12340                        if (dumpState.onTitlePrinted())
12341                            pw.println();
12342                        pw.println("Registered ContentProviders:");
12343                        printedSomething = true;
12344                    }
12345                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12346                    pw.print("    "); pw.println(p.toString());
12347                }
12348                printedSomething = false;
12349                for (Map.Entry<String, PackageParser.Provider> entry :
12350                        mProvidersByAuthority.entrySet()) {
12351                    PackageParser.Provider p = entry.getValue();
12352                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12353                        continue;
12354                    }
12355                    if (!printedSomething) {
12356                        if (dumpState.onTitlePrinted())
12357                            pw.println();
12358                        pw.println("ContentProvider Authorities:");
12359                        printedSomething = true;
12360                    }
12361                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12362                    pw.print("    "); pw.println(p.toString());
12363                    if (p.info != null && p.info.applicationInfo != null) {
12364                        final String appInfo = p.info.applicationInfo.toString();
12365                        pw.print("      applicationInfo="); pw.println(appInfo);
12366                    }
12367                }
12368            }
12369
12370            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12371                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12372            }
12373
12374            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12375                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12376            }
12377
12378            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12379                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12380            }
12381
12382            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12383                // XXX should handle packageName != null by dumping only install data that
12384                // the given package is involved with.
12385                if (dumpState.onTitlePrinted()) pw.println();
12386                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12387            }
12388
12389            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12390                if (dumpState.onTitlePrinted()) pw.println();
12391                mSettings.dumpReadMessagesLPr(pw, dumpState);
12392
12393                pw.println();
12394                pw.println("Package warning messages:");
12395                final File fname = getSettingsProblemFile();
12396                FileInputStream in = null;
12397                try {
12398                    in = new FileInputStream(fname);
12399                    final int avail = in.available();
12400                    final byte[] data = new byte[avail];
12401                    in.read(data);
12402                    pw.print(new String(data));
12403                } catch (FileNotFoundException e) {
12404                } catch (IOException e) {
12405                } finally {
12406                    if (in != null) {
12407                        try {
12408                            in.close();
12409                        } catch (IOException e) {
12410                        }
12411                    }
12412                }
12413            }
12414        }
12415    }
12416
12417    // ------- apps on sdcard specific code -------
12418    static final boolean DEBUG_SD_INSTALL = false;
12419
12420    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12421
12422    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12423
12424    private boolean mMediaMounted = false;
12425
12426    static String getEncryptKey() {
12427        try {
12428            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12429                    SD_ENCRYPTION_KEYSTORE_NAME);
12430            if (sdEncKey == null) {
12431                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12432                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12433                if (sdEncKey == null) {
12434                    Slog.e(TAG, "Failed to create encryption keys");
12435                    return null;
12436                }
12437            }
12438            return sdEncKey;
12439        } catch (NoSuchAlgorithmException nsae) {
12440            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12441            return null;
12442        } catch (IOException ioe) {
12443            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12444            return null;
12445        }
12446    }
12447
12448    /*
12449     * Update media status on PackageManager.
12450     */
12451    @Override
12452    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12453        int callingUid = Binder.getCallingUid();
12454        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12455            throw new SecurityException("Media status can only be updated by the system");
12456        }
12457        // reader; this apparently protects mMediaMounted, but should probably
12458        // be a different lock in that case.
12459        synchronized (mPackages) {
12460            Log.i(TAG, "Updating external media status from "
12461                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12462                    + (mediaStatus ? "mounted" : "unmounted"));
12463            if (DEBUG_SD_INSTALL)
12464                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12465                        + ", mMediaMounted=" + mMediaMounted);
12466            if (mediaStatus == mMediaMounted) {
12467                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12468                        : 0, -1);
12469                mHandler.sendMessage(msg);
12470                return;
12471            }
12472            mMediaMounted = mediaStatus;
12473        }
12474        // Queue up an async operation since the package installation may take a
12475        // little while.
12476        mHandler.post(new Runnable() {
12477            public void run() {
12478                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12479            }
12480        });
12481    }
12482
12483    /**
12484     * Called by MountService when the initial ASECs to scan are available.
12485     * Should block until all the ASEC containers are finished being scanned.
12486     */
12487    public void scanAvailableAsecs() {
12488        updateExternalMediaStatusInner(true, false, false);
12489        if (mShouldRestoreconData) {
12490            SELinuxMMAC.setRestoreconDone();
12491            mShouldRestoreconData = false;
12492        }
12493    }
12494
12495    /*
12496     * Collect information of applications on external media, map them against
12497     * existing containers and update information based on current mount status.
12498     * Please note that we always have to report status if reportStatus has been
12499     * set to true especially when unloading packages.
12500     */
12501    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12502            boolean externalStorage) {
12503        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12504        int[] uidArr = EmptyArray.INT;
12505
12506        final String[] list = PackageHelper.getSecureContainerList();
12507        if (ArrayUtils.isEmpty(list)) {
12508            Log.i(TAG, "No secure containers found");
12509        } else {
12510            // Process list of secure containers and categorize them
12511            // as active or stale based on their package internal state.
12512
12513            // reader
12514            synchronized (mPackages) {
12515                for (String cid : list) {
12516                    // Leave stages untouched for now; installer service owns them
12517                    if (PackageInstallerService.isStageName(cid)) continue;
12518
12519                    if (DEBUG_SD_INSTALL)
12520                        Log.i(TAG, "Processing container " + cid);
12521                    String pkgName = getAsecPackageName(cid);
12522                    if (pkgName == null) {
12523                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12524                        continue;
12525                    }
12526                    if (DEBUG_SD_INSTALL)
12527                        Log.i(TAG, "Looking for pkg : " + pkgName);
12528
12529                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12530                    if (ps == null) {
12531                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12532                        continue;
12533                    }
12534
12535                    /*
12536                     * Skip packages that are not external if we're unmounting
12537                     * external storage.
12538                     */
12539                    if (externalStorage && !isMounted && !isExternal(ps)) {
12540                        continue;
12541                    }
12542
12543                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12544                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12545                    // The package status is changed only if the code path
12546                    // matches between settings and the container id.
12547                    if (ps.codePathString != null
12548                            && ps.codePathString.startsWith(args.getCodePath())) {
12549                        if (DEBUG_SD_INSTALL) {
12550                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12551                                    + " at code path: " + ps.codePathString);
12552                        }
12553
12554                        // We do have a valid package installed on sdcard
12555                        processCids.put(args, ps.codePathString);
12556                        final int uid = ps.appId;
12557                        if (uid != -1) {
12558                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12559                        }
12560                    } else {
12561                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12562                                + ps.codePathString);
12563                    }
12564                }
12565            }
12566
12567            Arrays.sort(uidArr);
12568        }
12569
12570        // Process packages with valid entries.
12571        if (isMounted) {
12572            if (DEBUG_SD_INSTALL)
12573                Log.i(TAG, "Loading packages");
12574            loadMediaPackages(processCids, uidArr);
12575            startCleaningPackages();
12576            mInstallerService.onSecureContainersAvailable();
12577        } else {
12578            if (DEBUG_SD_INSTALL)
12579                Log.i(TAG, "Unloading packages");
12580            unloadMediaPackages(processCids, uidArr, reportStatus);
12581        }
12582    }
12583
12584    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12585            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12586        int size = pkgList.size();
12587        if (size > 0) {
12588            // Send broadcasts here
12589            Bundle extras = new Bundle();
12590            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12591                    .toArray(new String[size]));
12592            if (uidArr != null) {
12593                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12594            }
12595            if (replacing) {
12596                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12597            }
12598            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12599                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12600            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12601        }
12602    }
12603
12604   /*
12605     * Look at potentially valid container ids from processCids If package
12606     * information doesn't match the one on record or package scanning fails,
12607     * the cid is added to list of removeCids. We currently don't delete stale
12608     * containers.
12609     */
12610    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12611        ArrayList<String> pkgList = new ArrayList<String>();
12612        Set<AsecInstallArgs> keys = processCids.keySet();
12613
12614        for (AsecInstallArgs args : keys) {
12615            String codePath = processCids.get(args);
12616            if (DEBUG_SD_INSTALL)
12617                Log.i(TAG, "Loading container : " + args.cid);
12618            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12619            try {
12620                // Make sure there are no container errors first.
12621                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12622                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12623                            + " when installing from sdcard");
12624                    continue;
12625                }
12626                // Check code path here.
12627                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12628                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12629                            + " does not match one in settings " + codePath);
12630                    continue;
12631                }
12632                // Parse package
12633                int parseFlags = mDefParseFlags;
12634                if (args.isExternal()) {
12635                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12636                }
12637                if (args.isFwdLocked()) {
12638                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12639                }
12640
12641                synchronized (mInstallLock) {
12642                    PackageParser.Package pkg = null;
12643                    try {
12644                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12645                    } catch (PackageManagerException e) {
12646                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12647                    }
12648                    // Scan the package
12649                    if (pkg != null) {
12650                        /*
12651                         * TODO why is the lock being held? doPostInstall is
12652                         * called in other places without the lock. This needs
12653                         * to be straightened out.
12654                         */
12655                        // writer
12656                        synchronized (mPackages) {
12657                            retCode = PackageManager.INSTALL_SUCCEEDED;
12658                            pkgList.add(pkg.packageName);
12659                            // Post process args
12660                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12661                                    pkg.applicationInfo.uid);
12662                        }
12663                    } else {
12664                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12665                    }
12666                }
12667
12668            } finally {
12669                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12670                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12671                }
12672            }
12673        }
12674        // writer
12675        synchronized (mPackages) {
12676            // If the platform SDK has changed since the last time we booted,
12677            // we need to re-grant app permission to catch any new ones that
12678            // appear. This is really a hack, and means that apps can in some
12679            // cases get permissions that the user didn't initially explicitly
12680            // allow... it would be nice to have some better way to handle
12681            // this situation.
12682            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12683            if (regrantPermissions)
12684                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12685                        + mSdkVersion + "; regranting permissions for external storage");
12686            mSettings.mExternalSdkPlatform = mSdkVersion;
12687
12688            // Make sure group IDs have been assigned, and any permission
12689            // changes in other apps are accounted for
12690            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12691                    | (regrantPermissions
12692                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12693                            : 0));
12694
12695            mSettings.updateExternalDatabaseVersion();
12696
12697            // can downgrade to reader
12698            // Persist settings
12699            mSettings.writeLPr();
12700        }
12701        // Send a broadcast to let everyone know we are done processing
12702        if (pkgList.size() > 0) {
12703            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12704        }
12705    }
12706
12707   /*
12708     * Utility method to unload a list of specified containers
12709     */
12710    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12711        // Just unmount all valid containers.
12712        for (AsecInstallArgs arg : cidArgs) {
12713            synchronized (mInstallLock) {
12714                arg.doPostDeleteLI(false);
12715           }
12716       }
12717   }
12718
12719    /*
12720     * Unload packages mounted on external media. This involves deleting package
12721     * data from internal structures, sending broadcasts about diabled packages,
12722     * gc'ing to free up references, unmounting all secure containers
12723     * corresponding to packages on external media, and posting a
12724     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12725     * that we always have to post this message if status has been requested no
12726     * matter what.
12727     */
12728    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12729            final boolean reportStatus) {
12730        if (DEBUG_SD_INSTALL)
12731            Log.i(TAG, "unloading media packages");
12732        ArrayList<String> pkgList = new ArrayList<String>();
12733        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12734        final Set<AsecInstallArgs> keys = processCids.keySet();
12735        for (AsecInstallArgs args : keys) {
12736            String pkgName = args.getPackageName();
12737            if (DEBUG_SD_INSTALL)
12738                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12739            // Delete package internally
12740            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12741            synchronized (mInstallLock) {
12742                boolean res = deletePackageLI(pkgName, null, false, null, null,
12743                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12744                if (res) {
12745                    pkgList.add(pkgName);
12746                } else {
12747                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12748                    failedList.add(args);
12749                }
12750            }
12751        }
12752
12753        // reader
12754        synchronized (mPackages) {
12755            // We didn't update the settings after removing each package;
12756            // write them now for all packages.
12757            mSettings.writeLPr();
12758        }
12759
12760        // We have to absolutely send UPDATED_MEDIA_STATUS only
12761        // after confirming that all the receivers processed the ordered
12762        // broadcast when packages get disabled, force a gc to clean things up.
12763        // and unload all the containers.
12764        if (pkgList.size() > 0) {
12765            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12766                    new IIntentReceiver.Stub() {
12767                public void performReceive(Intent intent, int resultCode, String data,
12768                        Bundle extras, boolean ordered, boolean sticky,
12769                        int sendingUser) throws RemoteException {
12770                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12771                            reportStatus ? 1 : 0, 1, keys);
12772                    mHandler.sendMessage(msg);
12773                }
12774            });
12775        } else {
12776            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12777                    keys);
12778            mHandler.sendMessage(msg);
12779        }
12780    }
12781
12782    /** Binder call */
12783    @Override
12784    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12785            final int flags) {
12786        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12787        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12788        int returnCode = PackageManager.MOVE_SUCCEEDED;
12789        int currInstallFlags = 0;
12790        int newInstallFlags = 0;
12791
12792        File codeFile = null;
12793        String installerPackageName = null;
12794        String packageAbiOverride = null;
12795
12796        // reader
12797        synchronized (mPackages) {
12798            final PackageParser.Package pkg = mPackages.get(packageName);
12799            final PackageSetting ps = mSettings.mPackages.get(packageName);
12800            if (pkg == null || ps == null) {
12801                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12802            } else {
12803                // Disable moving fwd locked apps and system packages
12804                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12805                    Slog.w(TAG, "Cannot move system application");
12806                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12807                } else if (pkg.mOperationPending) {
12808                    Slog.w(TAG, "Attempt to move package which has pending operations");
12809                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12810                } else {
12811                    // Find install location first
12812                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12813                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12814                        Slog.w(TAG, "Ambigous flags specified for move location.");
12815                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12816                    } else {
12817                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12818                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12819                        currInstallFlags = isExternal(pkg)
12820                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12821
12822                        if (newInstallFlags == currInstallFlags) {
12823                            Slog.w(TAG, "No move required. Trying to move to same location");
12824                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12825                        } else {
12826                            if (isForwardLocked(pkg)) {
12827                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12828                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12829                            }
12830                        }
12831                    }
12832                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12833                        pkg.mOperationPending = true;
12834                    }
12835                }
12836
12837                codeFile = new File(pkg.codePath);
12838                installerPackageName = ps.installerPackageName;
12839                packageAbiOverride = ps.cpuAbiOverrideString;
12840            }
12841        }
12842
12843        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12844            try {
12845                observer.packageMoved(packageName, returnCode);
12846            } catch (RemoteException ignored) {
12847            }
12848            return;
12849        }
12850
12851        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12852            @Override
12853            public void onUserActionRequired(Intent intent) throws RemoteException {
12854                throw new IllegalStateException();
12855            }
12856
12857            @Override
12858            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12859                    Bundle extras) throws RemoteException {
12860                Slog.d(TAG, "Install result for move: "
12861                        + PackageManager.installStatusToString(returnCode, msg));
12862
12863                // We usually have a new package now after the install, but if
12864                // we failed we need to clear the pending flag on the original
12865                // package object.
12866                synchronized (mPackages) {
12867                    final PackageParser.Package pkg = mPackages.get(packageName);
12868                    if (pkg != null) {
12869                        pkg.mOperationPending = false;
12870                    }
12871                }
12872
12873                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12874                switch (status) {
12875                    case PackageInstaller.STATUS_SUCCESS:
12876                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12877                        break;
12878                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12879                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12880                        break;
12881                    default:
12882                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12883                        break;
12884                }
12885            }
12886        };
12887
12888        // Treat a move like reinstalling an existing app, which ensures that we
12889        // process everythign uniformly, like unpacking native libraries.
12890        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12891
12892        final Message msg = mHandler.obtainMessage(INIT_COPY);
12893        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12894        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12895                installerPackageName, null, user, packageAbiOverride);
12896        mHandler.sendMessage(msg);
12897    }
12898
12899    @Override
12900    public boolean setInstallLocation(int loc) {
12901        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12902                null);
12903        if (getInstallLocation() == loc) {
12904            return true;
12905        }
12906        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12907                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12908            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12909                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12910            return true;
12911        }
12912        return false;
12913   }
12914
12915    @Override
12916    public int getInstallLocation() {
12917        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12918                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12919                PackageHelper.APP_INSTALL_AUTO);
12920    }
12921
12922    /** Called by UserManagerService */
12923    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12924        mDirtyUsers.remove(userHandle);
12925        mSettings.removeUserLPw(userHandle);
12926        mPendingBroadcasts.remove(userHandle);
12927        if (mInstaller != null) {
12928            // Technically, we shouldn't be doing this with the package lock
12929            // held.  However, this is very rare, and there is already so much
12930            // other disk I/O going on, that we'll let it slide for now.
12931            mInstaller.removeUserDataDirs(userHandle);
12932        }
12933        mUserNeedsBadging.delete(userHandle);
12934        removeUnusedPackagesLILPw(userManager, userHandle);
12935    }
12936
12937    /**
12938     * We're removing userHandle and would like to remove any downloaded packages
12939     * that are no longer in use by any other user.
12940     * @param userHandle the user being removed
12941     */
12942    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
12943        final boolean DEBUG_CLEAN_APKS = false;
12944        int [] users = userManager.getUserIdsLPr();
12945        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
12946        while (psit.hasNext()) {
12947            PackageSetting ps = psit.next();
12948            if (ps.pkg == null) {
12949                continue;
12950            }
12951            final String packageName = ps.pkg.packageName;
12952            // Skip over if system app
12953            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12954                continue;
12955            }
12956            if (DEBUG_CLEAN_APKS) {
12957                Slog.i(TAG, "Checking package " + packageName);
12958            }
12959            boolean keep = false;
12960            for (int i = 0; i < users.length; i++) {
12961                if (users[i] != userHandle && ps.getInstalled(users[i])) {
12962                    keep = true;
12963                    if (DEBUG_CLEAN_APKS) {
12964                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
12965                                + users[i]);
12966                    }
12967                    break;
12968                }
12969            }
12970            if (!keep) {
12971                if (DEBUG_CLEAN_APKS) {
12972                    Slog.i(TAG, "  Removing package " + packageName);
12973                }
12974                mHandler.post(new Runnable() {
12975                    public void run() {
12976                        deletePackageX(packageName, userHandle, 0);
12977                    } //end run
12978                });
12979            }
12980        }
12981    }
12982
12983    /** Called by UserManagerService */
12984    void createNewUserLILPw(int userHandle, File path) {
12985        if (mInstaller != null) {
12986            mInstaller.createUserConfig(userHandle);
12987            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12988        }
12989    }
12990
12991    @Override
12992    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12993        mContext.enforceCallingOrSelfPermission(
12994                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12995                "Only package verification agents can read the verifier device identity");
12996
12997        synchronized (mPackages) {
12998            return mSettings.getVerifierDeviceIdentityLPw();
12999        }
13000    }
13001
13002    @Override
13003    public void setPermissionEnforced(String permission, boolean enforced) {
13004        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13005        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13006            synchronized (mPackages) {
13007                if (mSettings.mReadExternalStorageEnforced == null
13008                        || mSettings.mReadExternalStorageEnforced != enforced) {
13009                    mSettings.mReadExternalStorageEnforced = enforced;
13010                    mSettings.writeLPr();
13011                }
13012            }
13013            // kill any non-foreground processes so we restart them and
13014            // grant/revoke the GID.
13015            final IActivityManager am = ActivityManagerNative.getDefault();
13016            if (am != null) {
13017                final long token = Binder.clearCallingIdentity();
13018                try {
13019                    am.killProcessesBelowForeground("setPermissionEnforcement");
13020                } catch (RemoteException e) {
13021                } finally {
13022                    Binder.restoreCallingIdentity(token);
13023                }
13024            }
13025        } else {
13026            throw new IllegalArgumentException("No selective enforcement for " + permission);
13027        }
13028    }
13029
13030    @Override
13031    @Deprecated
13032    public boolean isPermissionEnforced(String permission) {
13033        return true;
13034    }
13035
13036    @Override
13037    public boolean isStorageLow() {
13038        final long token = Binder.clearCallingIdentity();
13039        try {
13040            final DeviceStorageMonitorInternal
13041                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13042            if (dsm != null) {
13043                return dsm.isMemoryLow();
13044            } else {
13045                return false;
13046            }
13047        } finally {
13048            Binder.restoreCallingIdentity(token);
13049        }
13050    }
13051
13052    @Override
13053    public IPackageInstaller getPackageInstaller() {
13054        return mInstallerService;
13055    }
13056
13057    private boolean userNeedsBadging(int userId) {
13058        int index = mUserNeedsBadging.indexOfKey(userId);
13059        if (index < 0) {
13060            final UserInfo userInfo;
13061            final long token = Binder.clearCallingIdentity();
13062            try {
13063                userInfo = sUserManager.getUserInfo(userId);
13064            } finally {
13065                Binder.restoreCallingIdentity(token);
13066            }
13067            final boolean b;
13068            if (userInfo != null && userInfo.isManagedProfile()) {
13069                b = true;
13070            } else {
13071                b = false;
13072            }
13073            mUserNeedsBadging.put(userId, b);
13074            return b;
13075        }
13076        return mUserNeedsBadging.valueAt(index);
13077    }
13078
13079    @Override
13080    public KeySet getKeySetByAlias(String packageName, String alias) {
13081        if (packageName == null || alias == null) {
13082            return null;
13083        }
13084        synchronized(mPackages) {
13085            final PackageParser.Package pkg = mPackages.get(packageName);
13086            if (pkg == null) {
13087                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13088                throw new IllegalArgumentException("Unknown package: " + packageName);
13089            }
13090            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13091            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13092        }
13093    }
13094
13095    @Override
13096    public KeySet getSigningKeySet(String packageName) {
13097        if (packageName == null) {
13098            return null;
13099        }
13100        synchronized(mPackages) {
13101            final PackageParser.Package pkg = mPackages.get(packageName);
13102            if (pkg == null) {
13103                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13104                throw new IllegalArgumentException("Unknown package: " + packageName);
13105            }
13106            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13107                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13108                throw new SecurityException("May not access signing KeySet of other apps.");
13109            }
13110            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13111            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13112        }
13113    }
13114
13115    @Override
13116    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13117        if (packageName == null || ks == null) {
13118            return false;
13119        }
13120        synchronized(mPackages) {
13121            final PackageParser.Package pkg = mPackages.get(packageName);
13122            if (pkg == null) {
13123                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13124                throw new IllegalArgumentException("Unknown package: " + packageName);
13125            }
13126            IBinder ksh = ks.getToken();
13127            if (ksh instanceof KeySetHandle) {
13128                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13129                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13130            }
13131            return false;
13132        }
13133    }
13134
13135    @Override
13136    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13137        if (packageName == null || ks == null) {
13138            return false;
13139        }
13140        synchronized(mPackages) {
13141            final PackageParser.Package pkg = mPackages.get(packageName);
13142            if (pkg == null) {
13143                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13144                throw new IllegalArgumentException("Unknown package: " + packageName);
13145            }
13146            IBinder ksh = ks.getToken();
13147            if (ksh instanceof KeySetHandle) {
13148                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13149                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13150            }
13151            return false;
13152        }
13153    }
13154}
13155