PackageManagerService.java revision 25e1ecaabbde4741663c8e5a777d9df9b939572c
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        if (DEBUG_ABI_SELECTION) {
5593            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5594                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5595                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5596        }
5597
5598        // Push the derived path down into PackageSettings so we know what to
5599        // clean up at uninstall time.
5600        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5601
5602        if (DEBUG_ABI_SELECTION) {
5603            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5604                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5605                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5606        }
5607
5608        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5609            // We don't do this here during boot because we can do it all
5610            // at once after scanning all existing packages.
5611            //
5612            // We also do this *before* we perform dexopt on this package, so that
5613            // we can avoid redundant dexopts, and also to make sure we've got the
5614            // code and package path correct.
5615            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5616                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5617        }
5618
5619        if ((scanFlags & SCAN_NO_DEX) == 0) {
5620            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5621                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5622                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5623            }
5624        }
5625
5626        if (mFactoryTest && pkg.requestedPermissions.contains(
5627                android.Manifest.permission.FACTORY_TEST)) {
5628            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5629        }
5630
5631        ArrayList<PackageParser.Package> clientLibPkgs = null;
5632
5633        // writer
5634        synchronized (mPackages) {
5635            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5636                // Only system apps can add new shared libraries.
5637                if (pkg.libraryNames != null) {
5638                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5639                        String name = pkg.libraryNames.get(i);
5640                        boolean allowed = false;
5641                        if (isUpdatedSystemApp(pkg)) {
5642                            // New library entries can only be added through the
5643                            // system image.  This is important to get rid of a lot
5644                            // of nasty edge cases: for example if we allowed a non-
5645                            // system update of the app to add a library, then uninstalling
5646                            // the update would make the library go away, and assumptions
5647                            // we made such as through app install filtering would now
5648                            // have allowed apps on the device which aren't compatible
5649                            // with it.  Better to just have the restriction here, be
5650                            // conservative, and create many fewer cases that can negatively
5651                            // impact the user experience.
5652                            final PackageSetting sysPs = mSettings
5653                                    .getDisabledSystemPkgLPr(pkg.packageName);
5654                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5655                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5656                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5657                                        allowed = true;
5658                                        allowed = true;
5659                                        break;
5660                                    }
5661                                }
5662                            }
5663                        } else {
5664                            allowed = true;
5665                        }
5666                        if (allowed) {
5667                            if (!mSharedLibraries.containsKey(name)) {
5668                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5669                            } else if (!name.equals(pkg.packageName)) {
5670                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5671                                        + name + " already exists; skipping");
5672                            }
5673                        } else {
5674                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5675                                    + name + " that is not declared on system image; skipping");
5676                        }
5677                    }
5678                    if ((scanFlags&SCAN_BOOTING) == 0) {
5679                        // If we are not booting, we need to update any applications
5680                        // that are clients of our shared library.  If we are booting,
5681                        // this will all be done once the scan is complete.
5682                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5683                    }
5684                }
5685            }
5686        }
5687
5688        // We also need to dexopt any apps that are dependent on this library.  Note that
5689        // if these fail, we should abort the install since installing the library will
5690        // result in some apps being broken.
5691        if (clientLibPkgs != null) {
5692            if ((scanFlags & SCAN_NO_DEX) == 0) {
5693                for (int i = 0; i < clientLibPkgs.size(); i++) {
5694                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5695                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5696                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5697                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5698                                "scanPackageLI failed to dexopt clientLibPkgs");
5699                    }
5700                }
5701            }
5702        }
5703
5704        // Request the ActivityManager to kill the process(only for existing packages)
5705        // so that we do not end up in a confused state while the user is still using the older
5706        // version of the application while the new one gets installed.
5707        if ((scanFlags & SCAN_REPLACING) != 0) {
5708            killApplication(pkg.applicationInfo.packageName,
5709                        pkg.applicationInfo.uid, "update pkg");
5710        }
5711
5712        // Also need to kill any apps that are dependent on the library.
5713        if (clientLibPkgs != null) {
5714            for (int i=0; i<clientLibPkgs.size(); i++) {
5715                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5716                killApplication(clientPkg.applicationInfo.packageName,
5717                        clientPkg.applicationInfo.uid, "update lib");
5718            }
5719        }
5720
5721        // writer
5722        synchronized (mPackages) {
5723            // We don't expect installation to fail beyond this point
5724
5725            // Add the new setting to mSettings
5726            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5727            // Add the new setting to mPackages
5728            mPackages.put(pkg.applicationInfo.packageName, pkg);
5729            // Make sure we don't accidentally delete its data.
5730            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5731            while (iter.hasNext()) {
5732                PackageCleanItem item = iter.next();
5733                if (pkgName.equals(item.packageName)) {
5734                    iter.remove();
5735                }
5736            }
5737
5738            // Take care of first install / last update times.
5739            if (currentTime != 0) {
5740                if (pkgSetting.firstInstallTime == 0) {
5741                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5742                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5743                    pkgSetting.lastUpdateTime = currentTime;
5744                }
5745            } else if (pkgSetting.firstInstallTime == 0) {
5746                // We need *something*.  Take time time stamp of the file.
5747                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5748            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5749                if (scanFileTime != pkgSetting.timeStamp) {
5750                    // A package on the system image has changed; consider this
5751                    // to be an update.
5752                    pkgSetting.lastUpdateTime = scanFileTime;
5753                }
5754            }
5755
5756            // Add the package's KeySets to the global KeySetManagerService
5757            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5758            try {
5759                // Old KeySetData no longer valid.
5760                ksms.removeAppKeySetDataLPw(pkg.packageName);
5761                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5762                if (pkg.mKeySetMapping != null) {
5763                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5764                            pkg.mKeySetMapping.entrySet()) {
5765                        if (entry.getValue() != null) {
5766                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5767                                                          entry.getValue(), entry.getKey());
5768                        }
5769                    }
5770                    if (pkg.mUpgradeKeySets != null) {
5771                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5772                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5773                        }
5774                    }
5775                }
5776            } catch (NullPointerException e) {
5777                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5778            } catch (IllegalArgumentException e) {
5779                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5780            }
5781
5782            int N = pkg.providers.size();
5783            StringBuilder r = null;
5784            int i;
5785            for (i=0; i<N; i++) {
5786                PackageParser.Provider p = pkg.providers.get(i);
5787                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5788                        p.info.processName, pkg.applicationInfo.uid);
5789                mProviders.addProvider(p);
5790                p.syncable = p.info.isSyncable;
5791                if (p.info.authority != null) {
5792                    String names[] = p.info.authority.split(";");
5793                    p.info.authority = null;
5794                    for (int j = 0; j < names.length; j++) {
5795                        if (j == 1 && p.syncable) {
5796                            // We only want the first authority for a provider to possibly be
5797                            // syncable, so if we already added this provider using a different
5798                            // authority clear the syncable flag. We copy the provider before
5799                            // changing it because the mProviders object contains a reference
5800                            // to a provider that we don't want to change.
5801                            // Only do this for the second authority since the resulting provider
5802                            // object can be the same for all future authorities for this provider.
5803                            p = new PackageParser.Provider(p);
5804                            p.syncable = false;
5805                        }
5806                        if (!mProvidersByAuthority.containsKey(names[j])) {
5807                            mProvidersByAuthority.put(names[j], p);
5808                            if (p.info.authority == null) {
5809                                p.info.authority = names[j];
5810                            } else {
5811                                p.info.authority = p.info.authority + ";" + names[j];
5812                            }
5813                            if (DEBUG_PACKAGE_SCANNING) {
5814                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5815                                    Log.d(TAG, "Registered content provider: " + names[j]
5816                                            + ", className = " + p.info.name + ", isSyncable = "
5817                                            + p.info.isSyncable);
5818                            }
5819                        } else {
5820                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5821                            Slog.w(TAG, "Skipping provider name " + names[j] +
5822                                    " (in package " + pkg.applicationInfo.packageName +
5823                                    "): name already used by "
5824                                    + ((other != null && other.getComponentName() != null)
5825                                            ? other.getComponentName().getPackageName() : "?"));
5826                        }
5827                    }
5828                }
5829                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5830                    if (r == null) {
5831                        r = new StringBuilder(256);
5832                    } else {
5833                        r.append(' ');
5834                    }
5835                    r.append(p.info.name);
5836                }
5837            }
5838            if (r != null) {
5839                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5840            }
5841
5842            N = pkg.services.size();
5843            r = null;
5844            for (i=0; i<N; i++) {
5845                PackageParser.Service s = pkg.services.get(i);
5846                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5847                        s.info.processName, pkg.applicationInfo.uid);
5848                mServices.addService(s);
5849                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5850                    if (r == null) {
5851                        r = new StringBuilder(256);
5852                    } else {
5853                        r.append(' ');
5854                    }
5855                    r.append(s.info.name);
5856                }
5857            }
5858            if (r != null) {
5859                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5860            }
5861
5862            N = pkg.receivers.size();
5863            r = null;
5864            for (i=0; i<N; i++) {
5865                PackageParser.Activity a = pkg.receivers.get(i);
5866                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5867                        a.info.processName, pkg.applicationInfo.uid);
5868                mReceivers.addActivity(a, "receiver");
5869                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5870                    if (r == null) {
5871                        r = new StringBuilder(256);
5872                    } else {
5873                        r.append(' ');
5874                    }
5875                    r.append(a.info.name);
5876                }
5877            }
5878            if (r != null) {
5879                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5880            }
5881
5882            N = pkg.activities.size();
5883            r = null;
5884            for (i=0; i<N; i++) {
5885                PackageParser.Activity a = pkg.activities.get(i);
5886                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5887                        a.info.processName, pkg.applicationInfo.uid);
5888                mActivities.addActivity(a, "activity");
5889                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5890                    if (r == null) {
5891                        r = new StringBuilder(256);
5892                    } else {
5893                        r.append(' ');
5894                    }
5895                    r.append(a.info.name);
5896                }
5897            }
5898            if (r != null) {
5899                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5900            }
5901
5902            N = pkg.permissionGroups.size();
5903            r = null;
5904            for (i=0; i<N; i++) {
5905                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5906                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5907                if (cur == null) {
5908                    mPermissionGroups.put(pg.info.name, pg);
5909                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5910                        if (r == null) {
5911                            r = new StringBuilder(256);
5912                        } else {
5913                            r.append(' ');
5914                        }
5915                        r.append(pg.info.name);
5916                    }
5917                } else {
5918                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5919                            + pg.info.packageName + " ignored: original from "
5920                            + cur.info.packageName);
5921                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5922                        if (r == null) {
5923                            r = new StringBuilder(256);
5924                        } else {
5925                            r.append(' ');
5926                        }
5927                        r.append("DUP:");
5928                        r.append(pg.info.name);
5929                    }
5930                }
5931            }
5932            if (r != null) {
5933                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5934            }
5935
5936            N = pkg.permissions.size();
5937            r = null;
5938            for (i=0; i<N; i++) {
5939                PackageParser.Permission p = pkg.permissions.get(i);
5940                HashMap<String, BasePermission> permissionMap =
5941                        p.tree ? mSettings.mPermissionTrees
5942                        : mSettings.mPermissions;
5943                p.group = mPermissionGroups.get(p.info.group);
5944                if (p.info.group == null || p.group != null) {
5945                    BasePermission bp = permissionMap.get(p.info.name);
5946
5947                    // Allow system apps to redefine non-system permissions
5948                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
5949                        final boolean currentOwnerIsSystem = (bp.perm != null
5950                                && isSystemApp(bp.perm.owner));
5951                        if (isSystemApp(p.owner) && !currentOwnerIsSystem) {
5952                            String msg = "New decl " + p.owner + " of permission  "
5953                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
5954                            reportSettingsProblem(Log.WARN, msg);
5955                            bp = null;
5956                        }
5957                    }
5958
5959                    if (bp == null) {
5960                        bp = new BasePermission(p.info.name, p.info.packageName,
5961                                BasePermission.TYPE_NORMAL);
5962                        permissionMap.put(p.info.name, bp);
5963                    }
5964
5965                    if (bp.perm == null) {
5966                        if (bp.sourcePackage == null
5967                                || bp.sourcePackage.equals(p.info.packageName)) {
5968                            BasePermission tree = findPermissionTreeLP(p.info.name);
5969                            if (tree == null
5970                                    || tree.sourcePackage.equals(p.info.packageName)) {
5971                                bp.packageSetting = pkgSetting;
5972                                bp.perm = p;
5973                                bp.uid = pkg.applicationInfo.uid;
5974                                bp.sourcePackage = p.info.packageName;
5975                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5976                                    if (r == null) {
5977                                        r = new StringBuilder(256);
5978                                    } else {
5979                                        r.append(' ');
5980                                    }
5981                                    r.append(p.info.name);
5982                                }
5983                            } else {
5984                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5985                                        + p.info.packageName + " ignored: base tree "
5986                                        + tree.name + " is from package "
5987                                        + tree.sourcePackage);
5988                            }
5989                        } else {
5990                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5991                                    + p.info.packageName + " ignored: original from "
5992                                    + bp.sourcePackage);
5993                        }
5994                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5995                        if (r == null) {
5996                            r = new StringBuilder(256);
5997                        } else {
5998                            r.append(' ');
5999                        }
6000                        r.append("DUP:");
6001                        r.append(p.info.name);
6002                    }
6003                    if (bp.perm == p) {
6004                        bp.protectionLevel = p.info.protectionLevel;
6005                    }
6006                } else {
6007                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6008                            + p.info.packageName + " ignored: no group "
6009                            + p.group);
6010                }
6011            }
6012            if (r != null) {
6013                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6014            }
6015
6016            N = pkg.instrumentation.size();
6017            r = null;
6018            for (i=0; i<N; i++) {
6019                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6020                a.info.packageName = pkg.applicationInfo.packageName;
6021                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6022                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6023                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6024                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6025                a.info.dataDir = pkg.applicationInfo.dataDir;
6026
6027                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6028                // need other information about the application, like the ABI and what not ?
6029                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6030                mInstrumentation.put(a.getComponentName(), a);
6031                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6032                    if (r == null) {
6033                        r = new StringBuilder(256);
6034                    } else {
6035                        r.append(' ');
6036                    }
6037                    r.append(a.info.name);
6038                }
6039            }
6040            if (r != null) {
6041                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6042            }
6043
6044            if (pkg.protectedBroadcasts != null) {
6045                N = pkg.protectedBroadcasts.size();
6046                for (i=0; i<N; i++) {
6047                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6048                }
6049            }
6050
6051            pkgSetting.setTimeStamp(scanFileTime);
6052
6053            // Create idmap files for pairs of (packages, overlay packages).
6054            // Note: "android", ie framework-res.apk, is handled by native layers.
6055            if (pkg.mOverlayTarget != null) {
6056                // This is an overlay package.
6057                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6058                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6059                        mOverlays.put(pkg.mOverlayTarget,
6060                                new HashMap<String, PackageParser.Package>());
6061                    }
6062                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6063                    map.put(pkg.packageName, pkg);
6064                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6065                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6066                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6067                                "scanPackageLI failed to createIdmap");
6068                    }
6069                }
6070            } else if (mOverlays.containsKey(pkg.packageName) &&
6071                    !pkg.packageName.equals("android")) {
6072                // This is a regular package, with one or more known overlay packages.
6073                createIdmapsForPackageLI(pkg);
6074            }
6075        }
6076
6077        return pkg;
6078    }
6079
6080    /**
6081     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6082     * i.e, so that all packages can be run inside a single process if required.
6083     *
6084     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6085     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6086     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6087     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6088     * updating a package that belongs to a shared user.
6089     *
6090     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6091     * adds unnecessary complexity.
6092     */
6093    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6094            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6095        String requiredInstructionSet = null;
6096        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6097            requiredInstructionSet = VMRuntime.getInstructionSet(
6098                     scannedPackage.applicationInfo.primaryCpuAbi);
6099        }
6100
6101        PackageSetting requirer = null;
6102        for (PackageSetting ps : packagesForUser) {
6103            // If packagesForUser contains scannedPackage, we skip it. This will happen
6104            // when scannedPackage is an update of an existing package. Without this check,
6105            // we will never be able to change the ABI of any package belonging to a shared
6106            // user, even if it's compatible with other packages.
6107            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6108                if (ps.primaryCpuAbiString == null) {
6109                    continue;
6110                }
6111
6112                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6113                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6114                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6115                    // this but there's not much we can do.
6116                    String errorMessage = "Instruction set mismatch, "
6117                            + ((requirer == null) ? "[caller]" : requirer)
6118                            + " requires " + requiredInstructionSet + " whereas " + ps
6119                            + " requires " + instructionSet;
6120                    Slog.w(TAG, errorMessage);
6121                }
6122
6123                if (requiredInstructionSet == null) {
6124                    requiredInstructionSet = instructionSet;
6125                    requirer = ps;
6126                }
6127            }
6128        }
6129
6130        if (requiredInstructionSet != null) {
6131            String adjustedAbi;
6132            if (requirer != null) {
6133                // requirer != null implies that either scannedPackage was null or that scannedPackage
6134                // did not require an ABI, in which case we have to adjust scannedPackage to match
6135                // the ABI of the set (which is the same as requirer's ABI)
6136                adjustedAbi = requirer.primaryCpuAbiString;
6137                if (scannedPackage != null) {
6138                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6139                }
6140            } else {
6141                // requirer == null implies that we're updating all ABIs in the set to
6142                // match scannedPackage.
6143                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6144            }
6145
6146            for (PackageSetting ps : packagesForUser) {
6147                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6148                    if (ps.primaryCpuAbiString != null) {
6149                        continue;
6150                    }
6151
6152                    ps.primaryCpuAbiString = adjustedAbi;
6153                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6154                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6155                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6156
6157                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6158                                deferDexOpt, true) == DEX_OPT_FAILED) {
6159                            ps.primaryCpuAbiString = null;
6160                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6161                            return;
6162                        } else {
6163                            mInstaller.rmdex(ps.codePathString,
6164                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6165                        }
6166                    }
6167                }
6168            }
6169        }
6170    }
6171
6172    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6173        synchronized (mPackages) {
6174            mResolverReplaced = true;
6175            // Set up information for custom user intent resolution activity.
6176            mResolveActivity.applicationInfo = pkg.applicationInfo;
6177            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6178            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6179            mResolveActivity.processName = null;
6180            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6181            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6182                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6183            mResolveActivity.theme = 0;
6184            mResolveActivity.exported = true;
6185            mResolveActivity.enabled = true;
6186            mResolveInfo.activityInfo = mResolveActivity;
6187            mResolveInfo.priority = 0;
6188            mResolveInfo.preferredOrder = 0;
6189            mResolveInfo.match = 0;
6190            mResolveComponentName = mCustomResolverComponentName;
6191            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6192                    mResolveComponentName);
6193        }
6194    }
6195
6196    private static String calculateBundledApkRoot(final String codePathString) {
6197        final File codePath = new File(codePathString);
6198        final File codeRoot;
6199        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6200            codeRoot = Environment.getRootDirectory();
6201        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6202            codeRoot = Environment.getOemDirectory();
6203        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6204            codeRoot = Environment.getVendorDirectory();
6205        } else {
6206            // Unrecognized code path; take its top real segment as the apk root:
6207            // e.g. /something/app/blah.apk => /something
6208            try {
6209                File f = codePath.getCanonicalFile();
6210                File parent = f.getParentFile();    // non-null because codePath is a file
6211                File tmp;
6212                while ((tmp = parent.getParentFile()) != null) {
6213                    f = parent;
6214                    parent = tmp;
6215                }
6216                codeRoot = f;
6217                Slog.w(TAG, "Unrecognized code path "
6218                        + codePath + " - using " + codeRoot);
6219            } catch (IOException e) {
6220                // Can't canonicalize the code path -- shenanigans?
6221                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6222                return Environment.getRootDirectory().getPath();
6223            }
6224        }
6225        return codeRoot.getPath();
6226    }
6227
6228    /**
6229     * Derive and set the location of native libraries for the given package,
6230     * which varies depending on where and how the package was installed.
6231     */
6232    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6233        final ApplicationInfo info = pkg.applicationInfo;
6234        final String codePath = pkg.codePath;
6235        final File codeFile = new File(codePath);
6236        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6237        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6238
6239        info.nativeLibraryRootDir = null;
6240        info.nativeLibraryRootRequiresIsa = false;
6241        info.nativeLibraryDir = null;
6242        info.secondaryNativeLibraryDir = null;
6243
6244        if (isApkFile(codeFile)) {
6245            // Monolithic install
6246            if (bundledApp) {
6247                // If "/system/lib64/apkname" exists, assume that is the per-package
6248                // native library directory to use; otherwise use "/system/lib/apkname".
6249                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6250                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6251                        getPrimaryInstructionSet(info));
6252
6253                // This is a bundled system app so choose the path based on the ABI.
6254                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6255                // is just the default path.
6256                final String apkName = deriveCodePathName(codePath);
6257                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6258                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6259                        apkName).getAbsolutePath();
6260
6261                if (info.secondaryCpuAbi != null) {
6262                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6263                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6264                            secondaryLibDir, apkName).getAbsolutePath();
6265                }
6266            } else if (asecApp) {
6267                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6268                        .getAbsolutePath();
6269            } else {
6270                final String apkName = deriveCodePathName(codePath);
6271                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6272                        .getAbsolutePath();
6273            }
6274
6275            info.nativeLibraryRootRequiresIsa = false;
6276            info.nativeLibraryDir = info.nativeLibraryRootDir;
6277        } else {
6278            // Cluster install
6279            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6280            info.nativeLibraryRootRequiresIsa = true;
6281
6282            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6283                    getPrimaryInstructionSet(info)).getAbsolutePath();
6284
6285            if (info.secondaryCpuAbi != null) {
6286                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6287                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6288            }
6289        }
6290    }
6291
6292    /**
6293     * Calculate the abis and roots for a bundled app. These can uniquely
6294     * be determined from the contents of the system partition, i.e whether
6295     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6296     * of this information, and instead assume that the system was built
6297     * sensibly.
6298     */
6299    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6300                                           PackageSetting pkgSetting) {
6301        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6302
6303        // If "/system/lib64/apkname" exists, assume that is the per-package
6304        // native library directory to use; otherwise use "/system/lib/apkname".
6305        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6306        setBundledAppAbi(pkg, apkRoot, apkName);
6307        // pkgSetting might be null during rescan following uninstall of updates
6308        // to a bundled app, so accommodate that possibility.  The settings in
6309        // that case will be established later from the parsed package.
6310        //
6311        // If the settings aren't null, sync them up with what we've just derived.
6312        // note that apkRoot isn't stored in the package settings.
6313        if (pkgSetting != null) {
6314            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6315            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6316        }
6317    }
6318
6319    /**
6320     * Deduces the ABI of a bundled app and sets the relevant fields on the
6321     * parsed pkg object.
6322     *
6323     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6324     *        under which system libraries are installed.
6325     * @param apkName the name of the installed package.
6326     */
6327    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6328        final File codeFile = new File(pkg.codePath);
6329
6330        final boolean has64BitLibs;
6331        final boolean has32BitLibs;
6332        if (isApkFile(codeFile)) {
6333            // Monolithic install
6334            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6335            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6336        } else {
6337            // Cluster install
6338            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6339            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6340                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6341                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6342                has64BitLibs = (new File(rootDir, isa)).exists();
6343            } else {
6344                has64BitLibs = false;
6345            }
6346            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6347                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6348                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6349                has32BitLibs = (new File(rootDir, isa)).exists();
6350            } else {
6351                has32BitLibs = false;
6352            }
6353        }
6354
6355        if (has64BitLibs && !has32BitLibs) {
6356            // The package has 64 bit libs, but not 32 bit libs. Its primary
6357            // ABI should be 64 bit. We can safely assume here that the bundled
6358            // native libraries correspond to the most preferred ABI in the list.
6359
6360            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6361            pkg.applicationInfo.secondaryCpuAbi = null;
6362        } else if (has32BitLibs && !has64BitLibs) {
6363            // The package has 32 bit libs but not 64 bit libs. Its primary
6364            // ABI should be 32 bit.
6365
6366            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6367            pkg.applicationInfo.secondaryCpuAbi = null;
6368        } else if (has32BitLibs && has64BitLibs) {
6369            // The application has both 64 and 32 bit bundled libraries. We check
6370            // here that the app declares multiArch support, and warn if it doesn't.
6371            //
6372            // We will be lenient here and record both ABIs. The primary will be the
6373            // ABI that's higher on the list, i.e, a device that's configured to prefer
6374            // 64 bit apps will see a 64 bit primary ABI,
6375
6376            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6377                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6378            }
6379
6380            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6381                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6382                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6383            } else {
6384                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6385                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6386            }
6387        } else {
6388            pkg.applicationInfo.primaryCpuAbi = null;
6389            pkg.applicationInfo.secondaryCpuAbi = null;
6390        }
6391    }
6392
6393    private void killApplication(String pkgName, int appId, String reason) {
6394        // Request the ActivityManager to kill the process(only for existing packages)
6395        // so that we do not end up in a confused state while the user is still using the older
6396        // version of the application while the new one gets installed.
6397        IActivityManager am = ActivityManagerNative.getDefault();
6398        if (am != null) {
6399            try {
6400                am.killApplicationWithAppId(pkgName, appId, reason);
6401            } catch (RemoteException e) {
6402            }
6403        }
6404    }
6405
6406    void removePackageLI(PackageSetting ps, boolean chatty) {
6407        if (DEBUG_INSTALL) {
6408            if (chatty)
6409                Log.d(TAG, "Removing package " + ps.name);
6410        }
6411
6412        // writer
6413        synchronized (mPackages) {
6414            mPackages.remove(ps.name);
6415            final PackageParser.Package pkg = ps.pkg;
6416            if (pkg != null) {
6417                cleanPackageDataStructuresLILPw(pkg, chatty);
6418            }
6419        }
6420    }
6421
6422    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6423        if (DEBUG_INSTALL) {
6424            if (chatty)
6425                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6426        }
6427
6428        // writer
6429        synchronized (mPackages) {
6430            mPackages.remove(pkg.applicationInfo.packageName);
6431            cleanPackageDataStructuresLILPw(pkg, chatty);
6432        }
6433    }
6434
6435    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6436        int N = pkg.providers.size();
6437        StringBuilder r = null;
6438        int i;
6439        for (i=0; i<N; i++) {
6440            PackageParser.Provider p = pkg.providers.get(i);
6441            mProviders.removeProvider(p);
6442            if (p.info.authority == null) {
6443
6444                /* There was another ContentProvider with this authority when
6445                 * this app was installed so this authority is null,
6446                 * Ignore it as we don't have to unregister the provider.
6447                 */
6448                continue;
6449            }
6450            String names[] = p.info.authority.split(";");
6451            for (int j = 0; j < names.length; j++) {
6452                if (mProvidersByAuthority.get(names[j]) == p) {
6453                    mProvidersByAuthority.remove(names[j]);
6454                    if (DEBUG_REMOVE) {
6455                        if (chatty)
6456                            Log.d(TAG, "Unregistered content provider: " + names[j]
6457                                    + ", className = " + p.info.name + ", isSyncable = "
6458                                    + p.info.isSyncable);
6459                    }
6460                }
6461            }
6462            if (DEBUG_REMOVE && chatty) {
6463                if (r == null) {
6464                    r = new StringBuilder(256);
6465                } else {
6466                    r.append(' ');
6467                }
6468                r.append(p.info.name);
6469            }
6470        }
6471        if (r != null) {
6472            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6473        }
6474
6475        N = pkg.services.size();
6476        r = null;
6477        for (i=0; i<N; i++) {
6478            PackageParser.Service s = pkg.services.get(i);
6479            mServices.removeService(s);
6480            if (chatty) {
6481                if (r == null) {
6482                    r = new StringBuilder(256);
6483                } else {
6484                    r.append(' ');
6485                }
6486                r.append(s.info.name);
6487            }
6488        }
6489        if (r != null) {
6490            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6491        }
6492
6493        N = pkg.receivers.size();
6494        r = null;
6495        for (i=0; i<N; i++) {
6496            PackageParser.Activity a = pkg.receivers.get(i);
6497            mReceivers.removeActivity(a, "receiver");
6498            if (DEBUG_REMOVE && chatty) {
6499                if (r == null) {
6500                    r = new StringBuilder(256);
6501                } else {
6502                    r.append(' ');
6503                }
6504                r.append(a.info.name);
6505            }
6506        }
6507        if (r != null) {
6508            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6509        }
6510
6511        N = pkg.activities.size();
6512        r = null;
6513        for (i=0; i<N; i++) {
6514            PackageParser.Activity a = pkg.activities.get(i);
6515            mActivities.removeActivity(a, "activity");
6516            if (DEBUG_REMOVE && chatty) {
6517                if (r == null) {
6518                    r = new StringBuilder(256);
6519                } else {
6520                    r.append(' ');
6521                }
6522                r.append(a.info.name);
6523            }
6524        }
6525        if (r != null) {
6526            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6527        }
6528
6529        N = pkg.permissions.size();
6530        r = null;
6531        for (i=0; i<N; i++) {
6532            PackageParser.Permission p = pkg.permissions.get(i);
6533            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6534            if (bp == null) {
6535                bp = mSettings.mPermissionTrees.get(p.info.name);
6536            }
6537            if (bp != null && bp.perm == p) {
6538                bp.perm = null;
6539                if (DEBUG_REMOVE && chatty) {
6540                    if (r == null) {
6541                        r = new StringBuilder(256);
6542                    } else {
6543                        r.append(' ');
6544                    }
6545                    r.append(p.info.name);
6546                }
6547            }
6548            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6549                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6550                if (appOpPerms != null) {
6551                    appOpPerms.remove(pkg.packageName);
6552                }
6553            }
6554        }
6555        if (r != null) {
6556            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6557        }
6558
6559        N = pkg.requestedPermissions.size();
6560        r = null;
6561        for (i=0; i<N; i++) {
6562            String perm = pkg.requestedPermissions.get(i);
6563            BasePermission bp = mSettings.mPermissions.get(perm);
6564            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6565                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6566                if (appOpPerms != null) {
6567                    appOpPerms.remove(pkg.packageName);
6568                    if (appOpPerms.isEmpty()) {
6569                        mAppOpPermissionPackages.remove(perm);
6570                    }
6571                }
6572            }
6573        }
6574        if (r != null) {
6575            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6576        }
6577
6578        N = pkg.instrumentation.size();
6579        r = null;
6580        for (i=0; i<N; i++) {
6581            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6582            mInstrumentation.remove(a.getComponentName());
6583            if (DEBUG_REMOVE && chatty) {
6584                if (r == null) {
6585                    r = new StringBuilder(256);
6586                } else {
6587                    r.append(' ');
6588                }
6589                r.append(a.info.name);
6590            }
6591        }
6592        if (r != null) {
6593            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6594        }
6595
6596        r = null;
6597        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6598            // Only system apps can hold shared libraries.
6599            if (pkg.libraryNames != null) {
6600                for (i=0; i<pkg.libraryNames.size(); i++) {
6601                    String name = pkg.libraryNames.get(i);
6602                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6603                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6604                        mSharedLibraries.remove(name);
6605                        if (DEBUG_REMOVE && chatty) {
6606                            if (r == null) {
6607                                r = new StringBuilder(256);
6608                            } else {
6609                                r.append(' ');
6610                            }
6611                            r.append(name);
6612                        }
6613                    }
6614                }
6615            }
6616        }
6617        if (r != null) {
6618            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6619        }
6620    }
6621
6622    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6623        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6624            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6625                return true;
6626            }
6627        }
6628        return false;
6629    }
6630
6631    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6632    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6633    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6634
6635    private void updatePermissionsLPw(String changingPkg,
6636            PackageParser.Package pkgInfo, int flags) {
6637        // Make sure there are no dangling permission trees.
6638        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6639        while (it.hasNext()) {
6640            final BasePermission bp = it.next();
6641            if (bp.packageSetting == null) {
6642                // We may not yet have parsed the package, so just see if
6643                // we still know about its settings.
6644                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6645            }
6646            if (bp.packageSetting == null) {
6647                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6648                        + " from package " + bp.sourcePackage);
6649                it.remove();
6650            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6651                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6652                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6653                            + " from package " + bp.sourcePackage);
6654                    flags |= UPDATE_PERMISSIONS_ALL;
6655                    it.remove();
6656                }
6657            }
6658        }
6659
6660        // Make sure all dynamic permissions have been assigned to a package,
6661        // and make sure there are no dangling permissions.
6662        it = mSettings.mPermissions.values().iterator();
6663        while (it.hasNext()) {
6664            final BasePermission bp = it.next();
6665            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6666                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6667                        + bp.name + " pkg=" + bp.sourcePackage
6668                        + " info=" + bp.pendingInfo);
6669                if (bp.packageSetting == null && bp.pendingInfo != null) {
6670                    final BasePermission tree = findPermissionTreeLP(bp.name);
6671                    if (tree != null && tree.perm != null) {
6672                        bp.packageSetting = tree.packageSetting;
6673                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6674                                new PermissionInfo(bp.pendingInfo));
6675                        bp.perm.info.packageName = tree.perm.info.packageName;
6676                        bp.perm.info.name = bp.name;
6677                        bp.uid = tree.uid;
6678                    }
6679                }
6680            }
6681            if (bp.packageSetting == null) {
6682                // We may not yet have parsed the package, so just see if
6683                // we still know about its settings.
6684                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6685            }
6686            if (bp.packageSetting == null) {
6687                Slog.w(TAG, "Removing dangling permission: " + bp.name
6688                        + " from package " + bp.sourcePackage);
6689                it.remove();
6690            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6691                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6692                    Slog.i(TAG, "Removing old permission: " + bp.name
6693                            + " from package " + bp.sourcePackage);
6694                    flags |= UPDATE_PERMISSIONS_ALL;
6695                    it.remove();
6696                }
6697            }
6698        }
6699
6700        // Now update the permissions for all packages, in particular
6701        // replace the granted permissions of the system packages.
6702        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6703            for (PackageParser.Package pkg : mPackages.values()) {
6704                if (pkg != pkgInfo) {
6705                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6706                            changingPkg);
6707                }
6708            }
6709        }
6710
6711        if (pkgInfo != null) {
6712            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6713        }
6714    }
6715
6716    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6717            String packageOfInterest) {
6718        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6719        if (ps == null) {
6720            return;
6721        }
6722        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6723        HashSet<String> origPermissions = gp.grantedPermissions;
6724        boolean changedPermission = false;
6725
6726        if (replace) {
6727            ps.permissionsFixed = false;
6728            if (gp == ps) {
6729                origPermissions = new HashSet<String>(gp.grantedPermissions);
6730                gp.grantedPermissions.clear();
6731                gp.gids = mGlobalGids;
6732            }
6733        }
6734
6735        if (gp.gids == null) {
6736            gp.gids = mGlobalGids;
6737        }
6738
6739        final int N = pkg.requestedPermissions.size();
6740        for (int i=0; i<N; i++) {
6741            final String name = pkg.requestedPermissions.get(i);
6742            final boolean required = pkg.requestedPermissionsRequired.get(i);
6743            final BasePermission bp = mSettings.mPermissions.get(name);
6744            if (DEBUG_INSTALL) {
6745                if (gp != ps) {
6746                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6747                }
6748            }
6749
6750            if (bp == null || bp.packageSetting == null) {
6751                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6752                    Slog.w(TAG, "Unknown permission " + name
6753                            + " in package " + pkg.packageName);
6754                }
6755                continue;
6756            }
6757
6758            final String perm = bp.name;
6759            boolean allowed;
6760            boolean allowedSig = false;
6761            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6762                // Keep track of app op permissions.
6763                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6764                if (pkgs == null) {
6765                    pkgs = new ArraySet<>();
6766                    mAppOpPermissionPackages.put(bp.name, pkgs);
6767                }
6768                pkgs.add(pkg.packageName);
6769            }
6770            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6771            if (level == PermissionInfo.PROTECTION_NORMAL
6772                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6773                // We grant a normal or dangerous permission if any of the following
6774                // are true:
6775                // 1) The permission is required
6776                // 2) The permission is optional, but was granted in the past
6777                // 3) The permission is optional, but was requested by an
6778                //    app in /system (not /data)
6779                //
6780                // Otherwise, reject the permission.
6781                allowed = (required || origPermissions.contains(perm)
6782                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6783            } else if (bp.packageSetting == null) {
6784                // This permission is invalid; skip it.
6785                allowed = false;
6786            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6787                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6788                if (allowed) {
6789                    allowedSig = true;
6790                }
6791            } else {
6792                allowed = false;
6793            }
6794            if (DEBUG_INSTALL) {
6795                if (gp != ps) {
6796                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6797                }
6798            }
6799            if (allowed) {
6800                if (!isSystemApp(ps) && ps.permissionsFixed) {
6801                    // If this is an existing, non-system package, then
6802                    // we can't add any new permissions to it.
6803                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6804                        // Except...  if this is a permission that was added
6805                        // to the platform (note: need to only do this when
6806                        // updating the platform).
6807                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6808                    }
6809                }
6810                if (allowed) {
6811                    if (!gp.grantedPermissions.contains(perm)) {
6812                        changedPermission = true;
6813                        gp.grantedPermissions.add(perm);
6814                        gp.gids = appendInts(gp.gids, bp.gids);
6815                    } else if (!ps.haveGids) {
6816                        gp.gids = appendInts(gp.gids, bp.gids);
6817                    }
6818                } else {
6819                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6820                        Slog.w(TAG, "Not granting permission " + perm
6821                                + " to package " + pkg.packageName
6822                                + " because it was previously installed without");
6823                    }
6824                }
6825            } else {
6826                if (gp.grantedPermissions.remove(perm)) {
6827                    changedPermission = true;
6828                    gp.gids = removeInts(gp.gids, bp.gids);
6829                    Slog.i(TAG, "Un-granting permission " + perm
6830                            + " from package " + pkg.packageName
6831                            + " (protectionLevel=" + bp.protectionLevel
6832                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6833                            + ")");
6834                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6835                    // Don't print warning for app op permissions, since it is fine for them
6836                    // not to be granted, there is a UI for the user to decide.
6837                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6838                        Slog.w(TAG, "Not granting permission " + perm
6839                                + " to package " + pkg.packageName
6840                                + " (protectionLevel=" + bp.protectionLevel
6841                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6842                                + ")");
6843                    }
6844                }
6845            }
6846        }
6847
6848        if ((changedPermission || replace) && !ps.permissionsFixed &&
6849                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6850            // This is the first that we have heard about this package, so the
6851            // permissions we have now selected are fixed until explicitly
6852            // changed.
6853            ps.permissionsFixed = true;
6854        }
6855        ps.haveGids = true;
6856    }
6857
6858    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6859        boolean allowed = false;
6860        final int NP = PackageParser.NEW_PERMISSIONS.length;
6861        for (int ip=0; ip<NP; ip++) {
6862            final PackageParser.NewPermissionInfo npi
6863                    = PackageParser.NEW_PERMISSIONS[ip];
6864            if (npi.name.equals(perm)
6865                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6866                allowed = true;
6867                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6868                        + pkg.packageName);
6869                break;
6870            }
6871        }
6872        return allowed;
6873    }
6874
6875    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6876                                          BasePermission bp, HashSet<String> origPermissions) {
6877        boolean allowed;
6878        allowed = (compareSignatures(
6879                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6880                        == PackageManager.SIGNATURE_MATCH)
6881                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6882                        == PackageManager.SIGNATURE_MATCH);
6883        if (!allowed && (bp.protectionLevel
6884                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6885            if (isSystemApp(pkg)) {
6886                // For updated system applications, a system permission
6887                // is granted only if it had been defined by the original application.
6888                if (isUpdatedSystemApp(pkg)) {
6889                    final PackageSetting sysPs = mSettings
6890                            .getDisabledSystemPkgLPr(pkg.packageName);
6891                    final GrantedPermissions origGp = sysPs.sharedUser != null
6892                            ? sysPs.sharedUser : sysPs;
6893
6894                    if (origGp.grantedPermissions.contains(perm)) {
6895                        // If the original was granted this permission, we take
6896                        // that grant decision as read and propagate it to the
6897                        // update.
6898                        allowed = true;
6899                    } else {
6900                        // The system apk may have been updated with an older
6901                        // version of the one on the data partition, but which
6902                        // granted a new system permission that it didn't have
6903                        // before.  In this case we do want to allow the app to
6904                        // now get the new permission if the ancestral apk is
6905                        // privileged to get it.
6906                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6907                            for (int j=0;
6908                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6909                                if (perm.equals(
6910                                        sysPs.pkg.requestedPermissions.get(j))) {
6911                                    allowed = true;
6912                                    break;
6913                                }
6914                            }
6915                        }
6916                    }
6917                } else {
6918                    allowed = isPrivilegedApp(pkg);
6919                }
6920            }
6921        }
6922        if (!allowed && (bp.protectionLevel
6923                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6924            // For development permissions, a development permission
6925            // is granted only if it was already granted.
6926            allowed = origPermissions.contains(perm);
6927        }
6928        return allowed;
6929    }
6930
6931    final class ActivityIntentResolver
6932            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6933        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6934                boolean defaultOnly, int userId) {
6935            if (!sUserManager.exists(userId)) return null;
6936            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6937            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6938        }
6939
6940        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6941                int userId) {
6942            if (!sUserManager.exists(userId)) return null;
6943            mFlags = flags;
6944            return super.queryIntent(intent, resolvedType,
6945                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6946        }
6947
6948        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6949                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6950            if (!sUserManager.exists(userId)) return null;
6951            if (packageActivities == null) {
6952                return null;
6953            }
6954            mFlags = flags;
6955            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6956            final int N = packageActivities.size();
6957            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6958                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6959
6960            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6961            for (int i = 0; i < N; ++i) {
6962                intentFilters = packageActivities.get(i).intents;
6963                if (intentFilters != null && intentFilters.size() > 0) {
6964                    PackageParser.ActivityIntentInfo[] array =
6965                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6966                    intentFilters.toArray(array);
6967                    listCut.add(array);
6968                }
6969            }
6970            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6971        }
6972
6973        public final void addActivity(PackageParser.Activity a, String type) {
6974            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6975            mActivities.put(a.getComponentName(), a);
6976            if (DEBUG_SHOW_INFO)
6977                Log.v(
6978                TAG, "  " + type + " " +
6979                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6980            if (DEBUG_SHOW_INFO)
6981                Log.v(TAG, "    Class=" + a.info.name);
6982            final int NI = a.intents.size();
6983            for (int j=0; j<NI; j++) {
6984                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6985                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6986                    intent.setPriority(0);
6987                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6988                            + a.className + " with priority > 0, forcing to 0");
6989                }
6990                if (DEBUG_SHOW_INFO) {
6991                    Log.v(TAG, "    IntentFilter:");
6992                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6993                }
6994                if (!intent.debugCheck()) {
6995                    Log.w(TAG, "==> For Activity " + a.info.name);
6996                }
6997                addFilter(intent);
6998            }
6999        }
7000
7001        public final void removeActivity(PackageParser.Activity a, String type) {
7002            mActivities.remove(a.getComponentName());
7003            if (DEBUG_SHOW_INFO) {
7004                Log.v(TAG, "  " + type + " "
7005                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7006                                : a.info.name) + ":");
7007                Log.v(TAG, "    Class=" + a.info.name);
7008            }
7009            final int NI = a.intents.size();
7010            for (int j=0; j<NI; j++) {
7011                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7012                if (DEBUG_SHOW_INFO) {
7013                    Log.v(TAG, "    IntentFilter:");
7014                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7015                }
7016                removeFilter(intent);
7017            }
7018        }
7019
7020        @Override
7021        protected boolean allowFilterResult(
7022                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7023            ActivityInfo filterAi = filter.activity.info;
7024            for (int i=dest.size()-1; i>=0; i--) {
7025                ActivityInfo destAi = dest.get(i).activityInfo;
7026                if (destAi.name == filterAi.name
7027                        && destAi.packageName == filterAi.packageName) {
7028                    return false;
7029                }
7030            }
7031            return true;
7032        }
7033
7034        @Override
7035        protected ActivityIntentInfo[] newArray(int size) {
7036            return new ActivityIntentInfo[size];
7037        }
7038
7039        @Override
7040        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7041            if (!sUserManager.exists(userId)) return true;
7042            PackageParser.Package p = filter.activity.owner;
7043            if (p != null) {
7044                PackageSetting ps = (PackageSetting)p.mExtras;
7045                if (ps != null) {
7046                    // System apps are never considered stopped for purposes of
7047                    // filtering, because there may be no way for the user to
7048                    // actually re-launch them.
7049                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7050                            && ps.getStopped(userId);
7051                }
7052            }
7053            return false;
7054        }
7055
7056        @Override
7057        protected boolean isPackageForFilter(String packageName,
7058                PackageParser.ActivityIntentInfo info) {
7059            return packageName.equals(info.activity.owner.packageName);
7060        }
7061
7062        @Override
7063        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7064                int match, int userId) {
7065            if (!sUserManager.exists(userId)) return null;
7066            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7067                return null;
7068            }
7069            final PackageParser.Activity activity = info.activity;
7070            if (mSafeMode && (activity.info.applicationInfo.flags
7071                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7072                return null;
7073            }
7074            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7075            if (ps == null) {
7076                return null;
7077            }
7078            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7079                    ps.readUserState(userId), userId);
7080            if (ai == null) {
7081                return null;
7082            }
7083            final ResolveInfo res = new ResolveInfo();
7084            res.activityInfo = ai;
7085            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7086                res.filter = info;
7087            }
7088            res.priority = info.getPriority();
7089            res.preferredOrder = activity.owner.mPreferredOrder;
7090            //System.out.println("Result: " + res.activityInfo.className +
7091            //                   " = " + res.priority);
7092            res.match = match;
7093            res.isDefault = info.hasDefault;
7094            res.labelRes = info.labelRes;
7095            res.nonLocalizedLabel = info.nonLocalizedLabel;
7096            if (userNeedsBadging(userId)) {
7097                res.noResourceId = true;
7098            } else {
7099                res.icon = info.icon;
7100            }
7101            res.system = isSystemApp(res.activityInfo.applicationInfo);
7102            return res;
7103        }
7104
7105        @Override
7106        protected void sortResults(List<ResolveInfo> results) {
7107            Collections.sort(results, mResolvePrioritySorter);
7108        }
7109
7110        @Override
7111        protected void dumpFilter(PrintWriter out, String prefix,
7112                PackageParser.ActivityIntentInfo filter) {
7113            out.print(prefix); out.print(
7114                    Integer.toHexString(System.identityHashCode(filter.activity)));
7115                    out.print(' ');
7116                    filter.activity.printComponentShortName(out);
7117                    out.print(" filter ");
7118                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7119        }
7120
7121//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7122//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7123//            final List<ResolveInfo> retList = Lists.newArrayList();
7124//            while (i.hasNext()) {
7125//                final ResolveInfo resolveInfo = i.next();
7126//                if (isEnabledLP(resolveInfo.activityInfo)) {
7127//                    retList.add(resolveInfo);
7128//                }
7129//            }
7130//            return retList;
7131//        }
7132
7133        // Keys are String (activity class name), values are Activity.
7134        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7135                = new HashMap<ComponentName, PackageParser.Activity>();
7136        private int mFlags;
7137    }
7138
7139    private final class ServiceIntentResolver
7140            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7141        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7142                boolean defaultOnly, int userId) {
7143            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7144            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7145        }
7146
7147        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7148                int userId) {
7149            if (!sUserManager.exists(userId)) return null;
7150            mFlags = flags;
7151            return super.queryIntent(intent, resolvedType,
7152                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7153        }
7154
7155        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7156                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7157            if (!sUserManager.exists(userId)) return null;
7158            if (packageServices == null) {
7159                return null;
7160            }
7161            mFlags = flags;
7162            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7163            final int N = packageServices.size();
7164            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7165                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7166
7167            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7168            for (int i = 0; i < N; ++i) {
7169                intentFilters = packageServices.get(i).intents;
7170                if (intentFilters != null && intentFilters.size() > 0) {
7171                    PackageParser.ServiceIntentInfo[] array =
7172                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7173                    intentFilters.toArray(array);
7174                    listCut.add(array);
7175                }
7176            }
7177            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7178        }
7179
7180        public final void addService(PackageParser.Service s) {
7181            mServices.put(s.getComponentName(), s);
7182            if (DEBUG_SHOW_INFO) {
7183                Log.v(TAG, "  "
7184                        + (s.info.nonLocalizedLabel != null
7185                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7186                Log.v(TAG, "    Class=" + s.info.name);
7187            }
7188            final int NI = s.intents.size();
7189            int j;
7190            for (j=0; j<NI; j++) {
7191                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7192                if (DEBUG_SHOW_INFO) {
7193                    Log.v(TAG, "    IntentFilter:");
7194                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7195                }
7196                if (!intent.debugCheck()) {
7197                    Log.w(TAG, "==> For Service " + s.info.name);
7198                }
7199                addFilter(intent);
7200            }
7201        }
7202
7203        public final void removeService(PackageParser.Service s) {
7204            mServices.remove(s.getComponentName());
7205            if (DEBUG_SHOW_INFO) {
7206                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7207                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7208                Log.v(TAG, "    Class=" + s.info.name);
7209            }
7210            final int NI = s.intents.size();
7211            int j;
7212            for (j=0; j<NI; j++) {
7213                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7214                if (DEBUG_SHOW_INFO) {
7215                    Log.v(TAG, "    IntentFilter:");
7216                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7217                }
7218                removeFilter(intent);
7219            }
7220        }
7221
7222        @Override
7223        protected boolean allowFilterResult(
7224                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7225            ServiceInfo filterSi = filter.service.info;
7226            for (int i=dest.size()-1; i>=0; i--) {
7227                ServiceInfo destAi = dest.get(i).serviceInfo;
7228                if (destAi.name == filterSi.name
7229                        && destAi.packageName == filterSi.packageName) {
7230                    return false;
7231                }
7232            }
7233            return true;
7234        }
7235
7236        @Override
7237        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7238            return new PackageParser.ServiceIntentInfo[size];
7239        }
7240
7241        @Override
7242        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7243            if (!sUserManager.exists(userId)) return true;
7244            PackageParser.Package p = filter.service.owner;
7245            if (p != null) {
7246                PackageSetting ps = (PackageSetting)p.mExtras;
7247                if (ps != null) {
7248                    // System apps are never considered stopped for purposes of
7249                    // filtering, because there may be no way for the user to
7250                    // actually re-launch them.
7251                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7252                            && ps.getStopped(userId);
7253                }
7254            }
7255            return false;
7256        }
7257
7258        @Override
7259        protected boolean isPackageForFilter(String packageName,
7260                PackageParser.ServiceIntentInfo info) {
7261            return packageName.equals(info.service.owner.packageName);
7262        }
7263
7264        @Override
7265        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7266                int match, int userId) {
7267            if (!sUserManager.exists(userId)) return null;
7268            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7269            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7270                return null;
7271            }
7272            final PackageParser.Service service = info.service;
7273            if (mSafeMode && (service.info.applicationInfo.flags
7274                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7275                return null;
7276            }
7277            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7278            if (ps == null) {
7279                return null;
7280            }
7281            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7282                    ps.readUserState(userId), userId);
7283            if (si == null) {
7284                return null;
7285            }
7286            final ResolveInfo res = new ResolveInfo();
7287            res.serviceInfo = si;
7288            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7289                res.filter = filter;
7290            }
7291            res.priority = info.getPriority();
7292            res.preferredOrder = service.owner.mPreferredOrder;
7293            //System.out.println("Result: " + res.activityInfo.className +
7294            //                   " = " + res.priority);
7295            res.match = match;
7296            res.isDefault = info.hasDefault;
7297            res.labelRes = info.labelRes;
7298            res.nonLocalizedLabel = info.nonLocalizedLabel;
7299            res.icon = info.icon;
7300            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7301            return res;
7302        }
7303
7304        @Override
7305        protected void sortResults(List<ResolveInfo> results) {
7306            Collections.sort(results, mResolvePrioritySorter);
7307        }
7308
7309        @Override
7310        protected void dumpFilter(PrintWriter out, String prefix,
7311                PackageParser.ServiceIntentInfo filter) {
7312            out.print(prefix); out.print(
7313                    Integer.toHexString(System.identityHashCode(filter.service)));
7314                    out.print(' ');
7315                    filter.service.printComponentShortName(out);
7316                    out.print(" filter ");
7317                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7318        }
7319
7320//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7321//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7322//            final List<ResolveInfo> retList = Lists.newArrayList();
7323//            while (i.hasNext()) {
7324//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7325//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7326//                    retList.add(resolveInfo);
7327//                }
7328//            }
7329//            return retList;
7330//        }
7331
7332        // Keys are String (activity class name), values are Activity.
7333        private final HashMap<ComponentName, PackageParser.Service> mServices
7334                = new HashMap<ComponentName, PackageParser.Service>();
7335        private int mFlags;
7336    };
7337
7338    private final class ProviderIntentResolver
7339            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7340        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7341                boolean defaultOnly, int userId) {
7342            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7343            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7344        }
7345
7346        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7347                int userId) {
7348            if (!sUserManager.exists(userId))
7349                return null;
7350            mFlags = flags;
7351            return super.queryIntent(intent, resolvedType,
7352                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7353        }
7354
7355        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7356                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7357            if (!sUserManager.exists(userId))
7358                return null;
7359            if (packageProviders == null) {
7360                return null;
7361            }
7362            mFlags = flags;
7363            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7364            final int N = packageProviders.size();
7365            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7366                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7367
7368            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7369            for (int i = 0; i < N; ++i) {
7370                intentFilters = packageProviders.get(i).intents;
7371                if (intentFilters != null && intentFilters.size() > 0) {
7372                    PackageParser.ProviderIntentInfo[] array =
7373                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7374                    intentFilters.toArray(array);
7375                    listCut.add(array);
7376                }
7377            }
7378            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7379        }
7380
7381        public final void addProvider(PackageParser.Provider p) {
7382            if (mProviders.containsKey(p.getComponentName())) {
7383                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7384                return;
7385            }
7386
7387            mProviders.put(p.getComponentName(), p);
7388            if (DEBUG_SHOW_INFO) {
7389                Log.v(TAG, "  "
7390                        + (p.info.nonLocalizedLabel != null
7391                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7392                Log.v(TAG, "    Class=" + p.info.name);
7393            }
7394            final int NI = p.intents.size();
7395            int j;
7396            for (j = 0; j < NI; j++) {
7397                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7398                if (DEBUG_SHOW_INFO) {
7399                    Log.v(TAG, "    IntentFilter:");
7400                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7401                }
7402                if (!intent.debugCheck()) {
7403                    Log.w(TAG, "==> For Provider " + p.info.name);
7404                }
7405                addFilter(intent);
7406            }
7407        }
7408
7409        public final void removeProvider(PackageParser.Provider p) {
7410            mProviders.remove(p.getComponentName());
7411            if (DEBUG_SHOW_INFO) {
7412                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7413                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7414                Log.v(TAG, "    Class=" + p.info.name);
7415            }
7416            final int NI = p.intents.size();
7417            int j;
7418            for (j = 0; j < NI; j++) {
7419                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7420                if (DEBUG_SHOW_INFO) {
7421                    Log.v(TAG, "    IntentFilter:");
7422                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7423                }
7424                removeFilter(intent);
7425            }
7426        }
7427
7428        @Override
7429        protected boolean allowFilterResult(
7430                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7431            ProviderInfo filterPi = filter.provider.info;
7432            for (int i = dest.size() - 1; i >= 0; i--) {
7433                ProviderInfo destPi = dest.get(i).providerInfo;
7434                if (destPi.name == filterPi.name
7435                        && destPi.packageName == filterPi.packageName) {
7436                    return false;
7437                }
7438            }
7439            return true;
7440        }
7441
7442        @Override
7443        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7444            return new PackageParser.ProviderIntentInfo[size];
7445        }
7446
7447        @Override
7448        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7449            if (!sUserManager.exists(userId))
7450                return true;
7451            PackageParser.Package p = filter.provider.owner;
7452            if (p != null) {
7453                PackageSetting ps = (PackageSetting) p.mExtras;
7454                if (ps != null) {
7455                    // System apps are never considered stopped for purposes of
7456                    // filtering, because there may be no way for the user to
7457                    // actually re-launch them.
7458                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7459                            && ps.getStopped(userId);
7460                }
7461            }
7462            return false;
7463        }
7464
7465        @Override
7466        protected boolean isPackageForFilter(String packageName,
7467                PackageParser.ProviderIntentInfo info) {
7468            return packageName.equals(info.provider.owner.packageName);
7469        }
7470
7471        @Override
7472        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7473                int match, int userId) {
7474            if (!sUserManager.exists(userId))
7475                return null;
7476            final PackageParser.ProviderIntentInfo info = filter;
7477            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7478                return null;
7479            }
7480            final PackageParser.Provider provider = info.provider;
7481            if (mSafeMode && (provider.info.applicationInfo.flags
7482                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7483                return null;
7484            }
7485            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7486            if (ps == null) {
7487                return null;
7488            }
7489            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7490                    ps.readUserState(userId), userId);
7491            if (pi == null) {
7492                return null;
7493            }
7494            final ResolveInfo res = new ResolveInfo();
7495            res.providerInfo = pi;
7496            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7497                res.filter = filter;
7498            }
7499            res.priority = info.getPriority();
7500            res.preferredOrder = provider.owner.mPreferredOrder;
7501            res.match = match;
7502            res.isDefault = info.hasDefault;
7503            res.labelRes = info.labelRes;
7504            res.nonLocalizedLabel = info.nonLocalizedLabel;
7505            res.icon = info.icon;
7506            res.system = isSystemApp(res.providerInfo.applicationInfo);
7507            return res;
7508        }
7509
7510        @Override
7511        protected void sortResults(List<ResolveInfo> results) {
7512            Collections.sort(results, mResolvePrioritySorter);
7513        }
7514
7515        @Override
7516        protected void dumpFilter(PrintWriter out, String prefix,
7517                PackageParser.ProviderIntentInfo filter) {
7518            out.print(prefix);
7519            out.print(
7520                    Integer.toHexString(System.identityHashCode(filter.provider)));
7521            out.print(' ');
7522            filter.provider.printComponentShortName(out);
7523            out.print(" filter ");
7524            out.println(Integer.toHexString(System.identityHashCode(filter)));
7525        }
7526
7527        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7528                = new HashMap<ComponentName, PackageParser.Provider>();
7529        private int mFlags;
7530    };
7531
7532    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7533            new Comparator<ResolveInfo>() {
7534        public int compare(ResolveInfo r1, ResolveInfo r2) {
7535            int v1 = r1.priority;
7536            int v2 = r2.priority;
7537            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7538            if (v1 != v2) {
7539                return (v1 > v2) ? -1 : 1;
7540            }
7541            v1 = r1.preferredOrder;
7542            v2 = r2.preferredOrder;
7543            if (v1 != v2) {
7544                return (v1 > v2) ? -1 : 1;
7545            }
7546            if (r1.isDefault != r2.isDefault) {
7547                return r1.isDefault ? -1 : 1;
7548            }
7549            v1 = r1.match;
7550            v2 = r2.match;
7551            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7552            if (v1 != v2) {
7553                return (v1 > v2) ? -1 : 1;
7554            }
7555            if (r1.system != r2.system) {
7556                return r1.system ? -1 : 1;
7557            }
7558            return 0;
7559        }
7560    };
7561
7562    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7563            new Comparator<ProviderInfo>() {
7564        public int compare(ProviderInfo p1, ProviderInfo p2) {
7565            final int v1 = p1.initOrder;
7566            final int v2 = p2.initOrder;
7567            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7568        }
7569    };
7570
7571    static final void sendPackageBroadcast(String action, String pkg,
7572            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7573            int[] userIds) {
7574        IActivityManager am = ActivityManagerNative.getDefault();
7575        if (am != null) {
7576            try {
7577                if (userIds == null) {
7578                    userIds = am.getRunningUserIds();
7579                }
7580                for (int id : userIds) {
7581                    final Intent intent = new Intent(action,
7582                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7583                    if (extras != null) {
7584                        intent.putExtras(extras);
7585                    }
7586                    if (targetPkg != null) {
7587                        intent.setPackage(targetPkg);
7588                    }
7589                    // Modify the UID when posting to other users
7590                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7591                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7592                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7593                        intent.putExtra(Intent.EXTRA_UID, uid);
7594                    }
7595                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7596                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7597                    if (DEBUG_BROADCASTS) {
7598                        RuntimeException here = new RuntimeException("here");
7599                        here.fillInStackTrace();
7600                        Slog.d(TAG, "Sending to user " + id + ": "
7601                                + intent.toShortString(false, true, false, false)
7602                                + " " + intent.getExtras(), here);
7603                    }
7604                    am.broadcastIntent(null, intent, null, finishedReceiver,
7605                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7606                            finishedReceiver != null, false, id);
7607                }
7608            } catch (RemoteException ex) {
7609            }
7610        }
7611    }
7612
7613    /**
7614     * Check if the external storage media is available. This is true if there
7615     * is a mounted external storage medium or if the external storage is
7616     * emulated.
7617     */
7618    private boolean isExternalMediaAvailable() {
7619        return mMediaMounted || Environment.isExternalStorageEmulated();
7620    }
7621
7622    @Override
7623    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7624        // writer
7625        synchronized (mPackages) {
7626            if (!isExternalMediaAvailable()) {
7627                // If the external storage is no longer mounted at this point,
7628                // the caller may not have been able to delete all of this
7629                // packages files and can not delete any more.  Bail.
7630                return null;
7631            }
7632            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7633            if (lastPackage != null) {
7634                pkgs.remove(lastPackage);
7635            }
7636            if (pkgs.size() > 0) {
7637                return pkgs.get(0);
7638            }
7639        }
7640        return null;
7641    }
7642
7643    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7644        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7645                userId, andCode ? 1 : 0, packageName);
7646        if (mSystemReady) {
7647            msg.sendToTarget();
7648        } else {
7649            if (mPostSystemReadyMessages == null) {
7650                mPostSystemReadyMessages = new ArrayList<>();
7651            }
7652            mPostSystemReadyMessages.add(msg);
7653        }
7654    }
7655
7656    void startCleaningPackages() {
7657        // reader
7658        synchronized (mPackages) {
7659            if (!isExternalMediaAvailable()) {
7660                return;
7661            }
7662            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7663                return;
7664            }
7665        }
7666        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7667        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7668        IActivityManager am = ActivityManagerNative.getDefault();
7669        if (am != null) {
7670            try {
7671                am.startService(null, intent, null, UserHandle.USER_OWNER);
7672            } catch (RemoteException e) {
7673            }
7674        }
7675    }
7676
7677    @Override
7678    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7679            int installFlags, String installerPackageName, VerificationParams verificationParams,
7680            String packageAbiOverride) {
7681        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7682                packageAbiOverride, UserHandle.getCallingUserId());
7683    }
7684
7685    @Override
7686    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7687            int installFlags, String installerPackageName, VerificationParams verificationParams,
7688            String packageAbiOverride, int userId) {
7689        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7690
7691        final int callingUid = Binder.getCallingUid();
7692        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7693
7694        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7695            try {
7696                if (observer != null) {
7697                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7698                }
7699            } catch (RemoteException re) {
7700            }
7701            return;
7702        }
7703
7704        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7705            installFlags |= PackageManager.INSTALL_FROM_ADB;
7706
7707        } else {
7708            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7709            // about installerPackageName.
7710
7711            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7712            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7713        }
7714
7715        UserHandle user;
7716        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7717            user = UserHandle.ALL;
7718        } else {
7719            user = new UserHandle(userId);
7720        }
7721
7722        verificationParams.setInstallerUid(callingUid);
7723
7724        final File originFile = new File(originPath);
7725        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7726
7727        final Message msg = mHandler.obtainMessage(INIT_COPY);
7728        msg.obj = new InstallParams(origin, observer, installFlags,
7729                installerPackageName, verificationParams, user, packageAbiOverride);
7730        mHandler.sendMessage(msg);
7731    }
7732
7733    void installStage(String packageName, File stagedDir, String stagedCid,
7734            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7735            String installerPackageName, int installerUid, UserHandle user) {
7736        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7737                params.referrerUri, installerUid, null);
7738
7739        final OriginInfo origin;
7740        if (stagedDir != null) {
7741            origin = OriginInfo.fromStagedFile(stagedDir);
7742        } else {
7743            origin = OriginInfo.fromStagedContainer(stagedCid);
7744        }
7745
7746        final Message msg = mHandler.obtainMessage(INIT_COPY);
7747        msg.obj = new InstallParams(origin, observer, params.installFlags,
7748                installerPackageName, verifParams, user, params.abiOverride);
7749        mHandler.sendMessage(msg);
7750    }
7751
7752    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7753        Bundle extras = new Bundle(1);
7754        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7755
7756        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7757                packageName, extras, null, null, new int[] {userId});
7758        try {
7759            IActivityManager am = ActivityManagerNative.getDefault();
7760            final boolean isSystem =
7761                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7762            if (isSystem && am.isUserRunning(userId, false)) {
7763                // The just-installed/enabled app is bundled on the system, so presumed
7764                // to be able to run automatically without needing an explicit launch.
7765                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7766                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7767                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7768                        .setPackage(packageName);
7769                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7770                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7771            }
7772        } catch (RemoteException e) {
7773            // shouldn't happen
7774            Slog.w(TAG, "Unable to bootstrap installed package", e);
7775        }
7776    }
7777
7778    @Override
7779    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7780            int userId) {
7781        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7782        PackageSetting pkgSetting;
7783        final int uid = Binder.getCallingUid();
7784        enforceCrossUserPermission(uid, userId, true, true,
7785                "setApplicationHiddenSetting for user " + userId);
7786
7787        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7788            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7789            return false;
7790        }
7791
7792        long callingId = Binder.clearCallingIdentity();
7793        try {
7794            boolean sendAdded = false;
7795            boolean sendRemoved = false;
7796            // writer
7797            synchronized (mPackages) {
7798                pkgSetting = mSettings.mPackages.get(packageName);
7799                if (pkgSetting == null) {
7800                    return false;
7801                }
7802                if (pkgSetting.getHidden(userId) != hidden) {
7803                    pkgSetting.setHidden(hidden, userId);
7804                    mSettings.writePackageRestrictionsLPr(userId);
7805                    if (hidden) {
7806                        sendRemoved = true;
7807                    } else {
7808                        sendAdded = true;
7809                    }
7810                }
7811            }
7812            if (sendAdded) {
7813                sendPackageAddedForUser(packageName, pkgSetting, userId);
7814                return true;
7815            }
7816            if (sendRemoved) {
7817                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7818                        "hiding pkg");
7819                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7820            }
7821        } finally {
7822            Binder.restoreCallingIdentity(callingId);
7823        }
7824        return false;
7825    }
7826
7827    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7828            int userId) {
7829        final PackageRemovedInfo info = new PackageRemovedInfo();
7830        info.removedPackage = packageName;
7831        info.removedUsers = new int[] {userId};
7832        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7833        info.sendBroadcast(false, false, false);
7834    }
7835
7836    /**
7837     * Returns true if application is not found or there was an error. Otherwise it returns
7838     * the hidden state of the package for the given user.
7839     */
7840    @Override
7841    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7842        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7843        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7844                false, "getApplicationHidden for user " + userId);
7845        PackageSetting pkgSetting;
7846        long callingId = Binder.clearCallingIdentity();
7847        try {
7848            // writer
7849            synchronized (mPackages) {
7850                pkgSetting = mSettings.mPackages.get(packageName);
7851                if (pkgSetting == null) {
7852                    return true;
7853                }
7854                return pkgSetting.getHidden(userId);
7855            }
7856        } finally {
7857            Binder.restoreCallingIdentity(callingId);
7858        }
7859    }
7860
7861    /**
7862     * @hide
7863     */
7864    @Override
7865    public int installExistingPackageAsUser(String packageName, int userId) {
7866        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7867                null);
7868        PackageSetting pkgSetting;
7869        final int uid = Binder.getCallingUid();
7870        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7871                + userId);
7872        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7873            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7874        }
7875
7876        long callingId = Binder.clearCallingIdentity();
7877        try {
7878            boolean sendAdded = false;
7879            Bundle extras = new Bundle(1);
7880
7881            // writer
7882            synchronized (mPackages) {
7883                pkgSetting = mSettings.mPackages.get(packageName);
7884                if (pkgSetting == null) {
7885                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7886                }
7887                if (!pkgSetting.getInstalled(userId)) {
7888                    pkgSetting.setInstalled(true, userId);
7889                    pkgSetting.setHidden(false, userId);
7890                    mSettings.writePackageRestrictionsLPr(userId);
7891                    sendAdded = true;
7892                }
7893            }
7894
7895            if (sendAdded) {
7896                sendPackageAddedForUser(packageName, pkgSetting, userId);
7897            }
7898        } finally {
7899            Binder.restoreCallingIdentity(callingId);
7900        }
7901
7902        return PackageManager.INSTALL_SUCCEEDED;
7903    }
7904
7905    boolean isUserRestricted(int userId, String restrictionKey) {
7906        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7907        if (restrictions.getBoolean(restrictionKey, false)) {
7908            Log.w(TAG, "User is restricted: " + restrictionKey);
7909            return true;
7910        }
7911        return false;
7912    }
7913
7914    @Override
7915    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7916        mContext.enforceCallingOrSelfPermission(
7917                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7918                "Only package verification agents can verify applications");
7919
7920        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7921        final PackageVerificationResponse response = new PackageVerificationResponse(
7922                verificationCode, Binder.getCallingUid());
7923        msg.arg1 = id;
7924        msg.obj = response;
7925        mHandler.sendMessage(msg);
7926    }
7927
7928    @Override
7929    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7930            long millisecondsToDelay) {
7931        mContext.enforceCallingOrSelfPermission(
7932                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7933                "Only package verification agents can extend verification timeouts");
7934
7935        final PackageVerificationState state = mPendingVerification.get(id);
7936        final PackageVerificationResponse response = new PackageVerificationResponse(
7937                verificationCodeAtTimeout, Binder.getCallingUid());
7938
7939        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7940            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7941        }
7942        if (millisecondsToDelay < 0) {
7943            millisecondsToDelay = 0;
7944        }
7945        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7946                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7947            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7948        }
7949
7950        if ((state != null) && !state.timeoutExtended()) {
7951            state.extendTimeout();
7952
7953            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7954            msg.arg1 = id;
7955            msg.obj = response;
7956            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7957        }
7958    }
7959
7960    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7961            int verificationCode, UserHandle user) {
7962        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7963        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7964        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7965        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7966        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7967
7968        mContext.sendBroadcastAsUser(intent, user,
7969                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7970    }
7971
7972    private ComponentName matchComponentForVerifier(String packageName,
7973            List<ResolveInfo> receivers) {
7974        ActivityInfo targetReceiver = null;
7975
7976        final int NR = receivers.size();
7977        for (int i = 0; i < NR; i++) {
7978            final ResolveInfo info = receivers.get(i);
7979            if (info.activityInfo == null) {
7980                continue;
7981            }
7982
7983            if (packageName.equals(info.activityInfo.packageName)) {
7984                targetReceiver = info.activityInfo;
7985                break;
7986            }
7987        }
7988
7989        if (targetReceiver == null) {
7990            return null;
7991        }
7992
7993        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7994    }
7995
7996    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7997            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7998        if (pkgInfo.verifiers.length == 0) {
7999            return null;
8000        }
8001
8002        final int N = pkgInfo.verifiers.length;
8003        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8004        for (int i = 0; i < N; i++) {
8005            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8006
8007            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8008                    receivers);
8009            if (comp == null) {
8010                continue;
8011            }
8012
8013            final int verifierUid = getUidForVerifier(verifierInfo);
8014            if (verifierUid == -1) {
8015                continue;
8016            }
8017
8018            if (DEBUG_VERIFY) {
8019                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8020                        + " with the correct signature");
8021            }
8022            sufficientVerifiers.add(comp);
8023            verificationState.addSufficientVerifier(verifierUid);
8024        }
8025
8026        return sufficientVerifiers;
8027    }
8028
8029    private int getUidForVerifier(VerifierInfo verifierInfo) {
8030        synchronized (mPackages) {
8031            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8032            if (pkg == null) {
8033                return -1;
8034            } else if (pkg.mSignatures.length != 1) {
8035                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8036                        + " has more than one signature; ignoring");
8037                return -1;
8038            }
8039
8040            /*
8041             * If the public key of the package's signature does not match
8042             * our expected public key, then this is a different package and
8043             * we should skip.
8044             */
8045
8046            final byte[] expectedPublicKey;
8047            try {
8048                final Signature verifierSig = pkg.mSignatures[0];
8049                final PublicKey publicKey = verifierSig.getPublicKey();
8050                expectedPublicKey = publicKey.getEncoded();
8051            } catch (CertificateException e) {
8052                return -1;
8053            }
8054
8055            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8056
8057            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8058                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8059                        + " does not have the expected public key; ignoring");
8060                return -1;
8061            }
8062
8063            return pkg.applicationInfo.uid;
8064        }
8065    }
8066
8067    @Override
8068    public void finishPackageInstall(int token) {
8069        enforceSystemOrRoot("Only the system is allowed to finish installs");
8070
8071        if (DEBUG_INSTALL) {
8072            Slog.v(TAG, "BM finishing package install for " + token);
8073        }
8074
8075        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8076        mHandler.sendMessage(msg);
8077    }
8078
8079    /**
8080     * Get the verification agent timeout.
8081     *
8082     * @return verification timeout in milliseconds
8083     */
8084    private long getVerificationTimeout() {
8085        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8086                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8087                DEFAULT_VERIFICATION_TIMEOUT);
8088    }
8089
8090    /**
8091     * Get the default verification agent response code.
8092     *
8093     * @return default verification response code
8094     */
8095    private int getDefaultVerificationResponse() {
8096        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8097                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8098                DEFAULT_VERIFICATION_RESPONSE);
8099    }
8100
8101    /**
8102     * Check whether or not package verification has been enabled.
8103     *
8104     * @return true if verification should be performed
8105     */
8106    private boolean isVerificationEnabled(int userId, int installFlags) {
8107        if (!DEFAULT_VERIFY_ENABLE) {
8108            return false;
8109        }
8110
8111        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8112
8113        // Check if installing from ADB
8114        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8115            // Do not run verification in a test harness environment
8116            if (ActivityManager.isRunningInTestHarness()) {
8117                return false;
8118            }
8119            if (ensureVerifyAppsEnabled) {
8120                return true;
8121            }
8122            // Check if the developer does not want package verification for ADB installs
8123            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8124                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8125                return false;
8126            }
8127        }
8128
8129        if (ensureVerifyAppsEnabled) {
8130            return true;
8131        }
8132
8133        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8134                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8135    }
8136
8137    /**
8138     * Get the "allow unknown sources" setting.
8139     *
8140     * @return the current "allow unknown sources" setting
8141     */
8142    private int getUnknownSourcesSettings() {
8143        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8144                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8145                -1);
8146    }
8147
8148    @Override
8149    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8150        final int uid = Binder.getCallingUid();
8151        // writer
8152        synchronized (mPackages) {
8153            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8154            if (targetPackageSetting == null) {
8155                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8156            }
8157
8158            PackageSetting installerPackageSetting;
8159            if (installerPackageName != null) {
8160                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8161                if (installerPackageSetting == null) {
8162                    throw new IllegalArgumentException("Unknown installer package: "
8163                            + installerPackageName);
8164                }
8165            } else {
8166                installerPackageSetting = null;
8167            }
8168
8169            Signature[] callerSignature;
8170            Object obj = mSettings.getUserIdLPr(uid);
8171            if (obj != null) {
8172                if (obj instanceof SharedUserSetting) {
8173                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8174                } else if (obj instanceof PackageSetting) {
8175                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8176                } else {
8177                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8178                }
8179            } else {
8180                throw new SecurityException("Unknown calling uid " + uid);
8181            }
8182
8183            // Verify: can't set installerPackageName to a package that is
8184            // not signed with the same cert as the caller.
8185            if (installerPackageSetting != null) {
8186                if (compareSignatures(callerSignature,
8187                        installerPackageSetting.signatures.mSignatures)
8188                        != PackageManager.SIGNATURE_MATCH) {
8189                    throw new SecurityException(
8190                            "Caller does not have same cert as new installer package "
8191                            + installerPackageName);
8192                }
8193            }
8194
8195            // Verify: if target already has an installer package, it must
8196            // be signed with the same cert as the caller.
8197            if (targetPackageSetting.installerPackageName != null) {
8198                PackageSetting setting = mSettings.mPackages.get(
8199                        targetPackageSetting.installerPackageName);
8200                // If the currently set package isn't valid, then it's always
8201                // okay to change it.
8202                if (setting != null) {
8203                    if (compareSignatures(callerSignature,
8204                            setting.signatures.mSignatures)
8205                            != PackageManager.SIGNATURE_MATCH) {
8206                        throw new SecurityException(
8207                                "Caller does not have same cert as old installer package "
8208                                + targetPackageSetting.installerPackageName);
8209                    }
8210                }
8211            }
8212
8213            // Okay!
8214            targetPackageSetting.installerPackageName = installerPackageName;
8215            scheduleWriteSettingsLocked();
8216        }
8217    }
8218
8219    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8220        // Queue up an async operation since the package installation may take a little while.
8221        mHandler.post(new Runnable() {
8222            public void run() {
8223                mHandler.removeCallbacks(this);
8224                 // Result object to be returned
8225                PackageInstalledInfo res = new PackageInstalledInfo();
8226                res.returnCode = currentStatus;
8227                res.uid = -1;
8228                res.pkg = null;
8229                res.removedInfo = new PackageRemovedInfo();
8230                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8231                    args.doPreInstall(res.returnCode);
8232                    synchronized (mInstallLock) {
8233                        installPackageLI(args, res);
8234                    }
8235                    args.doPostInstall(res.returnCode, res.uid);
8236                }
8237
8238                // A restore should be performed at this point if (a) the install
8239                // succeeded, (b) the operation is not an update, and (c) the new
8240                // package has not opted out of backup participation.
8241                final boolean update = res.removedInfo.removedPackage != null;
8242                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8243                boolean doRestore = !update
8244                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8245
8246                // Set up the post-install work request bookkeeping.  This will be used
8247                // and cleaned up by the post-install event handling regardless of whether
8248                // there's a restore pass performed.  Token values are >= 1.
8249                int token;
8250                if (mNextInstallToken < 0) mNextInstallToken = 1;
8251                token = mNextInstallToken++;
8252
8253                PostInstallData data = new PostInstallData(args, res);
8254                mRunningInstalls.put(token, data);
8255                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8256
8257                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8258                    // Pass responsibility to the Backup Manager.  It will perform a
8259                    // restore if appropriate, then pass responsibility back to the
8260                    // Package Manager to run the post-install observer callbacks
8261                    // and broadcasts.
8262                    IBackupManager bm = IBackupManager.Stub.asInterface(
8263                            ServiceManager.getService(Context.BACKUP_SERVICE));
8264                    if (bm != null) {
8265                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8266                                + " to BM for possible restore");
8267                        try {
8268                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8269                        } catch (RemoteException e) {
8270                            // can't happen; the backup manager is local
8271                        } catch (Exception e) {
8272                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8273                            doRestore = false;
8274                        }
8275                    } else {
8276                        Slog.e(TAG, "Backup Manager not found!");
8277                        doRestore = false;
8278                    }
8279                }
8280
8281                if (!doRestore) {
8282                    // No restore possible, or the Backup Manager was mysteriously not
8283                    // available -- just fire the post-install work request directly.
8284                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8285                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8286                    mHandler.sendMessage(msg);
8287                }
8288            }
8289        });
8290    }
8291
8292    private abstract class HandlerParams {
8293        private static final int MAX_RETRIES = 4;
8294
8295        /**
8296         * Number of times startCopy() has been attempted and had a non-fatal
8297         * error.
8298         */
8299        private int mRetries = 0;
8300
8301        /** User handle for the user requesting the information or installation. */
8302        private final UserHandle mUser;
8303
8304        HandlerParams(UserHandle user) {
8305            mUser = user;
8306        }
8307
8308        UserHandle getUser() {
8309            return mUser;
8310        }
8311
8312        final boolean startCopy() {
8313            boolean res;
8314            try {
8315                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8316
8317                if (++mRetries > MAX_RETRIES) {
8318                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8319                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8320                    handleServiceError();
8321                    return false;
8322                } else {
8323                    handleStartCopy();
8324                    res = true;
8325                }
8326            } catch (RemoteException e) {
8327                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8328                mHandler.sendEmptyMessage(MCS_RECONNECT);
8329                res = false;
8330            }
8331            handleReturnCode();
8332            return res;
8333        }
8334
8335        final void serviceError() {
8336            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8337            handleServiceError();
8338            handleReturnCode();
8339        }
8340
8341        abstract void handleStartCopy() throws RemoteException;
8342        abstract void handleServiceError();
8343        abstract void handleReturnCode();
8344    }
8345
8346    class MeasureParams extends HandlerParams {
8347        private final PackageStats mStats;
8348        private boolean mSuccess;
8349
8350        private final IPackageStatsObserver mObserver;
8351
8352        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8353            super(new UserHandle(stats.userHandle));
8354            mObserver = observer;
8355            mStats = stats;
8356        }
8357
8358        @Override
8359        public String toString() {
8360            return "MeasureParams{"
8361                + Integer.toHexString(System.identityHashCode(this))
8362                + " " + mStats.packageName + "}";
8363        }
8364
8365        @Override
8366        void handleStartCopy() throws RemoteException {
8367            synchronized (mInstallLock) {
8368                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8369            }
8370
8371            if (mSuccess) {
8372                final boolean mounted;
8373                if (Environment.isExternalStorageEmulated()) {
8374                    mounted = true;
8375                } else {
8376                    final String status = Environment.getExternalStorageState();
8377                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8378                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8379                }
8380
8381                if (mounted) {
8382                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8383
8384                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8385                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8386
8387                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8388                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8389
8390                    // Always subtract cache size, since it's a subdirectory
8391                    mStats.externalDataSize -= mStats.externalCacheSize;
8392
8393                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8394                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8395
8396                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8397                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8398                }
8399            }
8400        }
8401
8402        @Override
8403        void handleReturnCode() {
8404            if (mObserver != null) {
8405                try {
8406                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8407                } catch (RemoteException e) {
8408                    Slog.i(TAG, "Observer no longer exists.");
8409                }
8410            }
8411        }
8412
8413        @Override
8414        void handleServiceError() {
8415            Slog.e(TAG, "Could not measure application " + mStats.packageName
8416                            + " external storage");
8417        }
8418    }
8419
8420    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8421            throws RemoteException {
8422        long result = 0;
8423        for (File path : paths) {
8424            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8425        }
8426        return result;
8427    }
8428
8429    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8430        for (File path : paths) {
8431            try {
8432                mcs.clearDirectory(path.getAbsolutePath());
8433            } catch (RemoteException e) {
8434            }
8435        }
8436    }
8437
8438    static class OriginInfo {
8439        /**
8440         * Location where install is coming from, before it has been
8441         * copied/renamed into place. This could be a single monolithic APK
8442         * file, or a cluster directory. This location may be untrusted.
8443         */
8444        final File file;
8445        final String cid;
8446
8447        /**
8448         * Flag indicating that {@link #file} or {@link #cid} has already been
8449         * staged, meaning downstream users don't need to defensively copy the
8450         * contents.
8451         */
8452        final boolean staged;
8453
8454        /**
8455         * Flag indicating that {@link #file} or {@link #cid} is an already
8456         * installed app that is being moved.
8457         */
8458        final boolean existing;
8459
8460        final String resolvedPath;
8461        final File resolvedFile;
8462
8463        static OriginInfo fromNothing() {
8464            return new OriginInfo(null, null, false, false);
8465        }
8466
8467        static OriginInfo fromUntrustedFile(File file) {
8468            return new OriginInfo(file, null, false, false);
8469        }
8470
8471        static OriginInfo fromExistingFile(File file) {
8472            return new OriginInfo(file, null, false, true);
8473        }
8474
8475        static OriginInfo fromStagedFile(File file) {
8476            return new OriginInfo(file, null, true, false);
8477        }
8478
8479        static OriginInfo fromStagedContainer(String cid) {
8480            return new OriginInfo(null, cid, true, false);
8481        }
8482
8483        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8484            this.file = file;
8485            this.cid = cid;
8486            this.staged = staged;
8487            this.existing = existing;
8488
8489            if (cid != null) {
8490                resolvedPath = PackageHelper.getSdDir(cid);
8491                resolvedFile = new File(resolvedPath);
8492            } else if (file != null) {
8493                resolvedPath = file.getAbsolutePath();
8494                resolvedFile = file;
8495            } else {
8496                resolvedPath = null;
8497                resolvedFile = null;
8498            }
8499        }
8500    }
8501
8502    class InstallParams extends HandlerParams {
8503        final OriginInfo origin;
8504        final IPackageInstallObserver2 observer;
8505        int installFlags;
8506        final String installerPackageName;
8507        final VerificationParams verificationParams;
8508        private InstallArgs mArgs;
8509        private int mRet;
8510        final String packageAbiOverride;
8511
8512        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8513                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8514                String packageAbiOverride) {
8515            super(user);
8516            this.origin = origin;
8517            this.observer = observer;
8518            this.installFlags = installFlags;
8519            this.installerPackageName = installerPackageName;
8520            this.verificationParams = verificationParams;
8521            this.packageAbiOverride = packageAbiOverride;
8522        }
8523
8524        @Override
8525        public String toString() {
8526            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8527                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8528        }
8529
8530        public ManifestDigest getManifestDigest() {
8531            if (verificationParams == null) {
8532                return null;
8533            }
8534            return verificationParams.getManifestDigest();
8535        }
8536
8537        private int installLocationPolicy(PackageInfoLite pkgLite) {
8538            String packageName = pkgLite.packageName;
8539            int installLocation = pkgLite.installLocation;
8540            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8541            // reader
8542            synchronized (mPackages) {
8543                PackageParser.Package pkg = mPackages.get(packageName);
8544                if (pkg != null) {
8545                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8546                        // Check for downgrading.
8547                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8548                            if (pkgLite.versionCode < pkg.mVersionCode) {
8549                                Slog.w(TAG, "Can't install update of " + packageName
8550                                        + " update version " + pkgLite.versionCode
8551                                        + " is older than installed version "
8552                                        + pkg.mVersionCode);
8553                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8554                            }
8555                        }
8556                        // Check for updated system application.
8557                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8558                            if (onSd) {
8559                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8560                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8561                            }
8562                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8563                        } else {
8564                            if (onSd) {
8565                                // Install flag overrides everything.
8566                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8567                            }
8568                            // If current upgrade specifies particular preference
8569                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8570                                // Application explicitly specified internal.
8571                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8572                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8573                                // App explictly prefers external. Let policy decide
8574                            } else {
8575                                // Prefer previous location
8576                                if (isExternal(pkg)) {
8577                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8578                                }
8579                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8580                            }
8581                        }
8582                    } else {
8583                        // Invalid install. Return error code
8584                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8585                    }
8586                }
8587            }
8588            // All the special cases have been taken care of.
8589            // Return result based on recommended install location.
8590            if (onSd) {
8591                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8592            }
8593            return pkgLite.recommendedInstallLocation;
8594        }
8595
8596        /*
8597         * Invoke remote method to get package information and install
8598         * location values. Override install location based on default
8599         * policy if needed and then create install arguments based
8600         * on the install location.
8601         */
8602        public void handleStartCopy() throws RemoteException {
8603            int ret = PackageManager.INSTALL_SUCCEEDED;
8604
8605            // If we're already staged, we've firmly committed to an install location
8606            if (origin.staged) {
8607                if (origin.file != null) {
8608                    installFlags |= PackageManager.INSTALL_INTERNAL;
8609                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8610                } else if (origin.cid != null) {
8611                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8612                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8613                } else {
8614                    throw new IllegalStateException("Invalid stage location");
8615                }
8616            }
8617
8618            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8619            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8620
8621            PackageInfoLite pkgLite = null;
8622
8623            if (onInt && onSd) {
8624                // Check if both bits are set.
8625                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8626                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8627            } else {
8628                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8629                        packageAbiOverride);
8630
8631                /*
8632                 * If we have too little free space, try to free cache
8633                 * before giving up.
8634                 */
8635                if (!origin.staged && pkgLite.recommendedInstallLocation
8636                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8637                    // TODO: focus freeing disk space on the target device
8638                    final StorageManager storage = StorageManager.from(mContext);
8639                    final long lowThreshold = storage.getStorageLowBytes(
8640                            Environment.getDataDirectory());
8641
8642                    final long sizeBytes = mContainerService.calculateInstalledSize(
8643                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8644
8645                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8646                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8647                                installFlags, packageAbiOverride);
8648                    }
8649
8650                    /*
8651                     * The cache free must have deleted the file we
8652                     * downloaded to install.
8653                     *
8654                     * TODO: fix the "freeCache" call to not delete
8655                     *       the file we care about.
8656                     */
8657                    if (pkgLite.recommendedInstallLocation
8658                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8659                        pkgLite.recommendedInstallLocation
8660                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8661                    }
8662                }
8663            }
8664
8665            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8666                int loc = pkgLite.recommendedInstallLocation;
8667                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8668                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8669                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8670                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8671                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8672                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8673                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8674                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8675                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8676                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8677                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8678                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8679                } else {
8680                    // Override with defaults if needed.
8681                    loc = installLocationPolicy(pkgLite);
8682                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8683                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8684                    } else if (!onSd && !onInt) {
8685                        // Override install location with flags
8686                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8687                            // Set the flag to install on external media.
8688                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8689                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8690                        } else {
8691                            // Make sure the flag for installing on external
8692                            // media is unset
8693                            installFlags |= PackageManager.INSTALL_INTERNAL;
8694                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8695                        }
8696                    }
8697                }
8698            }
8699
8700            final InstallArgs args = createInstallArgs(this);
8701            mArgs = args;
8702
8703            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8704                 /*
8705                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8706                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8707                 */
8708                int userIdentifier = getUser().getIdentifier();
8709                if (userIdentifier == UserHandle.USER_ALL
8710                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8711                    userIdentifier = UserHandle.USER_OWNER;
8712                }
8713
8714                /*
8715                 * Determine if we have any installed package verifiers. If we
8716                 * do, then we'll defer to them to verify the packages.
8717                 */
8718                final int requiredUid = mRequiredVerifierPackage == null ? -1
8719                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8720                if (!origin.existing && requiredUid != -1
8721                        && isVerificationEnabled(userIdentifier, installFlags)) {
8722                    final Intent verification = new Intent(
8723                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8724                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8725                            PACKAGE_MIME_TYPE);
8726                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8727
8728                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8729                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8730                            0 /* TODO: Which userId? */);
8731
8732                    if (DEBUG_VERIFY) {
8733                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8734                                + verification.toString() + " with " + pkgLite.verifiers.length
8735                                + " optional verifiers");
8736                    }
8737
8738                    final int verificationId = mPendingVerificationToken++;
8739
8740                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8741
8742                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8743                            installerPackageName);
8744
8745                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8746                            installFlags);
8747
8748                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8749                            pkgLite.packageName);
8750
8751                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8752                            pkgLite.versionCode);
8753
8754                    if (verificationParams != null) {
8755                        if (verificationParams.getVerificationURI() != null) {
8756                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8757                                 verificationParams.getVerificationURI());
8758                        }
8759                        if (verificationParams.getOriginatingURI() != null) {
8760                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8761                                  verificationParams.getOriginatingURI());
8762                        }
8763                        if (verificationParams.getReferrer() != null) {
8764                            verification.putExtra(Intent.EXTRA_REFERRER,
8765                                  verificationParams.getReferrer());
8766                        }
8767                        if (verificationParams.getOriginatingUid() >= 0) {
8768                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8769                                  verificationParams.getOriginatingUid());
8770                        }
8771                        if (verificationParams.getInstallerUid() >= 0) {
8772                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8773                                  verificationParams.getInstallerUid());
8774                        }
8775                    }
8776
8777                    final PackageVerificationState verificationState = new PackageVerificationState(
8778                            requiredUid, args);
8779
8780                    mPendingVerification.append(verificationId, verificationState);
8781
8782                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8783                            receivers, verificationState);
8784
8785                    /*
8786                     * If any sufficient verifiers were listed in the package
8787                     * manifest, attempt to ask them.
8788                     */
8789                    if (sufficientVerifiers != null) {
8790                        final int N = sufficientVerifiers.size();
8791                        if (N == 0) {
8792                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8793                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8794                        } else {
8795                            for (int i = 0; i < N; i++) {
8796                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8797
8798                                final Intent sufficientIntent = new Intent(verification);
8799                                sufficientIntent.setComponent(verifierComponent);
8800
8801                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8802                            }
8803                        }
8804                    }
8805
8806                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8807                            mRequiredVerifierPackage, receivers);
8808                    if (ret == PackageManager.INSTALL_SUCCEEDED
8809                            && mRequiredVerifierPackage != null) {
8810                        /*
8811                         * Send the intent to the required verification agent,
8812                         * but only start the verification timeout after the
8813                         * target BroadcastReceivers have run.
8814                         */
8815                        verification.setComponent(requiredVerifierComponent);
8816                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8817                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8818                                new BroadcastReceiver() {
8819                                    @Override
8820                                    public void onReceive(Context context, Intent intent) {
8821                                        final Message msg = mHandler
8822                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8823                                        msg.arg1 = verificationId;
8824                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8825                                    }
8826                                }, null, 0, null, null);
8827
8828                        /*
8829                         * We don't want the copy to proceed until verification
8830                         * succeeds, so null out this field.
8831                         */
8832                        mArgs = null;
8833                    }
8834                } else {
8835                    /*
8836                     * No package verification is enabled, so immediately start
8837                     * the remote call to initiate copy using temporary file.
8838                     */
8839                    ret = args.copyApk(mContainerService, true);
8840                }
8841            }
8842
8843            mRet = ret;
8844        }
8845
8846        @Override
8847        void handleReturnCode() {
8848            // If mArgs is null, then MCS couldn't be reached. When it
8849            // reconnects, it will try again to install. At that point, this
8850            // will succeed.
8851            if (mArgs != null) {
8852                processPendingInstall(mArgs, mRet);
8853            }
8854        }
8855
8856        @Override
8857        void handleServiceError() {
8858            mArgs = createInstallArgs(this);
8859            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8860        }
8861
8862        public boolean isForwardLocked() {
8863            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8864        }
8865    }
8866
8867    /**
8868     * Used during creation of InstallArgs
8869     *
8870     * @param installFlags package installation flags
8871     * @return true if should be installed on external storage
8872     */
8873    private static boolean installOnSd(int installFlags) {
8874        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8875            return false;
8876        }
8877        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8878            return true;
8879        }
8880        return false;
8881    }
8882
8883    /**
8884     * Used during creation of InstallArgs
8885     *
8886     * @param installFlags package installation flags
8887     * @return true if should be installed as forward locked
8888     */
8889    private static boolean installForwardLocked(int installFlags) {
8890        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8891    }
8892
8893    private InstallArgs createInstallArgs(InstallParams params) {
8894        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8895            return new AsecInstallArgs(params);
8896        } else {
8897            return new FileInstallArgs(params);
8898        }
8899    }
8900
8901    /**
8902     * Create args that describe an existing installed package. Typically used
8903     * when cleaning up old installs, or used as a move source.
8904     */
8905    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8906            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8907        final boolean isInAsec;
8908        if (installOnSd(installFlags)) {
8909            /* Apps on SD card are always in ASEC containers. */
8910            isInAsec = true;
8911        } else if (installForwardLocked(installFlags)
8912                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8913            /*
8914             * Forward-locked apps are only in ASEC containers if they're the
8915             * new style
8916             */
8917            isInAsec = true;
8918        } else {
8919            isInAsec = false;
8920        }
8921
8922        if (isInAsec) {
8923            return new AsecInstallArgs(codePath, instructionSets,
8924                    installOnSd(installFlags), installForwardLocked(installFlags));
8925        } else {
8926            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8927                    instructionSets);
8928        }
8929    }
8930
8931    static abstract class InstallArgs {
8932        /** @see InstallParams#origin */
8933        final OriginInfo origin;
8934
8935        final IPackageInstallObserver2 observer;
8936        // Always refers to PackageManager flags only
8937        final int installFlags;
8938        final String installerPackageName;
8939        final ManifestDigest manifestDigest;
8940        final UserHandle user;
8941        final String abiOverride;
8942
8943        // The list of instruction sets supported by this app. This is currently
8944        // only used during the rmdex() phase to clean up resources. We can get rid of this
8945        // if we move dex files under the common app path.
8946        /* nullable */ String[] instructionSets;
8947
8948        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8949                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
8950                String[] instructionSets, String abiOverride) {
8951            this.origin = origin;
8952            this.installFlags = installFlags;
8953            this.observer = observer;
8954            this.installerPackageName = installerPackageName;
8955            this.manifestDigest = manifestDigest;
8956            this.user = user;
8957            this.instructionSets = instructionSets;
8958            this.abiOverride = abiOverride;
8959        }
8960
8961        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8962        abstract int doPreInstall(int status);
8963
8964        /**
8965         * Rename package into final resting place. All paths on the given
8966         * scanned package should be updated to reflect the rename.
8967         */
8968        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
8969        abstract int doPostInstall(int status, int uid);
8970
8971        /** @see PackageSettingBase#codePathString */
8972        abstract String getCodePath();
8973        /** @see PackageSettingBase#resourcePathString */
8974        abstract String getResourcePath();
8975        abstract String getLegacyNativeLibraryPath();
8976
8977        // Need installer lock especially for dex file removal.
8978        abstract void cleanUpResourcesLI();
8979        abstract boolean doPostDeleteLI(boolean delete);
8980        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8981
8982        /**
8983         * Called before the source arguments are copied. This is used mostly
8984         * for MoveParams when it needs to read the source file to put it in the
8985         * destination.
8986         */
8987        int doPreCopy() {
8988            return PackageManager.INSTALL_SUCCEEDED;
8989        }
8990
8991        /**
8992         * Called after the source arguments are copied. This is used mostly for
8993         * MoveParams when it needs to read the source file to put it in the
8994         * destination.
8995         *
8996         * @return
8997         */
8998        int doPostCopy(int uid) {
8999            return PackageManager.INSTALL_SUCCEEDED;
9000        }
9001
9002        protected boolean isFwdLocked() {
9003            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9004        }
9005
9006        protected boolean isExternal() {
9007            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9008        }
9009
9010        UserHandle getUser() {
9011            return user;
9012        }
9013    }
9014
9015    /**
9016     * Logic to handle installation of non-ASEC applications, including copying
9017     * and renaming logic.
9018     */
9019    class FileInstallArgs extends InstallArgs {
9020        private File codeFile;
9021        private File resourceFile;
9022        private File legacyNativeLibraryPath;
9023
9024        // Example topology:
9025        // /data/app/com.example/base.apk
9026        // /data/app/com.example/split_foo.apk
9027        // /data/app/com.example/lib/arm/libfoo.so
9028        // /data/app/com.example/lib/arm64/libfoo.so
9029        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9030
9031        /** New install */
9032        FileInstallArgs(InstallParams params) {
9033            super(params.origin, params.observer, params.installFlags,
9034                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9035                    null /* instruction sets */, params.packageAbiOverride);
9036            if (isFwdLocked()) {
9037                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9038            }
9039        }
9040
9041        /** Existing install */
9042        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9043                String[] instructionSets) {
9044            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9045            this.codeFile = (codePath != null) ? new File(codePath) : null;
9046            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9047            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9048                    new File(legacyNativeLibraryPath) : null;
9049        }
9050
9051        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9052            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9053                    isFwdLocked(), abiOverride);
9054
9055            final StorageManager storage = StorageManager.from(mContext);
9056            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9057        }
9058
9059        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9060            if (origin.staged) {
9061                Slog.d(TAG, origin.file + " already staged; skipping copy");
9062                codeFile = origin.file;
9063                resourceFile = origin.file;
9064                return PackageManager.INSTALL_SUCCEEDED;
9065            }
9066
9067            try {
9068                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9069                codeFile = tempDir;
9070                resourceFile = tempDir;
9071            } catch (IOException e) {
9072                Slog.w(TAG, "Failed to create copy file: " + e);
9073                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9074            }
9075
9076            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9077                @Override
9078                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9079                    if (!FileUtils.isValidExtFilename(name)) {
9080                        throw new IllegalArgumentException("Invalid filename: " + name);
9081                    }
9082                    try {
9083                        final File file = new File(codeFile, name);
9084                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9085                                O_RDWR | O_CREAT, 0644);
9086                        Os.chmod(file.getAbsolutePath(), 0644);
9087                        return new ParcelFileDescriptor(fd);
9088                    } catch (ErrnoException e) {
9089                        throw new RemoteException("Failed to open: " + e.getMessage());
9090                    }
9091                }
9092            };
9093
9094            int ret = PackageManager.INSTALL_SUCCEEDED;
9095            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9096            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9097                Slog.e(TAG, "Failed to copy package");
9098                return ret;
9099            }
9100
9101            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9102            NativeLibraryHelper.Handle handle = null;
9103            try {
9104                handle = NativeLibraryHelper.Handle.create(codeFile);
9105                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9106                        abiOverride);
9107            } catch (IOException e) {
9108                Slog.e(TAG, "Copying native libraries failed", e);
9109                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9110            } finally {
9111                IoUtils.closeQuietly(handle);
9112            }
9113
9114            return ret;
9115        }
9116
9117        int doPreInstall(int status) {
9118            if (status != PackageManager.INSTALL_SUCCEEDED) {
9119                cleanUp();
9120            }
9121            return status;
9122        }
9123
9124        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9125            if (status != PackageManager.INSTALL_SUCCEEDED) {
9126                cleanUp();
9127                return false;
9128            } else {
9129                final File beforeCodeFile = codeFile;
9130                final File afterCodeFile = getNextCodePath(pkg.packageName);
9131
9132                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9133                try {
9134                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9135                } catch (ErrnoException e) {
9136                    Slog.d(TAG, "Failed to rename", e);
9137                    return false;
9138                }
9139
9140                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9141                    Slog.d(TAG, "Failed to restorecon");
9142                    return false;
9143                }
9144
9145                // Reflect the rename internally
9146                codeFile = afterCodeFile;
9147                resourceFile = afterCodeFile;
9148
9149                // Reflect the rename in scanned details
9150                pkg.codePath = afterCodeFile.getAbsolutePath();
9151                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9152                        pkg.baseCodePath);
9153                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9154                        pkg.splitCodePaths);
9155
9156                // Reflect the rename in app info
9157                pkg.applicationInfo.setCodePath(pkg.codePath);
9158                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9159                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9160                pkg.applicationInfo.setResourcePath(pkg.codePath);
9161                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9162                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9163
9164                return true;
9165            }
9166        }
9167
9168        int doPostInstall(int status, int uid) {
9169            if (status != PackageManager.INSTALL_SUCCEEDED) {
9170                cleanUp();
9171            }
9172            return status;
9173        }
9174
9175        @Override
9176        String getCodePath() {
9177            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9178        }
9179
9180        @Override
9181        String getResourcePath() {
9182            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9183        }
9184
9185        @Override
9186        String getLegacyNativeLibraryPath() {
9187            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9188        }
9189
9190        private boolean cleanUp() {
9191            if (codeFile == null || !codeFile.exists()) {
9192                return false;
9193            }
9194
9195            if (codeFile.isDirectory()) {
9196                FileUtils.deleteContents(codeFile);
9197            }
9198            codeFile.delete();
9199
9200            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9201                resourceFile.delete();
9202            }
9203
9204            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9205                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9206                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9207                }
9208                legacyNativeLibraryPath.delete();
9209            }
9210
9211            return true;
9212        }
9213
9214        void cleanUpResourcesLI() {
9215            // Try enumerating all code paths before deleting
9216            List<String> allCodePaths = Collections.EMPTY_LIST;
9217            if (codeFile != null && codeFile.exists()) {
9218                try {
9219                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9220                    allCodePaths = pkg.getAllCodePaths();
9221                } catch (PackageParserException e) {
9222                    // Ignored; we tried our best
9223                }
9224            }
9225
9226            cleanUp();
9227
9228            if (!allCodePaths.isEmpty()) {
9229                if (instructionSets == null) {
9230                    throw new IllegalStateException("instructionSet == null");
9231                }
9232                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9233                for (String codePath : allCodePaths) {
9234                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9235                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9236                        if (retCode < 0) {
9237                            Slog.w(TAG, "Couldn't remove dex file for package: "
9238                                    + " at location " + codePath + ", retcode=" + retCode);
9239                            // we don't consider this to be a failure of the core package deletion
9240                        }
9241                    }
9242                }
9243            }
9244        }
9245
9246        boolean doPostDeleteLI(boolean delete) {
9247            // XXX err, shouldn't we respect the delete flag?
9248            cleanUpResourcesLI();
9249            return true;
9250        }
9251    }
9252
9253    private boolean isAsecExternal(String cid) {
9254        final String asecPath = PackageHelper.getSdFilesystem(cid);
9255        return !asecPath.startsWith(mAsecInternalPath);
9256    }
9257
9258    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9259            PackageManagerException {
9260        if (copyRet < 0) {
9261            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9262                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9263                throw new PackageManagerException(copyRet, message);
9264            }
9265        }
9266    }
9267
9268    /**
9269     * Extract the MountService "container ID" from the full code path of an
9270     * .apk.
9271     */
9272    static String cidFromCodePath(String fullCodePath) {
9273        int eidx = fullCodePath.lastIndexOf("/");
9274        String subStr1 = fullCodePath.substring(0, eidx);
9275        int sidx = subStr1.lastIndexOf("/");
9276        return subStr1.substring(sidx+1, eidx);
9277    }
9278
9279    /**
9280     * Logic to handle installation of ASEC applications, including copying and
9281     * renaming logic.
9282     */
9283    class AsecInstallArgs extends InstallArgs {
9284        static final String RES_FILE_NAME = "pkg.apk";
9285        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9286
9287        String cid;
9288        String packagePath;
9289        String resourcePath;
9290        String legacyNativeLibraryDir;
9291
9292        /** New install */
9293        AsecInstallArgs(InstallParams params) {
9294            super(params.origin, params.observer, params.installFlags,
9295                    params.installerPackageName, params.getManifestDigest(),
9296                    params.getUser(), null /* instruction sets */,
9297                    params.packageAbiOverride);
9298        }
9299
9300        /** Existing install */
9301        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9302                        boolean isExternal, boolean isForwardLocked) {
9303            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9304                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9305                    instructionSets, null);
9306            // Hackily pretend we're still looking at a full code path
9307            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9308                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9309            }
9310
9311            // Extract cid from fullCodePath
9312            int eidx = fullCodePath.lastIndexOf("/");
9313            String subStr1 = fullCodePath.substring(0, eidx);
9314            int sidx = subStr1.lastIndexOf("/");
9315            cid = subStr1.substring(sidx+1, eidx);
9316            setMountPath(subStr1);
9317        }
9318
9319        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9320            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9321                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9322                    instructionSets, null);
9323            this.cid = cid;
9324            setMountPath(PackageHelper.getSdDir(cid));
9325        }
9326
9327        void createCopyFile() {
9328            cid = mInstallerService.allocateExternalStageCidLegacy();
9329        }
9330
9331        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9332            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9333                    abiOverride);
9334
9335            final File target;
9336            if (isExternal()) {
9337                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9338            } else {
9339                target = Environment.getDataDirectory();
9340            }
9341
9342            final StorageManager storage = StorageManager.from(mContext);
9343            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9344        }
9345
9346        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9347            if (origin.staged) {
9348                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9349                cid = origin.cid;
9350                setMountPath(PackageHelper.getSdDir(cid));
9351                return PackageManager.INSTALL_SUCCEEDED;
9352            }
9353
9354            if (temp) {
9355                createCopyFile();
9356            } else {
9357                /*
9358                 * Pre-emptively destroy the container since it's destroyed if
9359                 * copying fails due to it existing anyway.
9360                 */
9361                PackageHelper.destroySdDir(cid);
9362            }
9363
9364            final String newMountPath = imcs.copyPackageToContainer(
9365                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9366                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9367
9368            if (newMountPath != null) {
9369                setMountPath(newMountPath);
9370                return PackageManager.INSTALL_SUCCEEDED;
9371            } else {
9372                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9373            }
9374        }
9375
9376        @Override
9377        String getCodePath() {
9378            return packagePath;
9379        }
9380
9381        @Override
9382        String getResourcePath() {
9383            return resourcePath;
9384        }
9385
9386        @Override
9387        String getLegacyNativeLibraryPath() {
9388            return legacyNativeLibraryDir;
9389        }
9390
9391        int doPreInstall(int status) {
9392            if (status != PackageManager.INSTALL_SUCCEEDED) {
9393                // Destroy container
9394                PackageHelper.destroySdDir(cid);
9395            } else {
9396                boolean mounted = PackageHelper.isContainerMounted(cid);
9397                if (!mounted) {
9398                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9399                            Process.SYSTEM_UID);
9400                    if (newMountPath != null) {
9401                        setMountPath(newMountPath);
9402                    } else {
9403                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9404                    }
9405                }
9406            }
9407            return status;
9408        }
9409
9410        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9411            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9412            String newMountPath = null;
9413            if (PackageHelper.isContainerMounted(cid)) {
9414                // Unmount the container
9415                if (!PackageHelper.unMountSdDir(cid)) {
9416                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9417                    return false;
9418                }
9419            }
9420            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9421                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9422                        " which might be stale. Will try to clean up.");
9423                // Clean up the stale container and proceed to recreate.
9424                if (!PackageHelper.destroySdDir(newCacheId)) {
9425                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9426                    return false;
9427                }
9428                // Successfully cleaned up stale container. Try to rename again.
9429                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9430                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9431                            + " inspite of cleaning it up.");
9432                    return false;
9433                }
9434            }
9435            if (!PackageHelper.isContainerMounted(newCacheId)) {
9436                Slog.w(TAG, "Mounting container " + newCacheId);
9437                newMountPath = PackageHelper.mountSdDir(newCacheId,
9438                        getEncryptKey(), Process.SYSTEM_UID);
9439            } else {
9440                newMountPath = PackageHelper.getSdDir(newCacheId);
9441            }
9442            if (newMountPath == null) {
9443                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9444                return false;
9445            }
9446            Log.i(TAG, "Succesfully renamed " + cid +
9447                    " to " + newCacheId +
9448                    " at new path: " + newMountPath);
9449            cid = newCacheId;
9450
9451            final File beforeCodeFile = new File(packagePath);
9452            setMountPath(newMountPath);
9453            final File afterCodeFile = new File(packagePath);
9454
9455            // Reflect the rename in scanned details
9456            pkg.codePath = afterCodeFile.getAbsolutePath();
9457            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9458                    pkg.baseCodePath);
9459            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9460                    pkg.splitCodePaths);
9461
9462            // Reflect the rename in app info
9463            pkg.applicationInfo.setCodePath(pkg.codePath);
9464            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9465            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9466            pkg.applicationInfo.setResourcePath(pkg.codePath);
9467            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9468            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9469
9470            return true;
9471        }
9472
9473        private void setMountPath(String mountPath) {
9474            final File mountFile = new File(mountPath);
9475
9476            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9477            if (monolithicFile.exists()) {
9478                packagePath = monolithicFile.getAbsolutePath();
9479                if (isFwdLocked()) {
9480                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9481                } else {
9482                    resourcePath = packagePath;
9483                }
9484            } else {
9485                packagePath = mountFile.getAbsolutePath();
9486                resourcePath = packagePath;
9487            }
9488
9489            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9490        }
9491
9492        int doPostInstall(int status, int uid) {
9493            if (status != PackageManager.INSTALL_SUCCEEDED) {
9494                cleanUp();
9495            } else {
9496                final int groupOwner;
9497                final String protectedFile;
9498                if (isFwdLocked()) {
9499                    groupOwner = UserHandle.getSharedAppGid(uid);
9500                    protectedFile = RES_FILE_NAME;
9501                } else {
9502                    groupOwner = -1;
9503                    protectedFile = null;
9504                }
9505
9506                if (uid < Process.FIRST_APPLICATION_UID
9507                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9508                    Slog.e(TAG, "Failed to finalize " + cid);
9509                    PackageHelper.destroySdDir(cid);
9510                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9511                }
9512
9513                boolean mounted = PackageHelper.isContainerMounted(cid);
9514                if (!mounted) {
9515                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9516                }
9517            }
9518            return status;
9519        }
9520
9521        private void cleanUp() {
9522            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9523
9524            // Destroy secure container
9525            PackageHelper.destroySdDir(cid);
9526        }
9527
9528        private List<String> getAllCodePaths() {
9529            final File codeFile = new File(getCodePath());
9530            if (codeFile != null && codeFile.exists()) {
9531                try {
9532                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9533                    return pkg.getAllCodePaths();
9534                } catch (PackageParserException e) {
9535                    // Ignored; we tried our best
9536                }
9537            }
9538            return Collections.EMPTY_LIST;
9539        }
9540
9541        void cleanUpResourcesLI() {
9542            // Enumerate all code paths before deleting
9543            cleanUpResourcesLI(getAllCodePaths());
9544        }
9545
9546        private void cleanUpResourcesLI(List<String> allCodePaths) {
9547            cleanUp();
9548
9549            if (!allCodePaths.isEmpty()) {
9550                if (instructionSets == null) {
9551                    throw new IllegalStateException("instructionSet == null");
9552                }
9553                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9554                for (String codePath : allCodePaths) {
9555                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9556                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9557                        if (retCode < 0) {
9558                            Slog.w(TAG, "Couldn't remove dex file for package: "
9559                                    + " at location " + codePath + ", retcode=" + retCode);
9560                            // we don't consider this to be a failure of the core package deletion
9561                        }
9562                    }
9563                }
9564            }
9565        }
9566
9567        boolean matchContainer(String app) {
9568            if (cid.startsWith(app)) {
9569                return true;
9570            }
9571            return false;
9572        }
9573
9574        String getPackageName() {
9575            return getAsecPackageName(cid);
9576        }
9577
9578        boolean doPostDeleteLI(boolean delete) {
9579            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9580            final List<String> allCodePaths = getAllCodePaths();
9581            boolean mounted = PackageHelper.isContainerMounted(cid);
9582            if (mounted) {
9583                // Unmount first
9584                if (PackageHelper.unMountSdDir(cid)) {
9585                    mounted = false;
9586                }
9587            }
9588            if (!mounted && delete) {
9589                cleanUpResourcesLI(allCodePaths);
9590            }
9591            return !mounted;
9592        }
9593
9594        @Override
9595        int doPreCopy() {
9596            if (isFwdLocked()) {
9597                if (!PackageHelper.fixSdPermissions(cid,
9598                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9599                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9600                }
9601            }
9602
9603            return PackageManager.INSTALL_SUCCEEDED;
9604        }
9605
9606        @Override
9607        int doPostCopy(int uid) {
9608            if (isFwdLocked()) {
9609                if (uid < Process.FIRST_APPLICATION_UID
9610                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9611                                RES_FILE_NAME)) {
9612                    Slog.e(TAG, "Failed to finalize " + cid);
9613                    PackageHelper.destroySdDir(cid);
9614                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9615                }
9616            }
9617
9618            return PackageManager.INSTALL_SUCCEEDED;
9619        }
9620    }
9621
9622    static String getAsecPackageName(String packageCid) {
9623        int idx = packageCid.lastIndexOf("-");
9624        if (idx == -1) {
9625            return packageCid;
9626        }
9627        return packageCid.substring(0, idx);
9628    }
9629
9630    // Utility method used to create code paths based on package name and available index.
9631    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9632        String idxStr = "";
9633        int idx = 1;
9634        // Fall back to default value of idx=1 if prefix is not
9635        // part of oldCodePath
9636        if (oldCodePath != null) {
9637            String subStr = oldCodePath;
9638            // Drop the suffix right away
9639            if (suffix != null && subStr.endsWith(suffix)) {
9640                subStr = subStr.substring(0, subStr.length() - suffix.length());
9641            }
9642            // If oldCodePath already contains prefix find out the
9643            // ending index to either increment or decrement.
9644            int sidx = subStr.lastIndexOf(prefix);
9645            if (sidx != -1) {
9646                subStr = subStr.substring(sidx + prefix.length());
9647                if (subStr != null) {
9648                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9649                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9650                    }
9651                    try {
9652                        idx = Integer.parseInt(subStr);
9653                        if (idx <= 1) {
9654                            idx++;
9655                        } else {
9656                            idx--;
9657                        }
9658                    } catch(NumberFormatException e) {
9659                    }
9660                }
9661            }
9662        }
9663        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9664        return prefix + idxStr;
9665    }
9666
9667    private File getNextCodePath(String packageName) {
9668        int suffix = 1;
9669        File result;
9670        do {
9671            result = new File(mAppInstallDir, packageName + "-" + suffix);
9672            suffix++;
9673        } while (result.exists());
9674        return result;
9675    }
9676
9677    // Utility method used to ignore ADD/REMOVE events
9678    // by directory observer.
9679    private static boolean ignoreCodePath(String fullPathStr) {
9680        String apkName = deriveCodePathName(fullPathStr);
9681        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9682        if (idx != -1 && ((idx+1) < apkName.length())) {
9683            // Make sure the package ends with a numeral
9684            String version = apkName.substring(idx+1);
9685            try {
9686                Integer.parseInt(version);
9687                return true;
9688            } catch (NumberFormatException e) {}
9689        }
9690        return false;
9691    }
9692
9693    // Utility method that returns the relative package path with respect
9694    // to the installation directory. Like say for /data/data/com.test-1.apk
9695    // string com.test-1 is returned.
9696    static String deriveCodePathName(String codePath) {
9697        if (codePath == null) {
9698            return null;
9699        }
9700        final File codeFile = new File(codePath);
9701        final String name = codeFile.getName();
9702        if (codeFile.isDirectory()) {
9703            return name;
9704        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9705            final int lastDot = name.lastIndexOf('.');
9706            return name.substring(0, lastDot);
9707        } else {
9708            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9709            return null;
9710        }
9711    }
9712
9713    class PackageInstalledInfo {
9714        String name;
9715        int uid;
9716        // The set of users that originally had this package installed.
9717        int[] origUsers;
9718        // The set of users that now have this package installed.
9719        int[] newUsers;
9720        PackageParser.Package pkg;
9721        int returnCode;
9722        String returnMsg;
9723        PackageRemovedInfo removedInfo;
9724
9725        public void setError(int code, String msg) {
9726            returnCode = code;
9727            returnMsg = msg;
9728            Slog.w(TAG, msg);
9729        }
9730
9731        public void setError(String msg, PackageParserException e) {
9732            returnCode = e.error;
9733            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9734            Slog.w(TAG, msg, e);
9735        }
9736
9737        public void setError(String msg, PackageManagerException e) {
9738            returnCode = e.error;
9739            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9740            Slog.w(TAG, msg, e);
9741        }
9742
9743        // In some error cases we want to convey more info back to the observer
9744        String origPackage;
9745        String origPermission;
9746    }
9747
9748    /*
9749     * Install a non-existing package.
9750     */
9751    private void installNewPackageLI(PackageParser.Package pkg,
9752            int parseFlags, int scanFlags, UserHandle user,
9753            String installerPackageName, PackageInstalledInfo res) {
9754        // Remember this for later, in case we need to rollback this install
9755        String pkgName = pkg.packageName;
9756
9757        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9758        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9759        synchronized(mPackages) {
9760            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9761                // A package with the same name is already installed, though
9762                // it has been renamed to an older name.  The package we
9763                // are trying to install should be installed as an update to
9764                // the existing one, but that has not been requested, so bail.
9765                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9766                        + " without first uninstalling package running as "
9767                        + mSettings.mRenamedPackages.get(pkgName));
9768                return;
9769            }
9770            if (mPackages.containsKey(pkgName)) {
9771                // Don't allow installation over an existing package with the same name.
9772                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9773                        + " without first uninstalling.");
9774                return;
9775            }
9776        }
9777
9778        try {
9779            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9780                    System.currentTimeMillis(), user);
9781
9782            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9783            // delete the partially installed application. the data directory will have to be
9784            // restored if it was already existing
9785            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9786                // remove package from internal structures.  Note that we want deletePackageX to
9787                // delete the package data and cache directories that it created in
9788                // scanPackageLocked, unless those directories existed before we even tried to
9789                // install.
9790                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9791                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9792                                res.removedInfo, true);
9793            }
9794
9795        } catch (PackageManagerException e) {
9796            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9797        }
9798    }
9799
9800    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9801        // Upgrade keysets are being used.  Determine if new package has a superset of the
9802        // required keys.
9803        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9804        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9805        for (int i = 0; i < upgradeKeySets.length; i++) {
9806            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9807            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9808                return true;
9809            }
9810        }
9811        return false;
9812    }
9813
9814    private void replacePackageLI(PackageParser.Package pkg,
9815            int parseFlags, int scanFlags, UserHandle user,
9816            String installerPackageName, PackageInstalledInfo res) {
9817        PackageParser.Package oldPackage;
9818        String pkgName = pkg.packageName;
9819        int[] allUsers;
9820        boolean[] perUserInstalled;
9821
9822        // First find the old package info and check signatures
9823        synchronized(mPackages) {
9824            oldPackage = mPackages.get(pkgName);
9825            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9826            PackageSetting ps = mSettings.mPackages.get(pkgName);
9827            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9828                // default to original signature matching
9829                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9830                    != PackageManager.SIGNATURE_MATCH) {
9831                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9832                            "New package has a different signature: " + pkgName);
9833                    return;
9834                }
9835            } else {
9836                if(!checkUpgradeKeySetLP(ps, pkg)) {
9837                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9838                            "New package not signed by keys specified by upgrade-keysets: "
9839                            + pkgName);
9840                    return;
9841                }
9842            }
9843
9844            // In case of rollback, remember per-user/profile install state
9845            allUsers = sUserManager.getUserIds();
9846            perUserInstalled = new boolean[allUsers.length];
9847            for (int i = 0; i < allUsers.length; i++) {
9848                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9849            }
9850        }
9851
9852        boolean sysPkg = (isSystemApp(oldPackage));
9853        if (sysPkg) {
9854            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9855                    user, allUsers, perUserInstalled, installerPackageName, res);
9856        } else {
9857            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9858                    user, allUsers, perUserInstalled, installerPackageName, res);
9859        }
9860    }
9861
9862    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9863            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9864            int[] allUsers, boolean[] perUserInstalled,
9865            String installerPackageName, PackageInstalledInfo res) {
9866        String pkgName = deletedPackage.packageName;
9867        boolean deletedPkg = true;
9868        boolean updatedSettings = false;
9869
9870        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9871                + deletedPackage);
9872        long origUpdateTime;
9873        if (pkg.mExtras != null) {
9874            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9875        } else {
9876            origUpdateTime = 0;
9877        }
9878
9879        // First delete the existing package while retaining the data directory
9880        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9881                res.removedInfo, true)) {
9882            // If the existing package wasn't successfully deleted
9883            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9884            deletedPkg = false;
9885        } else {
9886            // Successfully deleted the old package; proceed with replace.
9887
9888            // If deleted package lived in a container, give users a chance to
9889            // relinquish resources before killing.
9890            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9891                if (DEBUG_INSTALL) {
9892                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9893                }
9894                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9895                final ArrayList<String> pkgList = new ArrayList<String>(1);
9896                pkgList.add(deletedPackage.applicationInfo.packageName);
9897                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9898            }
9899
9900            deleteCodeCacheDirsLI(pkgName);
9901            try {
9902                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9903                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9904                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9905                updatedSettings = true;
9906            } catch (PackageManagerException e) {
9907                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9908            }
9909        }
9910
9911        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9912            // remove package from internal structures.  Note that we want deletePackageX to
9913            // delete the package data and cache directories that it created in
9914            // scanPackageLocked, unless those directories existed before we even tried to
9915            // install.
9916            if(updatedSettings) {
9917                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9918                deletePackageLI(
9919                        pkgName, null, true, allUsers, perUserInstalled,
9920                        PackageManager.DELETE_KEEP_DATA,
9921                                res.removedInfo, true);
9922            }
9923            // Since we failed to install the new package we need to restore the old
9924            // package that we deleted.
9925            if (deletedPkg) {
9926                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9927                File restoreFile = new File(deletedPackage.codePath);
9928                // Parse old package
9929                boolean oldOnSd = isExternal(deletedPackage);
9930                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9931                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9932                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9933                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9934                try {
9935                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9936                } catch (PackageManagerException e) {
9937                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9938                            + e.getMessage());
9939                    return;
9940                }
9941                // Restore of old package succeeded. Update permissions.
9942                // writer
9943                synchronized (mPackages) {
9944                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9945                            UPDATE_PERMISSIONS_ALL);
9946                    // can downgrade to reader
9947                    mSettings.writeLPr();
9948                }
9949                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9950            }
9951        }
9952    }
9953
9954    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9955            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9956            int[] allUsers, boolean[] perUserInstalled,
9957            String installerPackageName, PackageInstalledInfo res) {
9958        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9959                + ", old=" + deletedPackage);
9960        boolean updatedSettings = false;
9961        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
9962        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9963            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9964        }
9965        String packageName = deletedPackage.packageName;
9966        if (packageName == null) {
9967            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9968                    "Attempt to delete null packageName.");
9969            return;
9970        }
9971        PackageParser.Package oldPkg;
9972        PackageSetting oldPkgSetting;
9973        // reader
9974        synchronized (mPackages) {
9975            oldPkg = mPackages.get(packageName);
9976            oldPkgSetting = mSettings.mPackages.get(packageName);
9977            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9978                    (oldPkgSetting == null)) {
9979                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9980                        "Couldn't find package:" + packageName + " information");
9981                return;
9982            }
9983        }
9984
9985        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9986
9987        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9988        res.removedInfo.removedPackage = packageName;
9989        // Remove existing system package
9990        removePackageLI(oldPkgSetting, true);
9991        // writer
9992        synchronized (mPackages) {
9993            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9994                // We didn't need to disable the .apk as a current system package,
9995                // which means we are replacing another update that is already
9996                // installed.  We need to make sure to delete the older one's .apk.
9997                res.removedInfo.args = createInstallArgsForExisting(0,
9998                        deletedPackage.applicationInfo.getCodePath(),
9999                        deletedPackage.applicationInfo.getResourcePath(),
10000                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10001                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10002            } else {
10003                res.removedInfo.args = null;
10004            }
10005        }
10006
10007        // Successfully disabled the old package. Now proceed with re-installation
10008        deleteCodeCacheDirsLI(packageName);
10009
10010        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10011        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10012
10013        PackageParser.Package newPackage = null;
10014        try {
10015            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10016            if (newPackage.mExtras != null) {
10017                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10018                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10019                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10020
10021                // is the update attempting to change shared user? that isn't going to work...
10022                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10023                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10024                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10025                            + " to " + newPkgSetting.sharedUser);
10026                    updatedSettings = true;
10027                }
10028            }
10029
10030            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10031                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10032                updatedSettings = true;
10033            }
10034
10035        } catch (PackageManagerException e) {
10036            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10037        }
10038
10039        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10040            // Re installation failed. Restore old information
10041            // Remove new pkg information
10042            if (newPackage != null) {
10043                removeInstalledPackageLI(newPackage, true);
10044            }
10045            // Add back the old system package
10046            try {
10047                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10048            } catch (PackageManagerException e) {
10049                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10050            }
10051            // Restore the old system information in Settings
10052            synchronized(mPackages) {
10053                if (updatedSettings) {
10054                    mSettings.enableSystemPackageLPw(packageName);
10055                    mSettings.setInstallerPackageName(packageName,
10056                            oldPkgSetting.installerPackageName);
10057                }
10058                mSettings.writeLPr();
10059            }
10060        }
10061    }
10062
10063    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10064            int[] allUsers, boolean[] perUserInstalled,
10065            PackageInstalledInfo res) {
10066        String pkgName = newPackage.packageName;
10067        synchronized (mPackages) {
10068            //write settings. the installStatus will be incomplete at this stage.
10069            //note that the new package setting would have already been
10070            //added to mPackages. It hasn't been persisted yet.
10071            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10072            mSettings.writeLPr();
10073        }
10074
10075        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10076
10077        synchronized (mPackages) {
10078            updatePermissionsLPw(newPackage.packageName, newPackage,
10079                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10080                            ? UPDATE_PERMISSIONS_ALL : 0));
10081            // For system-bundled packages, we assume that installing an upgraded version
10082            // of the package implies that the user actually wants to run that new code,
10083            // so we enable the package.
10084            if (isSystemApp(newPackage)) {
10085                // NB: implicit assumption that system package upgrades apply to all users
10086                if (DEBUG_INSTALL) {
10087                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10088                }
10089                PackageSetting ps = mSettings.mPackages.get(pkgName);
10090                if (ps != null) {
10091                    if (res.origUsers != null) {
10092                        for (int userHandle : res.origUsers) {
10093                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10094                                    userHandle, installerPackageName);
10095                        }
10096                    }
10097                    // Also convey the prior install/uninstall state
10098                    if (allUsers != null && perUserInstalled != null) {
10099                        for (int i = 0; i < allUsers.length; i++) {
10100                            if (DEBUG_INSTALL) {
10101                                Slog.d(TAG, "    user " + allUsers[i]
10102                                        + " => " + perUserInstalled[i]);
10103                            }
10104                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10105                        }
10106                        // these install state changes will be persisted in the
10107                        // upcoming call to mSettings.writeLPr().
10108                    }
10109                }
10110            }
10111            res.name = pkgName;
10112            res.uid = newPackage.applicationInfo.uid;
10113            res.pkg = newPackage;
10114            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10115            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10116            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10117            //to update install status
10118            mSettings.writeLPr();
10119        }
10120    }
10121
10122    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10123        final int installFlags = args.installFlags;
10124        String installerPackageName = args.installerPackageName;
10125        File tmpPackageFile = new File(args.getCodePath());
10126        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10127        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10128        boolean replace = false;
10129        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10130        // Result object to be returned
10131        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10132
10133        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10134        // Retrieve PackageSettings and parse package
10135        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10136                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10137                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10138        PackageParser pp = new PackageParser();
10139        pp.setSeparateProcesses(mSeparateProcesses);
10140        pp.setDisplayMetrics(mMetrics);
10141
10142        final PackageParser.Package pkg;
10143        try {
10144            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10145        } catch (PackageParserException e) {
10146            res.setError("Failed parse during installPackageLI", e);
10147            return;
10148        }
10149
10150        // Mark that we have an install time CPU ABI override.
10151        pkg.cpuAbiOverride = args.abiOverride;
10152
10153        String pkgName = res.name = pkg.packageName;
10154        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10155            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10156                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10157                return;
10158            }
10159        }
10160
10161        try {
10162            pp.collectCertificates(pkg, parseFlags);
10163            pp.collectManifestDigest(pkg);
10164        } catch (PackageParserException e) {
10165            res.setError("Failed collect during installPackageLI", e);
10166            return;
10167        }
10168
10169        /* If the installer passed in a manifest digest, compare it now. */
10170        if (args.manifestDigest != null) {
10171            if (DEBUG_INSTALL) {
10172                final String parsedManifest = pkg.manifestDigest == null ? "null"
10173                        : pkg.manifestDigest.toString();
10174                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10175                        + parsedManifest);
10176            }
10177
10178            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10179                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10180                return;
10181            }
10182        } else if (DEBUG_INSTALL) {
10183            final String parsedManifest = pkg.manifestDigest == null
10184                    ? "null" : pkg.manifestDigest.toString();
10185            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10186        }
10187
10188        // Get rid of all references to package scan path via parser.
10189        pp = null;
10190        String oldCodePath = null;
10191        boolean systemApp = false;
10192        synchronized (mPackages) {
10193            // Check whether the newly-scanned package wants to define an already-defined perm
10194            int N = pkg.permissions.size();
10195            for (int i = N-1; i >= 0; i--) {
10196                PackageParser.Permission perm = pkg.permissions.get(i);
10197                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10198                if (bp != null) {
10199                    // If the defining package is signed with our cert, it's okay.  This
10200                    // also includes the "updating the same package" case, of course.
10201                    // "updating same package" could also involve key-rotation.
10202                    final boolean sigsOk;
10203                    if (!bp.sourcePackage.equals(pkg.packageName)
10204                            || !(bp.packageSetting instanceof PackageSetting)
10205                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10206                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10207                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10208                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10209                    } else {
10210                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10211                    }
10212                    if (!sigsOk) {
10213                        // If the owning package is the system itself, we log but allow
10214                        // install to proceed; we fail the install on all other permission
10215                        // redefinitions.
10216                        if (!bp.sourcePackage.equals("android")) {
10217                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10218                                    + pkg.packageName + " attempting to redeclare permission "
10219                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10220                            res.origPermission = perm.info.name;
10221                            res.origPackage = bp.sourcePackage;
10222                            return;
10223                        } else {
10224                            Slog.w(TAG, "Package " + pkg.packageName
10225                                    + " attempting to redeclare system permission "
10226                                    + perm.info.name + "; ignoring new declaration");
10227                            pkg.permissions.remove(i);
10228                        }
10229                    }
10230                }
10231            }
10232
10233            // Check if installing already existing package
10234            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10235                String oldName = mSettings.mRenamedPackages.get(pkgName);
10236                if (pkg.mOriginalPackages != null
10237                        && pkg.mOriginalPackages.contains(oldName)
10238                        && mPackages.containsKey(oldName)) {
10239                    // This package is derived from an original package,
10240                    // and this device has been updating from that original
10241                    // name.  We must continue using the original name, so
10242                    // rename the new package here.
10243                    pkg.setPackageName(oldName);
10244                    pkgName = pkg.packageName;
10245                    replace = true;
10246                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10247                            + oldName + " pkgName=" + pkgName);
10248                } else if (mPackages.containsKey(pkgName)) {
10249                    // This package, under its official name, already exists
10250                    // on the device; we should replace it.
10251                    replace = true;
10252                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10253                }
10254            }
10255            PackageSetting ps = mSettings.mPackages.get(pkgName);
10256            if (ps != null) {
10257                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10258                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10259                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10260                    systemApp = (ps.pkg.applicationInfo.flags &
10261                            ApplicationInfo.FLAG_SYSTEM) != 0;
10262                }
10263                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10264            }
10265        }
10266
10267        if (systemApp && onSd) {
10268            // Disable updates to system apps on sdcard
10269            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10270                    "Cannot install updates to system apps on sdcard");
10271            return;
10272        }
10273
10274        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10275            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10276            return;
10277        }
10278
10279        if (replace) {
10280            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10281                    installerPackageName, res);
10282        } else {
10283            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10284                    args.user, installerPackageName, res);
10285        }
10286        synchronized (mPackages) {
10287            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10288            if (ps != null) {
10289                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10290            }
10291        }
10292    }
10293
10294    private static boolean isForwardLocked(PackageParser.Package pkg) {
10295        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10296    }
10297
10298    private static boolean isForwardLocked(ApplicationInfo info) {
10299        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10300    }
10301
10302    private boolean isForwardLocked(PackageSetting ps) {
10303        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10304    }
10305
10306    private static boolean isMultiArch(PackageSetting ps) {
10307        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10308    }
10309
10310    private static boolean isMultiArch(ApplicationInfo info) {
10311        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10312    }
10313
10314    private static boolean isExternal(PackageParser.Package pkg) {
10315        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10316    }
10317
10318    private static boolean isExternal(PackageSetting ps) {
10319        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10320    }
10321
10322    private static boolean isExternal(ApplicationInfo info) {
10323        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10324    }
10325
10326    private static boolean isSystemApp(PackageParser.Package pkg) {
10327        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10328    }
10329
10330    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10331        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10332    }
10333
10334    private static boolean isSystemApp(ApplicationInfo info) {
10335        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10336    }
10337
10338    private static boolean isSystemApp(PackageSetting ps) {
10339        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10340    }
10341
10342    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10343        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10344    }
10345
10346    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10347        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10348    }
10349
10350    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10351        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10352    }
10353
10354    private int packageFlagsToInstallFlags(PackageSetting ps) {
10355        int installFlags = 0;
10356        if (isExternal(ps)) {
10357            installFlags |= PackageManager.INSTALL_EXTERNAL;
10358        }
10359        if (isForwardLocked(ps)) {
10360            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10361        }
10362        return installFlags;
10363    }
10364
10365    private void deleteTempPackageFiles() {
10366        final FilenameFilter filter = new FilenameFilter() {
10367            public boolean accept(File dir, String name) {
10368                return name.startsWith("vmdl") && name.endsWith(".tmp");
10369            }
10370        };
10371        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10372            file.delete();
10373        }
10374    }
10375
10376    @Override
10377    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10378            int flags) {
10379        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10380                flags);
10381    }
10382
10383    @Override
10384    public void deletePackage(final String packageName,
10385            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10386        mContext.enforceCallingOrSelfPermission(
10387                android.Manifest.permission.DELETE_PACKAGES, null);
10388        final int uid = Binder.getCallingUid();
10389        if (UserHandle.getUserId(uid) != userId) {
10390            mContext.enforceCallingPermission(
10391                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10392                    "deletePackage for user " + userId);
10393        }
10394        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10395            try {
10396                observer.onPackageDeleted(packageName,
10397                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10398            } catch (RemoteException re) {
10399            }
10400            return;
10401        }
10402
10403        boolean uninstallBlocked = false;
10404        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10405            int[] users = sUserManager.getUserIds();
10406            for (int i = 0; i < users.length; ++i) {
10407                if (getBlockUninstallForUser(packageName, users[i])) {
10408                    uninstallBlocked = true;
10409                    break;
10410                }
10411            }
10412        } else {
10413            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10414        }
10415        if (uninstallBlocked) {
10416            try {
10417                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10418                        null);
10419            } catch (RemoteException re) {
10420            }
10421            return;
10422        }
10423
10424        if (DEBUG_REMOVE) {
10425            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10426        }
10427        // Queue up an async operation since the package deletion may take a little while.
10428        mHandler.post(new Runnable() {
10429            public void run() {
10430                mHandler.removeCallbacks(this);
10431                final int returnCode = deletePackageX(packageName, userId, flags);
10432                if (observer != null) {
10433                    try {
10434                        observer.onPackageDeleted(packageName, returnCode, null);
10435                    } catch (RemoteException e) {
10436                        Log.i(TAG, "Observer no longer exists.");
10437                    } //end catch
10438                } //end if
10439            } //end run
10440        });
10441    }
10442
10443    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10444        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10445                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10446        try {
10447            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10448                    || dpm.isDeviceOwner(packageName))) {
10449                return true;
10450            }
10451        } catch (RemoteException e) {
10452        }
10453        return false;
10454    }
10455
10456    /**
10457     *  This method is an internal method that could be get invoked either
10458     *  to delete an installed package or to clean up a failed installation.
10459     *  After deleting an installed package, a broadcast is sent to notify any
10460     *  listeners that the package has been installed. For cleaning up a failed
10461     *  installation, the broadcast is not necessary since the package's
10462     *  installation wouldn't have sent the initial broadcast either
10463     *  The key steps in deleting a package are
10464     *  deleting the package information in internal structures like mPackages,
10465     *  deleting the packages base directories through installd
10466     *  updating mSettings to reflect current status
10467     *  persisting settings for later use
10468     *  sending a broadcast if necessary
10469     */
10470    private int deletePackageX(String packageName, int userId, int flags) {
10471        final PackageRemovedInfo info = new PackageRemovedInfo();
10472        final boolean res;
10473
10474        if (isPackageDeviceAdmin(packageName, userId)) {
10475            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10476            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10477        }
10478
10479        boolean removedForAllUsers = false;
10480        boolean systemUpdate = false;
10481
10482        // for the uninstall-updates case and restricted profiles, remember the per-
10483        // userhandle installed state
10484        int[] allUsers;
10485        boolean[] perUserInstalled;
10486        synchronized (mPackages) {
10487            PackageSetting ps = mSettings.mPackages.get(packageName);
10488            allUsers = sUserManager.getUserIds();
10489            perUserInstalled = new boolean[allUsers.length];
10490            for (int i = 0; i < allUsers.length; i++) {
10491                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10492            }
10493        }
10494
10495        synchronized (mInstallLock) {
10496            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10497            res = deletePackageLI(packageName,
10498                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10499                            ? UserHandle.ALL : new UserHandle(userId),
10500                    true, allUsers, perUserInstalled,
10501                    flags | REMOVE_CHATTY, info, true);
10502            systemUpdate = info.isRemovedPackageSystemUpdate;
10503            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10504                removedForAllUsers = true;
10505            }
10506            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10507                    + " removedForAllUsers=" + removedForAllUsers);
10508        }
10509
10510        if (res) {
10511            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10512
10513            // If the removed package was a system update, the old system package
10514            // was re-enabled; we need to broadcast this information
10515            if (systemUpdate) {
10516                Bundle extras = new Bundle(1);
10517                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10518                        ? info.removedAppId : info.uid);
10519                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10520
10521                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10522                        extras, null, null, null);
10523                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10524                        extras, null, null, null);
10525                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10526                        null, packageName, null, null);
10527            }
10528        }
10529        // Force a gc here.
10530        Runtime.getRuntime().gc();
10531        // Delete the resources here after sending the broadcast to let
10532        // other processes clean up before deleting resources.
10533        if (info.args != null) {
10534            synchronized (mInstallLock) {
10535                info.args.doPostDeleteLI(true);
10536            }
10537        }
10538
10539        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10540    }
10541
10542    static class PackageRemovedInfo {
10543        String removedPackage;
10544        int uid = -1;
10545        int removedAppId = -1;
10546        int[] removedUsers = null;
10547        boolean isRemovedPackageSystemUpdate = false;
10548        // Clean up resources deleted packages.
10549        InstallArgs args = null;
10550
10551        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10552            Bundle extras = new Bundle(1);
10553            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10554            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10555            if (replacing) {
10556                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10557            }
10558            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10559            if (removedPackage != null) {
10560                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10561                        extras, null, null, removedUsers);
10562                if (fullRemove && !replacing) {
10563                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10564                            extras, null, null, removedUsers);
10565                }
10566            }
10567            if (removedAppId >= 0) {
10568                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10569                        removedUsers);
10570            }
10571        }
10572    }
10573
10574    /*
10575     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10576     * flag is not set, the data directory is removed as well.
10577     * make sure this flag is set for partially installed apps. If not its meaningless to
10578     * delete a partially installed application.
10579     */
10580    private void removePackageDataLI(PackageSetting ps,
10581            int[] allUserHandles, boolean[] perUserInstalled,
10582            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10583        String packageName = ps.name;
10584        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10585        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10586        // Retrieve object to delete permissions for shared user later on
10587        final PackageSetting deletedPs;
10588        // reader
10589        synchronized (mPackages) {
10590            deletedPs = mSettings.mPackages.get(packageName);
10591            if (outInfo != null) {
10592                outInfo.removedPackage = packageName;
10593                outInfo.removedUsers = deletedPs != null
10594                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10595                        : null;
10596            }
10597        }
10598        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10599            removeDataDirsLI(packageName);
10600            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10601        }
10602        // writer
10603        synchronized (mPackages) {
10604            if (deletedPs != null) {
10605                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10606                    if (outInfo != null) {
10607                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10608                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10609                    }
10610                    if (deletedPs != null) {
10611                        updatePermissionsLPw(deletedPs.name, null, 0);
10612                        if (deletedPs.sharedUser != null) {
10613                            // remove permissions associated with package
10614                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10615                        }
10616                    }
10617                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10618                }
10619                // make sure to preserve per-user disabled state if this removal was just
10620                // a downgrade of a system app to the factory package
10621                if (allUserHandles != null && perUserInstalled != null) {
10622                    if (DEBUG_REMOVE) {
10623                        Slog.d(TAG, "Propagating install state across downgrade");
10624                    }
10625                    for (int i = 0; i < allUserHandles.length; i++) {
10626                        if (DEBUG_REMOVE) {
10627                            Slog.d(TAG, "    user " + allUserHandles[i]
10628                                    + " => " + perUserInstalled[i]);
10629                        }
10630                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10631                    }
10632                }
10633            }
10634            // can downgrade to reader
10635            if (writeSettings) {
10636                // Save settings now
10637                mSettings.writeLPr();
10638            }
10639        }
10640        if (outInfo != null) {
10641            // A user ID was deleted here. Go through all users and remove it
10642            // from KeyStore.
10643            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10644        }
10645    }
10646
10647    static boolean locationIsPrivileged(File path) {
10648        try {
10649            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10650                    .getCanonicalPath();
10651            return path.getCanonicalPath().startsWith(privilegedAppDir);
10652        } catch (IOException e) {
10653            Slog.e(TAG, "Unable to access code path " + path);
10654        }
10655        return false;
10656    }
10657
10658    /*
10659     * Tries to delete system package.
10660     */
10661    private boolean deleteSystemPackageLI(PackageSetting newPs,
10662            int[] allUserHandles, boolean[] perUserInstalled,
10663            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10664        final boolean applyUserRestrictions
10665                = (allUserHandles != null) && (perUserInstalled != null);
10666        PackageSetting disabledPs = null;
10667        // Confirm if the system package has been updated
10668        // An updated system app can be deleted. This will also have to restore
10669        // the system pkg from system partition
10670        // reader
10671        synchronized (mPackages) {
10672            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10673        }
10674        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10675                + " disabledPs=" + disabledPs);
10676        if (disabledPs == null) {
10677            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10678            return false;
10679        } else if (DEBUG_REMOVE) {
10680            Slog.d(TAG, "Deleting system pkg from data partition");
10681        }
10682        if (DEBUG_REMOVE) {
10683            if (applyUserRestrictions) {
10684                Slog.d(TAG, "Remembering install states:");
10685                for (int i = 0; i < allUserHandles.length; i++) {
10686                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10687                }
10688            }
10689        }
10690        // Delete the updated package
10691        outInfo.isRemovedPackageSystemUpdate = true;
10692        if (disabledPs.versionCode < newPs.versionCode) {
10693            // Delete data for downgrades
10694            flags &= ~PackageManager.DELETE_KEEP_DATA;
10695        } else {
10696            // Preserve data by setting flag
10697            flags |= PackageManager.DELETE_KEEP_DATA;
10698        }
10699        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10700                allUserHandles, perUserInstalled, outInfo, writeSettings);
10701        if (!ret) {
10702            return false;
10703        }
10704        // writer
10705        synchronized (mPackages) {
10706            // Reinstate the old system package
10707            mSettings.enableSystemPackageLPw(newPs.name);
10708            // Remove any native libraries from the upgraded package.
10709            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10710        }
10711        // Install the system package
10712        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10713        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10714        if (locationIsPrivileged(disabledPs.codePath)) {
10715            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10716        }
10717
10718        final PackageParser.Package newPkg;
10719        try {
10720            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10721        } catch (PackageManagerException e) {
10722            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10723            return false;
10724        }
10725
10726        // writer
10727        synchronized (mPackages) {
10728            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10729            updatePermissionsLPw(newPkg.packageName, newPkg,
10730                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10731            if (applyUserRestrictions) {
10732                if (DEBUG_REMOVE) {
10733                    Slog.d(TAG, "Propagating install state across reinstall");
10734                }
10735                for (int i = 0; i < allUserHandles.length; i++) {
10736                    if (DEBUG_REMOVE) {
10737                        Slog.d(TAG, "    user " + allUserHandles[i]
10738                                + " => " + perUserInstalled[i]);
10739                    }
10740                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10741                }
10742                // Regardless of writeSettings we need to ensure that this restriction
10743                // state propagation is persisted
10744                mSettings.writeAllUsersPackageRestrictionsLPr();
10745            }
10746            // can downgrade to reader here
10747            if (writeSettings) {
10748                mSettings.writeLPr();
10749            }
10750        }
10751        return true;
10752    }
10753
10754    private boolean deleteInstalledPackageLI(PackageSetting ps,
10755            boolean deleteCodeAndResources, int flags,
10756            int[] allUserHandles, boolean[] perUserInstalled,
10757            PackageRemovedInfo outInfo, boolean writeSettings) {
10758        if (outInfo != null) {
10759            outInfo.uid = ps.appId;
10760        }
10761
10762        // Delete package data from internal structures and also remove data if flag is set
10763        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10764
10765        // Delete application code and resources
10766        if (deleteCodeAndResources && (outInfo != null)) {
10767            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10768                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10769                    getAppDexInstructionSets(ps));
10770            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10771        }
10772        return true;
10773    }
10774
10775    @Override
10776    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10777            int userId) {
10778        mContext.enforceCallingOrSelfPermission(
10779                android.Manifest.permission.DELETE_PACKAGES, null);
10780        synchronized (mPackages) {
10781            PackageSetting ps = mSettings.mPackages.get(packageName);
10782            if (ps == null) {
10783                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10784                return false;
10785            }
10786            if (!ps.getInstalled(userId)) {
10787                // Can't block uninstall for an app that is not installed or enabled.
10788                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10789                return false;
10790            }
10791            ps.setBlockUninstall(blockUninstall, userId);
10792            mSettings.writePackageRestrictionsLPr(userId);
10793        }
10794        return true;
10795    }
10796
10797    @Override
10798    public boolean getBlockUninstallForUser(String packageName, int userId) {
10799        synchronized (mPackages) {
10800            PackageSetting ps = mSettings.mPackages.get(packageName);
10801            if (ps == null) {
10802                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10803                return false;
10804            }
10805            return ps.getBlockUninstall(userId);
10806        }
10807    }
10808
10809    /*
10810     * This method handles package deletion in general
10811     */
10812    private boolean deletePackageLI(String packageName, UserHandle user,
10813            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10814            int flags, PackageRemovedInfo outInfo,
10815            boolean writeSettings) {
10816        if (packageName == null) {
10817            Slog.w(TAG, "Attempt to delete null packageName.");
10818            return false;
10819        }
10820        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10821        PackageSetting ps;
10822        boolean dataOnly = false;
10823        int removeUser = -1;
10824        int appId = -1;
10825        synchronized (mPackages) {
10826            ps = mSettings.mPackages.get(packageName);
10827            if (ps == null) {
10828                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10829                return false;
10830            }
10831            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10832                    && user.getIdentifier() != UserHandle.USER_ALL) {
10833                // The caller is asking that the package only be deleted for a single
10834                // user.  To do this, we just mark its uninstalled state and delete
10835                // its data.  If this is a system app, we only allow this to happen if
10836                // they have set the special DELETE_SYSTEM_APP which requests different
10837                // semantics than normal for uninstalling system apps.
10838                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10839                ps.setUserState(user.getIdentifier(),
10840                        COMPONENT_ENABLED_STATE_DEFAULT,
10841                        false, //installed
10842                        true,  //stopped
10843                        true,  //notLaunched
10844                        false, //hidden
10845                        null, null, null,
10846                        false // blockUninstall
10847                        );
10848                if (!isSystemApp(ps)) {
10849                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10850                        // Other user still have this package installed, so all
10851                        // we need to do is clear this user's data and save that
10852                        // it is uninstalled.
10853                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10854                        removeUser = user.getIdentifier();
10855                        appId = ps.appId;
10856                        mSettings.writePackageRestrictionsLPr(removeUser);
10857                    } else {
10858                        // We need to set it back to 'installed' so the uninstall
10859                        // broadcasts will be sent correctly.
10860                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10861                        ps.setInstalled(true, user.getIdentifier());
10862                    }
10863                } else {
10864                    // This is a system app, so we assume that the
10865                    // other users still have this package installed, so all
10866                    // we need to do is clear this user's data and save that
10867                    // it is uninstalled.
10868                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10869                    removeUser = user.getIdentifier();
10870                    appId = ps.appId;
10871                    mSettings.writePackageRestrictionsLPr(removeUser);
10872                }
10873            }
10874        }
10875
10876        if (removeUser >= 0) {
10877            // From above, we determined that we are deleting this only
10878            // for a single user.  Continue the work here.
10879            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10880            if (outInfo != null) {
10881                outInfo.removedPackage = packageName;
10882                outInfo.removedAppId = appId;
10883                outInfo.removedUsers = new int[] {removeUser};
10884            }
10885            mInstaller.clearUserData(packageName, removeUser);
10886            removeKeystoreDataIfNeeded(removeUser, appId);
10887            schedulePackageCleaning(packageName, removeUser, false);
10888            return true;
10889        }
10890
10891        if (dataOnly) {
10892            // Delete application data first
10893            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10894            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10895            return true;
10896        }
10897
10898        boolean ret = false;
10899        if (isSystemApp(ps)) {
10900            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10901            // When an updated system application is deleted we delete the existing resources as well and
10902            // fall back to existing code in system partition
10903            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10904                    flags, outInfo, writeSettings);
10905        } else {
10906            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10907            // Kill application pre-emptively especially for apps on sd.
10908            killApplication(packageName, ps.appId, "uninstall pkg");
10909            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10910                    allUserHandles, perUserInstalled,
10911                    outInfo, writeSettings);
10912        }
10913
10914        return ret;
10915    }
10916
10917    private final class ClearStorageConnection implements ServiceConnection {
10918        IMediaContainerService mContainerService;
10919
10920        @Override
10921        public void onServiceConnected(ComponentName name, IBinder service) {
10922            synchronized (this) {
10923                mContainerService = IMediaContainerService.Stub.asInterface(service);
10924                notifyAll();
10925            }
10926        }
10927
10928        @Override
10929        public void onServiceDisconnected(ComponentName name) {
10930        }
10931    }
10932
10933    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10934        final boolean mounted;
10935        if (Environment.isExternalStorageEmulated()) {
10936            mounted = true;
10937        } else {
10938            final String status = Environment.getExternalStorageState();
10939
10940            mounted = status.equals(Environment.MEDIA_MOUNTED)
10941                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10942        }
10943
10944        if (!mounted) {
10945            return;
10946        }
10947
10948        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10949        int[] users;
10950        if (userId == UserHandle.USER_ALL) {
10951            users = sUserManager.getUserIds();
10952        } else {
10953            users = new int[] { userId };
10954        }
10955        final ClearStorageConnection conn = new ClearStorageConnection();
10956        if (mContext.bindServiceAsUser(
10957                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10958            try {
10959                for (int curUser : users) {
10960                    long timeout = SystemClock.uptimeMillis() + 5000;
10961                    synchronized (conn) {
10962                        long now = SystemClock.uptimeMillis();
10963                        while (conn.mContainerService == null && now < timeout) {
10964                            try {
10965                                conn.wait(timeout - now);
10966                            } catch (InterruptedException e) {
10967                            }
10968                        }
10969                    }
10970                    if (conn.mContainerService == null) {
10971                        return;
10972                    }
10973
10974                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10975                    clearDirectory(conn.mContainerService,
10976                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10977                    if (allData) {
10978                        clearDirectory(conn.mContainerService,
10979                                userEnv.buildExternalStorageAppDataDirs(packageName));
10980                        clearDirectory(conn.mContainerService,
10981                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10982                    }
10983                }
10984            } finally {
10985                mContext.unbindService(conn);
10986            }
10987        }
10988    }
10989
10990    @Override
10991    public void clearApplicationUserData(final String packageName,
10992            final IPackageDataObserver observer, final int userId) {
10993        mContext.enforceCallingOrSelfPermission(
10994                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10995        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
10996        // Queue up an async operation since the package deletion may take a little while.
10997        mHandler.post(new Runnable() {
10998            public void run() {
10999                mHandler.removeCallbacks(this);
11000                final boolean succeeded;
11001                synchronized (mInstallLock) {
11002                    succeeded = clearApplicationUserDataLI(packageName, userId);
11003                }
11004                clearExternalStorageDataSync(packageName, userId, true);
11005                if (succeeded) {
11006                    // invoke DeviceStorageMonitor's update method to clear any notifications
11007                    DeviceStorageMonitorInternal
11008                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11009                    if (dsm != null) {
11010                        dsm.checkMemory();
11011                    }
11012                }
11013                if(observer != null) {
11014                    try {
11015                        observer.onRemoveCompleted(packageName, succeeded);
11016                    } catch (RemoteException e) {
11017                        Log.i(TAG, "Observer no longer exists.");
11018                    }
11019                } //end if observer
11020            } //end run
11021        });
11022    }
11023
11024    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11025        if (packageName == null) {
11026            Slog.w(TAG, "Attempt to delete null packageName.");
11027            return false;
11028        }
11029
11030        // Try finding details about the requested package
11031        PackageParser.Package pkg;
11032        synchronized (mPackages) {
11033            pkg = mPackages.get(packageName);
11034            if (pkg == null) {
11035                final PackageSetting ps = mSettings.mPackages.get(packageName);
11036                if (ps != null) {
11037                    pkg = ps.pkg;
11038                }
11039            }
11040        }
11041
11042        if (pkg == null) {
11043            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11044        }
11045
11046        // Always delete data directories for package, even if we found no other
11047        // record of app. This helps users recover from UID mismatches without
11048        // resorting to a full data wipe.
11049        int retCode = mInstaller.clearUserData(packageName, userId);
11050        if (retCode < 0) {
11051            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11052            return false;
11053        }
11054
11055        if (pkg == null) {
11056            return false;
11057        }
11058
11059        if (pkg != null && pkg.applicationInfo != null) {
11060            final int appId = pkg.applicationInfo.uid;
11061            removeKeystoreDataIfNeeded(userId, appId);
11062        }
11063
11064        // Create a native library symlink only if we have native libraries
11065        // and if the native libraries are 32 bit libraries. We do not provide
11066        // this symlink for 64 bit libraries.
11067        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11068                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11069            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11070            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11071                Slog.w(TAG, "Failed linking native library dir");
11072                return false;
11073            }
11074        }
11075
11076        return true;
11077    }
11078
11079    /**
11080     * Remove entries from the keystore daemon. Will only remove it if the
11081     * {@code appId} is valid.
11082     */
11083    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11084        if (appId < 0) {
11085            return;
11086        }
11087
11088        final KeyStore keyStore = KeyStore.getInstance();
11089        if (keyStore != null) {
11090            if (userId == UserHandle.USER_ALL) {
11091                for (final int individual : sUserManager.getUserIds()) {
11092                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11093                }
11094            } else {
11095                keyStore.clearUid(UserHandle.getUid(userId, appId));
11096            }
11097        } else {
11098            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11099        }
11100    }
11101
11102    @Override
11103    public void deleteApplicationCacheFiles(final String packageName,
11104            final IPackageDataObserver observer) {
11105        mContext.enforceCallingOrSelfPermission(
11106                android.Manifest.permission.DELETE_CACHE_FILES, null);
11107        // Queue up an async operation since the package deletion may take a little while.
11108        final int userId = UserHandle.getCallingUserId();
11109        mHandler.post(new Runnable() {
11110            public void run() {
11111                mHandler.removeCallbacks(this);
11112                final boolean succeded;
11113                synchronized (mInstallLock) {
11114                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11115                }
11116                clearExternalStorageDataSync(packageName, userId, false);
11117                if(observer != null) {
11118                    try {
11119                        observer.onRemoveCompleted(packageName, succeded);
11120                    } catch (RemoteException e) {
11121                        Log.i(TAG, "Observer no longer exists.");
11122                    }
11123                } //end if observer
11124            } //end run
11125        });
11126    }
11127
11128    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11129        if (packageName == null) {
11130            Slog.w(TAG, "Attempt to delete null packageName.");
11131            return false;
11132        }
11133        PackageParser.Package p;
11134        synchronized (mPackages) {
11135            p = mPackages.get(packageName);
11136        }
11137        if (p == null) {
11138            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11139            return false;
11140        }
11141        final ApplicationInfo applicationInfo = p.applicationInfo;
11142        if (applicationInfo == null) {
11143            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11144            return false;
11145        }
11146        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11147        if (retCode < 0) {
11148            Slog.w(TAG, "Couldn't remove cache files for package: "
11149                       + packageName + " u" + userId);
11150            return false;
11151        }
11152        return true;
11153    }
11154
11155    @Override
11156    public void getPackageSizeInfo(final String packageName, int userHandle,
11157            final IPackageStatsObserver observer) {
11158        mContext.enforceCallingOrSelfPermission(
11159                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11160        if (packageName == null) {
11161            throw new IllegalArgumentException("Attempt to get size of null packageName");
11162        }
11163
11164        PackageStats stats = new PackageStats(packageName, userHandle);
11165
11166        /*
11167         * Queue up an async operation since the package measurement may take a
11168         * little while.
11169         */
11170        Message msg = mHandler.obtainMessage(INIT_COPY);
11171        msg.obj = new MeasureParams(stats, observer);
11172        mHandler.sendMessage(msg);
11173    }
11174
11175    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11176            PackageStats pStats) {
11177        if (packageName == null) {
11178            Slog.w(TAG, "Attempt to get size of null packageName.");
11179            return false;
11180        }
11181        PackageParser.Package p;
11182        boolean dataOnly = false;
11183        String libDirRoot = null;
11184        String asecPath = null;
11185        PackageSetting ps = null;
11186        synchronized (mPackages) {
11187            p = mPackages.get(packageName);
11188            ps = mSettings.mPackages.get(packageName);
11189            if(p == null) {
11190                dataOnly = true;
11191                if((ps == null) || (ps.pkg == null)) {
11192                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11193                    return false;
11194                }
11195                p = ps.pkg;
11196            }
11197            if (ps != null) {
11198                libDirRoot = ps.legacyNativeLibraryPathString;
11199            }
11200            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11201                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11202                if (secureContainerId != null) {
11203                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11204                }
11205            }
11206        }
11207        String publicSrcDir = null;
11208        if(!dataOnly) {
11209            final ApplicationInfo applicationInfo = p.applicationInfo;
11210            if (applicationInfo == null) {
11211                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11212                return false;
11213            }
11214            if (isForwardLocked(p)) {
11215                publicSrcDir = applicationInfo.getBaseResourcePath();
11216            }
11217        }
11218        // TODO: extend to measure size of split APKs
11219        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11220        // not just the first level.
11221        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11222        // just the primary.
11223        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11224        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11225                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11226        if (res < 0) {
11227            return false;
11228        }
11229
11230        // Fix-up for forward-locked applications in ASEC containers.
11231        if (!isExternal(p)) {
11232            pStats.codeSize += pStats.externalCodeSize;
11233            pStats.externalCodeSize = 0L;
11234        }
11235
11236        return true;
11237    }
11238
11239
11240    @Override
11241    public void addPackageToPreferred(String packageName) {
11242        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11243    }
11244
11245    @Override
11246    public void removePackageFromPreferred(String packageName) {
11247        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11248    }
11249
11250    @Override
11251    public List<PackageInfo> getPreferredPackages(int flags) {
11252        return new ArrayList<PackageInfo>();
11253    }
11254
11255    private int getUidTargetSdkVersionLockedLPr(int uid) {
11256        Object obj = mSettings.getUserIdLPr(uid);
11257        if (obj instanceof SharedUserSetting) {
11258            final SharedUserSetting sus = (SharedUserSetting) obj;
11259            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11260            final Iterator<PackageSetting> it = sus.packages.iterator();
11261            while (it.hasNext()) {
11262                final PackageSetting ps = it.next();
11263                if (ps.pkg != null) {
11264                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11265                    if (v < vers) vers = v;
11266                }
11267            }
11268            return vers;
11269        } else if (obj instanceof PackageSetting) {
11270            final PackageSetting ps = (PackageSetting) obj;
11271            if (ps.pkg != null) {
11272                return ps.pkg.applicationInfo.targetSdkVersion;
11273            }
11274        }
11275        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11276    }
11277
11278    @Override
11279    public void addPreferredActivity(IntentFilter filter, int match,
11280            ComponentName[] set, ComponentName activity, int userId) {
11281        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11282                "Adding preferred");
11283    }
11284
11285    private void addPreferredActivityInternal(IntentFilter filter, int match,
11286            ComponentName[] set, ComponentName activity, boolean always, int userId,
11287            String opname) {
11288        // writer
11289        int callingUid = Binder.getCallingUid();
11290        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11291        if (filter.countActions() == 0) {
11292            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11293            return;
11294        }
11295        synchronized (mPackages) {
11296            if (mContext.checkCallingOrSelfPermission(
11297                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11298                    != PackageManager.PERMISSION_GRANTED) {
11299                if (getUidTargetSdkVersionLockedLPr(callingUid)
11300                        < Build.VERSION_CODES.FROYO) {
11301                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11302                            + callingUid);
11303                    return;
11304                }
11305                mContext.enforceCallingOrSelfPermission(
11306                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11307            }
11308
11309            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11310            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11311                    + userId + ":");
11312            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11313            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11314            mSettings.writePackageRestrictionsLPr(userId);
11315        }
11316    }
11317
11318    @Override
11319    public void replacePreferredActivity(IntentFilter filter, int match,
11320            ComponentName[] set, ComponentName activity, int userId) {
11321        if (filter.countActions() != 1) {
11322            throw new IllegalArgumentException(
11323                    "replacePreferredActivity expects filter to have only 1 action.");
11324        }
11325        if (filter.countDataAuthorities() != 0
11326                || filter.countDataPaths() != 0
11327                || filter.countDataSchemes() > 1
11328                || filter.countDataTypes() != 0) {
11329            throw new IllegalArgumentException(
11330                    "replacePreferredActivity expects filter to have no data authorities, " +
11331                    "paths, or types; and at most one scheme.");
11332        }
11333
11334        final int callingUid = Binder.getCallingUid();
11335        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11336        synchronized (mPackages) {
11337            if (mContext.checkCallingOrSelfPermission(
11338                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11339                    != PackageManager.PERMISSION_GRANTED) {
11340                if (getUidTargetSdkVersionLockedLPr(callingUid)
11341                        < Build.VERSION_CODES.FROYO) {
11342                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11343                            + Binder.getCallingUid());
11344                    return;
11345                }
11346                mContext.enforceCallingOrSelfPermission(
11347                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11348            }
11349
11350            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11351            if (pir != null) {
11352                // Get all of the existing entries that exactly match this filter.
11353                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11354                if (existing != null && existing.size() == 1) {
11355                    PreferredActivity cur = existing.get(0);
11356                    if (DEBUG_PREFERRED) {
11357                        Slog.i(TAG, "Checking replace of preferred:");
11358                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11359                        if (!cur.mPref.mAlways) {
11360                            Slog.i(TAG, "  -- CUR; not mAlways!");
11361                        } else {
11362                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11363                            Slog.i(TAG, "  -- CUR: mSet="
11364                                    + Arrays.toString(cur.mPref.mSetComponents));
11365                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11366                            Slog.i(TAG, "  -- NEW: mMatch="
11367                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11368                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11369                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11370                        }
11371                    }
11372                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11373                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11374                            && cur.mPref.sameSet(set)) {
11375                        // Setting the preferred activity to what it happens to be already
11376                        if (DEBUG_PREFERRED) {
11377                            Slog.i(TAG, "Replacing with same preferred activity "
11378                                    + cur.mPref.mShortComponent + " for user "
11379                                    + userId + ":");
11380                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11381                        }
11382                        return;
11383                    }
11384                }
11385
11386                if (existing != null) {
11387                    if (DEBUG_PREFERRED) {
11388                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11389                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11390                    }
11391                    for (int i = 0; i < existing.size(); i++) {
11392                        PreferredActivity pa = existing.get(i);
11393                        if (DEBUG_PREFERRED) {
11394                            Slog.i(TAG, "Removing existing preferred activity "
11395                                    + pa.mPref.mComponent + ":");
11396                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11397                        }
11398                        pir.removeFilter(pa);
11399                    }
11400                }
11401            }
11402            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11403                    "Replacing preferred");
11404        }
11405    }
11406
11407    @Override
11408    public void clearPackagePreferredActivities(String packageName) {
11409        final int uid = Binder.getCallingUid();
11410        // writer
11411        synchronized (mPackages) {
11412            PackageParser.Package pkg = mPackages.get(packageName);
11413            if (pkg == null || pkg.applicationInfo.uid != uid) {
11414                if (mContext.checkCallingOrSelfPermission(
11415                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11416                        != PackageManager.PERMISSION_GRANTED) {
11417                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11418                            < Build.VERSION_CODES.FROYO) {
11419                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11420                                + Binder.getCallingUid());
11421                        return;
11422                    }
11423                    mContext.enforceCallingOrSelfPermission(
11424                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11425                }
11426            }
11427
11428            int user = UserHandle.getCallingUserId();
11429            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11430                mSettings.writePackageRestrictionsLPr(user);
11431                scheduleWriteSettingsLocked();
11432            }
11433        }
11434    }
11435
11436    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11437    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11438        ArrayList<PreferredActivity> removed = null;
11439        boolean changed = false;
11440        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11441            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11442            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11443            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11444                continue;
11445            }
11446            Iterator<PreferredActivity> it = pir.filterIterator();
11447            while (it.hasNext()) {
11448                PreferredActivity pa = it.next();
11449                // Mark entry for removal only if it matches the package name
11450                // and the entry is of type "always".
11451                if (packageName == null ||
11452                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11453                                && pa.mPref.mAlways)) {
11454                    if (removed == null) {
11455                        removed = new ArrayList<PreferredActivity>();
11456                    }
11457                    removed.add(pa);
11458                }
11459            }
11460            if (removed != null) {
11461                for (int j=0; j<removed.size(); j++) {
11462                    PreferredActivity pa = removed.get(j);
11463                    pir.removeFilter(pa);
11464                }
11465                changed = true;
11466            }
11467        }
11468        return changed;
11469    }
11470
11471    @Override
11472    public void resetPreferredActivities(int userId) {
11473        /* TODO: Actually use userId. Why is it being passed in? */
11474        mContext.enforceCallingOrSelfPermission(
11475                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11476        // writer
11477        synchronized (mPackages) {
11478            int user = UserHandle.getCallingUserId();
11479            clearPackagePreferredActivitiesLPw(null, user);
11480            mSettings.readDefaultPreferredAppsLPw(this, user);
11481            mSettings.writePackageRestrictionsLPr(user);
11482            scheduleWriteSettingsLocked();
11483        }
11484    }
11485
11486    @Override
11487    public int getPreferredActivities(List<IntentFilter> outFilters,
11488            List<ComponentName> outActivities, String packageName) {
11489
11490        int num = 0;
11491        final int userId = UserHandle.getCallingUserId();
11492        // reader
11493        synchronized (mPackages) {
11494            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11495            if (pir != null) {
11496                final Iterator<PreferredActivity> it = pir.filterIterator();
11497                while (it.hasNext()) {
11498                    final PreferredActivity pa = it.next();
11499                    if (packageName == null
11500                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11501                                    && pa.mPref.mAlways)) {
11502                        if (outFilters != null) {
11503                            outFilters.add(new IntentFilter(pa));
11504                        }
11505                        if (outActivities != null) {
11506                            outActivities.add(pa.mPref.mComponent);
11507                        }
11508                    }
11509                }
11510            }
11511        }
11512
11513        return num;
11514    }
11515
11516    @Override
11517    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11518            int userId) {
11519        int callingUid = Binder.getCallingUid();
11520        if (callingUid != Process.SYSTEM_UID) {
11521            throw new SecurityException(
11522                    "addPersistentPreferredActivity can only be run by the system");
11523        }
11524        if (filter.countActions() == 0) {
11525            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11526            return;
11527        }
11528        synchronized (mPackages) {
11529            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11530                    " :");
11531            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11532            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11533                    new PersistentPreferredActivity(filter, activity));
11534            mSettings.writePackageRestrictionsLPr(userId);
11535        }
11536    }
11537
11538    @Override
11539    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11540        int callingUid = Binder.getCallingUid();
11541        if (callingUid != Process.SYSTEM_UID) {
11542            throw new SecurityException(
11543                    "clearPackagePersistentPreferredActivities can only be run by the system");
11544        }
11545        ArrayList<PersistentPreferredActivity> removed = null;
11546        boolean changed = false;
11547        synchronized (mPackages) {
11548            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11549                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11550                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11551                        .valueAt(i);
11552                if (userId != thisUserId) {
11553                    continue;
11554                }
11555                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11556                while (it.hasNext()) {
11557                    PersistentPreferredActivity ppa = it.next();
11558                    // Mark entry for removal only if it matches the package name.
11559                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11560                        if (removed == null) {
11561                            removed = new ArrayList<PersistentPreferredActivity>();
11562                        }
11563                        removed.add(ppa);
11564                    }
11565                }
11566                if (removed != null) {
11567                    for (int j=0; j<removed.size(); j++) {
11568                        PersistentPreferredActivity ppa = removed.get(j);
11569                        ppir.removeFilter(ppa);
11570                    }
11571                    changed = true;
11572                }
11573            }
11574
11575            if (changed) {
11576                mSettings.writePackageRestrictionsLPr(userId);
11577            }
11578        }
11579    }
11580
11581    @Override
11582    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11583            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11584        mContext.enforceCallingOrSelfPermission(
11585                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11586        int callingUid = Binder.getCallingUid();
11587        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11588        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11589        if (intentFilter.countActions() == 0) {
11590            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11591            return;
11592        }
11593        synchronized (mPackages) {
11594            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11595                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11596            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11597            mSettings.writePackageRestrictionsLPr(sourceUserId);
11598        }
11599    }
11600
11601    @Override
11602    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11603            int ownerUserId) {
11604        mContext.enforceCallingOrSelfPermission(
11605                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11606        int callingUid = Binder.getCallingUid();
11607        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11608        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11609        int callingUserId = UserHandle.getUserId(callingUid);
11610        synchronized (mPackages) {
11611            CrossProfileIntentResolver resolver =
11612                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11613            HashSet<CrossProfileIntentFilter> set =
11614                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11615            for (CrossProfileIntentFilter filter : set) {
11616                if (filter.getOwnerPackage().equals(ownerPackage)
11617                        && filter.getOwnerUserId() == callingUserId) {
11618                    resolver.removeFilter(filter);
11619                }
11620            }
11621            mSettings.writePackageRestrictionsLPr(sourceUserId);
11622        }
11623    }
11624
11625    // Enforcing that callingUid is owning pkg on userId
11626    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11627        // The system owns everything.
11628        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11629            return;
11630        }
11631        int callingUserId = UserHandle.getUserId(callingUid);
11632        if (callingUserId != userId) {
11633            throw new SecurityException("calling uid " + callingUid
11634                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11635                    + callingUserId);
11636        }
11637        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11638        if (pi == null) {
11639            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11640                    + callingUserId);
11641        }
11642        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11643            throw new SecurityException("Calling uid " + callingUid
11644                    + " does not own package " + pkg);
11645        }
11646    }
11647
11648    @Override
11649    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11650        Intent intent = new Intent(Intent.ACTION_MAIN);
11651        intent.addCategory(Intent.CATEGORY_HOME);
11652
11653        final int callingUserId = UserHandle.getCallingUserId();
11654        List<ResolveInfo> list = queryIntentActivities(intent, null,
11655                PackageManager.GET_META_DATA, callingUserId);
11656        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11657                true, false, false, callingUserId);
11658
11659        allHomeCandidates.clear();
11660        if (list != null) {
11661            for (ResolveInfo ri : list) {
11662                allHomeCandidates.add(ri);
11663            }
11664        }
11665        return (preferred == null || preferred.activityInfo == null)
11666                ? null
11667                : new ComponentName(preferred.activityInfo.packageName,
11668                        preferred.activityInfo.name);
11669    }
11670
11671    @Override
11672    public void setApplicationEnabledSetting(String appPackageName,
11673            int newState, int flags, int userId, String callingPackage) {
11674        if (!sUserManager.exists(userId)) return;
11675        if (callingPackage == null) {
11676            callingPackage = Integer.toString(Binder.getCallingUid());
11677        }
11678        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11679    }
11680
11681    @Override
11682    public void setComponentEnabledSetting(ComponentName componentName,
11683            int newState, int flags, int userId) {
11684        if (!sUserManager.exists(userId)) return;
11685        setEnabledSetting(componentName.getPackageName(),
11686                componentName.getClassName(), newState, flags, userId, null);
11687    }
11688
11689    private void setEnabledSetting(final String packageName, String className, int newState,
11690            final int flags, int userId, String callingPackage) {
11691        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11692              || newState == COMPONENT_ENABLED_STATE_ENABLED
11693              || newState == COMPONENT_ENABLED_STATE_DISABLED
11694              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11695              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11696            throw new IllegalArgumentException("Invalid new component state: "
11697                    + newState);
11698        }
11699        PackageSetting pkgSetting;
11700        final int uid = Binder.getCallingUid();
11701        final int permission = mContext.checkCallingOrSelfPermission(
11702                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11703        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11704        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11705        boolean sendNow = false;
11706        boolean isApp = (className == null);
11707        String componentName = isApp ? packageName : className;
11708        int packageUid = -1;
11709        ArrayList<String> components;
11710
11711        // writer
11712        synchronized (mPackages) {
11713            pkgSetting = mSettings.mPackages.get(packageName);
11714            if (pkgSetting == null) {
11715                if (className == null) {
11716                    throw new IllegalArgumentException(
11717                            "Unknown package: " + packageName);
11718                }
11719                throw new IllegalArgumentException(
11720                        "Unknown component: " + packageName
11721                        + "/" + className);
11722            }
11723            // Allow root and verify that userId is not being specified by a different user
11724            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11725                throw new SecurityException(
11726                        "Permission Denial: attempt to change component state from pid="
11727                        + Binder.getCallingPid()
11728                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11729            }
11730            if (className == null) {
11731                // We're dealing with an application/package level state change
11732                if (pkgSetting.getEnabled(userId) == newState) {
11733                    // Nothing to do
11734                    return;
11735                }
11736                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11737                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11738                    // Don't care about who enables an app.
11739                    callingPackage = null;
11740                }
11741                pkgSetting.setEnabled(newState, userId, callingPackage);
11742                // pkgSetting.pkg.mSetEnabled = newState;
11743            } else {
11744                // We're dealing with a component level state change
11745                // First, verify that this is a valid class name.
11746                PackageParser.Package pkg = pkgSetting.pkg;
11747                if (pkg == null || !pkg.hasComponentClassName(className)) {
11748                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11749                        throw new IllegalArgumentException("Component class " + className
11750                                + " does not exist in " + packageName);
11751                    } else {
11752                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11753                                + className + " does not exist in " + packageName);
11754                    }
11755                }
11756                switch (newState) {
11757                case COMPONENT_ENABLED_STATE_ENABLED:
11758                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11759                        return;
11760                    }
11761                    break;
11762                case COMPONENT_ENABLED_STATE_DISABLED:
11763                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11764                        return;
11765                    }
11766                    break;
11767                case COMPONENT_ENABLED_STATE_DEFAULT:
11768                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11769                        return;
11770                    }
11771                    break;
11772                default:
11773                    Slog.e(TAG, "Invalid new component state: " + newState);
11774                    return;
11775                }
11776            }
11777            mSettings.writePackageRestrictionsLPr(userId);
11778            components = mPendingBroadcasts.get(userId, packageName);
11779            final boolean newPackage = components == null;
11780            if (newPackage) {
11781                components = new ArrayList<String>();
11782            }
11783            if (!components.contains(componentName)) {
11784                components.add(componentName);
11785            }
11786            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11787                sendNow = true;
11788                // Purge entry from pending broadcast list if another one exists already
11789                // since we are sending one right away.
11790                mPendingBroadcasts.remove(userId, packageName);
11791            } else {
11792                if (newPackage) {
11793                    mPendingBroadcasts.put(userId, packageName, components);
11794                }
11795                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11796                    // Schedule a message
11797                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11798                }
11799            }
11800        }
11801
11802        long callingId = Binder.clearCallingIdentity();
11803        try {
11804            if (sendNow) {
11805                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11806                sendPackageChangedBroadcast(packageName,
11807                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11808            }
11809        } finally {
11810            Binder.restoreCallingIdentity(callingId);
11811        }
11812    }
11813
11814    private void sendPackageChangedBroadcast(String packageName,
11815            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11816        if (DEBUG_INSTALL)
11817            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11818                    + componentNames);
11819        Bundle extras = new Bundle(4);
11820        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11821        String nameList[] = new String[componentNames.size()];
11822        componentNames.toArray(nameList);
11823        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11824        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11825        extras.putInt(Intent.EXTRA_UID, packageUid);
11826        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11827                new int[] {UserHandle.getUserId(packageUid)});
11828    }
11829
11830    @Override
11831    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11832        if (!sUserManager.exists(userId)) return;
11833        final int uid = Binder.getCallingUid();
11834        final int permission = mContext.checkCallingOrSelfPermission(
11835                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11836        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11837        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11838        // writer
11839        synchronized (mPackages) {
11840            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11841                    uid, userId)) {
11842                scheduleWritePackageRestrictionsLocked(userId);
11843            }
11844        }
11845    }
11846
11847    @Override
11848    public String getInstallerPackageName(String packageName) {
11849        // reader
11850        synchronized (mPackages) {
11851            return mSettings.getInstallerPackageNameLPr(packageName);
11852        }
11853    }
11854
11855    @Override
11856    public int getApplicationEnabledSetting(String packageName, int userId) {
11857        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11858        int uid = Binder.getCallingUid();
11859        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11860        // reader
11861        synchronized (mPackages) {
11862            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11863        }
11864    }
11865
11866    @Override
11867    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11868        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11869        int uid = Binder.getCallingUid();
11870        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11871        // reader
11872        synchronized (mPackages) {
11873            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11874        }
11875    }
11876
11877    @Override
11878    public void enterSafeMode() {
11879        enforceSystemOrRoot("Only the system can request entering safe mode");
11880
11881        if (!mSystemReady) {
11882            mSafeMode = true;
11883        }
11884    }
11885
11886    @Override
11887    public void systemReady() {
11888        mSystemReady = true;
11889
11890        // Read the compatibilty setting when the system is ready.
11891        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11892                mContext.getContentResolver(),
11893                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11894        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11895        if (DEBUG_SETTINGS) {
11896            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11897        }
11898
11899        synchronized (mPackages) {
11900            // Verify that all of the preferred activity components actually
11901            // exist.  It is possible for applications to be updated and at
11902            // that point remove a previously declared activity component that
11903            // had been set as a preferred activity.  We try to clean this up
11904            // the next time we encounter that preferred activity, but it is
11905            // possible for the user flow to never be able to return to that
11906            // situation so here we do a sanity check to make sure we haven't
11907            // left any junk around.
11908            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11909            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11910                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11911                removed.clear();
11912                for (PreferredActivity pa : pir.filterSet()) {
11913                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11914                        removed.add(pa);
11915                    }
11916                }
11917                if (removed.size() > 0) {
11918                    for (int r=0; r<removed.size(); r++) {
11919                        PreferredActivity pa = removed.get(r);
11920                        Slog.w(TAG, "Removing dangling preferred activity: "
11921                                + pa.mPref.mComponent);
11922                        pir.removeFilter(pa);
11923                    }
11924                    mSettings.writePackageRestrictionsLPr(
11925                            mSettings.mPreferredActivities.keyAt(i));
11926                }
11927            }
11928        }
11929        sUserManager.systemReady();
11930
11931        // Kick off any messages waiting for system ready
11932        if (mPostSystemReadyMessages != null) {
11933            for (Message msg : mPostSystemReadyMessages) {
11934                msg.sendToTarget();
11935            }
11936            mPostSystemReadyMessages = null;
11937        }
11938    }
11939
11940    @Override
11941    public boolean isSafeMode() {
11942        return mSafeMode;
11943    }
11944
11945    @Override
11946    public boolean hasSystemUidErrors() {
11947        return mHasSystemUidErrors;
11948    }
11949
11950    static String arrayToString(int[] array) {
11951        StringBuffer buf = new StringBuffer(128);
11952        buf.append('[');
11953        if (array != null) {
11954            for (int i=0; i<array.length; i++) {
11955                if (i > 0) buf.append(", ");
11956                buf.append(array[i]);
11957            }
11958        }
11959        buf.append(']');
11960        return buf.toString();
11961    }
11962
11963    static class DumpState {
11964        public static final int DUMP_LIBS = 1 << 0;
11965        public static final int DUMP_FEATURES = 1 << 1;
11966        public static final int DUMP_RESOLVERS = 1 << 2;
11967        public static final int DUMP_PERMISSIONS = 1 << 3;
11968        public static final int DUMP_PACKAGES = 1 << 4;
11969        public static final int DUMP_SHARED_USERS = 1 << 5;
11970        public static final int DUMP_MESSAGES = 1 << 6;
11971        public static final int DUMP_PROVIDERS = 1 << 7;
11972        public static final int DUMP_VERIFIERS = 1 << 8;
11973        public static final int DUMP_PREFERRED = 1 << 9;
11974        public static final int DUMP_PREFERRED_XML = 1 << 10;
11975        public static final int DUMP_KEYSETS = 1 << 11;
11976        public static final int DUMP_VERSION = 1 << 12;
11977        public static final int DUMP_INSTALLS = 1 << 13;
11978
11979        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11980
11981        private int mTypes;
11982
11983        private int mOptions;
11984
11985        private boolean mTitlePrinted;
11986
11987        private SharedUserSetting mSharedUser;
11988
11989        public boolean isDumping(int type) {
11990            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11991                return true;
11992            }
11993
11994            return (mTypes & type) != 0;
11995        }
11996
11997        public void setDump(int type) {
11998            mTypes |= type;
11999        }
12000
12001        public boolean isOptionEnabled(int option) {
12002            return (mOptions & option) != 0;
12003        }
12004
12005        public void setOptionEnabled(int option) {
12006            mOptions |= option;
12007        }
12008
12009        public boolean onTitlePrinted() {
12010            final boolean printed = mTitlePrinted;
12011            mTitlePrinted = true;
12012            return printed;
12013        }
12014
12015        public boolean getTitlePrinted() {
12016            return mTitlePrinted;
12017        }
12018
12019        public void setTitlePrinted(boolean enabled) {
12020            mTitlePrinted = enabled;
12021        }
12022
12023        public SharedUserSetting getSharedUser() {
12024            return mSharedUser;
12025        }
12026
12027        public void setSharedUser(SharedUserSetting user) {
12028            mSharedUser = user;
12029        }
12030    }
12031
12032    @Override
12033    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12034        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12035                != PackageManager.PERMISSION_GRANTED) {
12036            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12037                    + Binder.getCallingPid()
12038                    + ", uid=" + Binder.getCallingUid()
12039                    + " without permission "
12040                    + android.Manifest.permission.DUMP);
12041            return;
12042        }
12043
12044        DumpState dumpState = new DumpState();
12045        boolean fullPreferred = false;
12046        boolean checkin = false;
12047
12048        String packageName = null;
12049
12050        int opti = 0;
12051        while (opti < args.length) {
12052            String opt = args[opti];
12053            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12054                break;
12055            }
12056            opti++;
12057            if ("-a".equals(opt)) {
12058                // Right now we only know how to print all.
12059            } else if ("-h".equals(opt)) {
12060                pw.println("Package manager dump options:");
12061                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12062                pw.println("    --checkin: dump for a checkin");
12063                pw.println("    -f: print details of intent filters");
12064                pw.println("    -h: print this help");
12065                pw.println("  cmd may be one of:");
12066                pw.println("    l[ibraries]: list known shared libraries");
12067                pw.println("    f[ibraries]: list device features");
12068                pw.println("    k[eysets]: print known keysets");
12069                pw.println("    r[esolvers]: dump intent resolvers");
12070                pw.println("    perm[issions]: dump permissions");
12071                pw.println("    pref[erred]: print preferred package settings");
12072                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12073                pw.println("    prov[iders]: dump content providers");
12074                pw.println("    p[ackages]: dump installed packages");
12075                pw.println("    s[hared-users]: dump shared user IDs");
12076                pw.println("    m[essages]: print collected runtime messages");
12077                pw.println("    v[erifiers]: print package verifier info");
12078                pw.println("    version: print database version info");
12079                pw.println("    write: write current settings now");
12080                pw.println("    <package.name>: info about given package");
12081                pw.println("    installs: details about install sessions");
12082                return;
12083            } else if ("--checkin".equals(opt)) {
12084                checkin = true;
12085            } else if ("-f".equals(opt)) {
12086                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12087            } else {
12088                pw.println("Unknown argument: " + opt + "; use -h for help");
12089            }
12090        }
12091
12092        // Is the caller requesting to dump a particular piece of data?
12093        if (opti < args.length) {
12094            String cmd = args[opti];
12095            opti++;
12096            // Is this a package name?
12097            if ("android".equals(cmd) || cmd.contains(".")) {
12098                packageName = cmd;
12099                // When dumping a single package, we always dump all of its
12100                // filter information since the amount of data will be reasonable.
12101                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12102            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12103                dumpState.setDump(DumpState.DUMP_LIBS);
12104            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12105                dumpState.setDump(DumpState.DUMP_FEATURES);
12106            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12107                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12108            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12109                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12110            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12111                dumpState.setDump(DumpState.DUMP_PREFERRED);
12112            } else if ("preferred-xml".equals(cmd)) {
12113                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12114                if (opti < args.length && "--full".equals(args[opti])) {
12115                    fullPreferred = true;
12116                    opti++;
12117                }
12118            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12119                dumpState.setDump(DumpState.DUMP_PACKAGES);
12120            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12121                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12122            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12123                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12124            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12125                dumpState.setDump(DumpState.DUMP_MESSAGES);
12126            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12127                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12128            } else if ("version".equals(cmd)) {
12129                dumpState.setDump(DumpState.DUMP_VERSION);
12130            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12131                dumpState.setDump(DumpState.DUMP_KEYSETS);
12132            } else if ("installs".equals(cmd)) {
12133                dumpState.setDump(DumpState.DUMP_INSTALLS);
12134            } else if ("write".equals(cmd)) {
12135                synchronized (mPackages) {
12136                    mSettings.writeLPr();
12137                    pw.println("Settings written.");
12138                    return;
12139                }
12140            }
12141        }
12142
12143        if (checkin) {
12144            pw.println("vers,1");
12145        }
12146
12147        // reader
12148        synchronized (mPackages) {
12149            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12150                if (!checkin) {
12151                    if (dumpState.onTitlePrinted())
12152                        pw.println();
12153                    pw.println("Database versions:");
12154                    pw.print("  SDK Version:");
12155                    pw.print(" internal=");
12156                    pw.print(mSettings.mInternalSdkPlatform);
12157                    pw.print(" external=");
12158                    pw.println(mSettings.mExternalSdkPlatform);
12159                    pw.print("  DB Version:");
12160                    pw.print(" internal=");
12161                    pw.print(mSettings.mInternalDatabaseVersion);
12162                    pw.print(" external=");
12163                    pw.println(mSettings.mExternalDatabaseVersion);
12164                }
12165            }
12166
12167            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12168                if (!checkin) {
12169                    if (dumpState.onTitlePrinted())
12170                        pw.println();
12171                    pw.println("Verifiers:");
12172                    pw.print("  Required: ");
12173                    pw.print(mRequiredVerifierPackage);
12174                    pw.print(" (uid=");
12175                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12176                    pw.println(")");
12177                } else if (mRequiredVerifierPackage != null) {
12178                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12179                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12180                }
12181            }
12182
12183            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12184                boolean printedHeader = false;
12185                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12186                while (it.hasNext()) {
12187                    String name = it.next();
12188                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12189                    if (!checkin) {
12190                        if (!printedHeader) {
12191                            if (dumpState.onTitlePrinted())
12192                                pw.println();
12193                            pw.println("Libraries:");
12194                            printedHeader = true;
12195                        }
12196                        pw.print("  ");
12197                    } else {
12198                        pw.print("lib,");
12199                    }
12200                    pw.print(name);
12201                    if (!checkin) {
12202                        pw.print(" -> ");
12203                    }
12204                    if (ent.path != null) {
12205                        if (!checkin) {
12206                            pw.print("(jar) ");
12207                            pw.print(ent.path);
12208                        } else {
12209                            pw.print(",jar,");
12210                            pw.print(ent.path);
12211                        }
12212                    } else {
12213                        if (!checkin) {
12214                            pw.print("(apk) ");
12215                            pw.print(ent.apk);
12216                        } else {
12217                            pw.print(",apk,");
12218                            pw.print(ent.apk);
12219                        }
12220                    }
12221                    pw.println();
12222                }
12223            }
12224
12225            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12226                if (dumpState.onTitlePrinted())
12227                    pw.println();
12228                if (!checkin) {
12229                    pw.println("Features:");
12230                }
12231                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12232                while (it.hasNext()) {
12233                    String name = it.next();
12234                    if (!checkin) {
12235                        pw.print("  ");
12236                    } else {
12237                        pw.print("feat,");
12238                    }
12239                    pw.println(name);
12240                }
12241            }
12242
12243            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12244                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12245                        : "Activity Resolver Table:", "  ", packageName,
12246                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12247                    dumpState.setTitlePrinted(true);
12248                }
12249                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12250                        : "Receiver Resolver Table:", "  ", packageName,
12251                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12252                    dumpState.setTitlePrinted(true);
12253                }
12254                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12255                        : "Service Resolver Table:", "  ", packageName,
12256                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12257                    dumpState.setTitlePrinted(true);
12258                }
12259                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12260                        : "Provider Resolver Table:", "  ", packageName,
12261                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12262                    dumpState.setTitlePrinted(true);
12263                }
12264            }
12265
12266            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12267                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12268                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12269                    int user = mSettings.mPreferredActivities.keyAt(i);
12270                    if (pir.dump(pw,
12271                            dumpState.getTitlePrinted()
12272                                ? "\nPreferred Activities User " + user + ":"
12273                                : "Preferred Activities User " + user + ":", "  ",
12274                            packageName, true)) {
12275                        dumpState.setTitlePrinted(true);
12276                    }
12277                }
12278            }
12279
12280            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12281                pw.flush();
12282                FileOutputStream fout = new FileOutputStream(fd);
12283                BufferedOutputStream str = new BufferedOutputStream(fout);
12284                XmlSerializer serializer = new FastXmlSerializer();
12285                try {
12286                    serializer.setOutput(str, "utf-8");
12287                    serializer.startDocument(null, true);
12288                    serializer.setFeature(
12289                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12290                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12291                    serializer.endDocument();
12292                    serializer.flush();
12293                } catch (IllegalArgumentException e) {
12294                    pw.println("Failed writing: " + e);
12295                } catch (IllegalStateException e) {
12296                    pw.println("Failed writing: " + e);
12297                } catch (IOException e) {
12298                    pw.println("Failed writing: " + e);
12299                }
12300            }
12301
12302            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12303                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12304                if (packageName == null) {
12305                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12306                        if (iperm == 0) {
12307                            if (dumpState.onTitlePrinted())
12308                                pw.println();
12309                            pw.println("AppOp Permissions:");
12310                        }
12311                        pw.print("  AppOp Permission ");
12312                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12313                        pw.println(":");
12314                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12315                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12316                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12317                        }
12318                    }
12319                }
12320            }
12321
12322            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12323                boolean printedSomething = false;
12324                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12325                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12326                        continue;
12327                    }
12328                    if (!printedSomething) {
12329                        if (dumpState.onTitlePrinted())
12330                            pw.println();
12331                        pw.println("Registered ContentProviders:");
12332                        printedSomething = true;
12333                    }
12334                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12335                    pw.print("    "); pw.println(p.toString());
12336                }
12337                printedSomething = false;
12338                for (Map.Entry<String, PackageParser.Provider> entry :
12339                        mProvidersByAuthority.entrySet()) {
12340                    PackageParser.Provider p = entry.getValue();
12341                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12342                        continue;
12343                    }
12344                    if (!printedSomething) {
12345                        if (dumpState.onTitlePrinted())
12346                            pw.println();
12347                        pw.println("ContentProvider Authorities:");
12348                        printedSomething = true;
12349                    }
12350                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12351                    pw.print("    "); pw.println(p.toString());
12352                    if (p.info != null && p.info.applicationInfo != null) {
12353                        final String appInfo = p.info.applicationInfo.toString();
12354                        pw.print("      applicationInfo="); pw.println(appInfo);
12355                    }
12356                }
12357            }
12358
12359            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12360                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12361            }
12362
12363            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12364                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12365            }
12366
12367            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12368                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12369            }
12370
12371            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12372                // XXX should handle packageName != null by dumping only install data that
12373                // the given package is involved with.
12374                if (dumpState.onTitlePrinted()) pw.println();
12375                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12376            }
12377
12378            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12379                if (dumpState.onTitlePrinted()) pw.println();
12380                mSettings.dumpReadMessagesLPr(pw, dumpState);
12381
12382                pw.println();
12383                pw.println("Package warning messages:");
12384                final File fname = getSettingsProblemFile();
12385                FileInputStream in = null;
12386                try {
12387                    in = new FileInputStream(fname);
12388                    final int avail = in.available();
12389                    final byte[] data = new byte[avail];
12390                    in.read(data);
12391                    pw.print(new String(data));
12392                } catch (FileNotFoundException e) {
12393                } catch (IOException e) {
12394                } finally {
12395                    if (in != null) {
12396                        try {
12397                            in.close();
12398                        } catch (IOException e) {
12399                        }
12400                    }
12401                }
12402            }
12403        }
12404    }
12405
12406    // ------- apps on sdcard specific code -------
12407    static final boolean DEBUG_SD_INSTALL = false;
12408
12409    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12410
12411    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12412
12413    private boolean mMediaMounted = false;
12414
12415    static String getEncryptKey() {
12416        try {
12417            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12418                    SD_ENCRYPTION_KEYSTORE_NAME);
12419            if (sdEncKey == null) {
12420                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12421                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12422                if (sdEncKey == null) {
12423                    Slog.e(TAG, "Failed to create encryption keys");
12424                    return null;
12425                }
12426            }
12427            return sdEncKey;
12428        } catch (NoSuchAlgorithmException nsae) {
12429            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12430            return null;
12431        } catch (IOException ioe) {
12432            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12433            return null;
12434        }
12435    }
12436
12437    /*
12438     * Update media status on PackageManager.
12439     */
12440    @Override
12441    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12442        int callingUid = Binder.getCallingUid();
12443        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12444            throw new SecurityException("Media status can only be updated by the system");
12445        }
12446        // reader; this apparently protects mMediaMounted, but should probably
12447        // be a different lock in that case.
12448        synchronized (mPackages) {
12449            Log.i(TAG, "Updating external media status from "
12450                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12451                    + (mediaStatus ? "mounted" : "unmounted"));
12452            if (DEBUG_SD_INSTALL)
12453                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12454                        + ", mMediaMounted=" + mMediaMounted);
12455            if (mediaStatus == mMediaMounted) {
12456                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12457                        : 0, -1);
12458                mHandler.sendMessage(msg);
12459                return;
12460            }
12461            mMediaMounted = mediaStatus;
12462        }
12463        // Queue up an async operation since the package installation may take a
12464        // little while.
12465        mHandler.post(new Runnable() {
12466            public void run() {
12467                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12468            }
12469        });
12470    }
12471
12472    /**
12473     * Called by MountService when the initial ASECs to scan are available.
12474     * Should block until all the ASEC containers are finished being scanned.
12475     */
12476    public void scanAvailableAsecs() {
12477        updateExternalMediaStatusInner(true, false, false);
12478        if (mShouldRestoreconData) {
12479            SELinuxMMAC.setRestoreconDone();
12480            mShouldRestoreconData = false;
12481        }
12482    }
12483
12484    /*
12485     * Collect information of applications on external media, map them against
12486     * existing containers and update information based on current mount status.
12487     * Please note that we always have to report status if reportStatus has been
12488     * set to true especially when unloading packages.
12489     */
12490    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12491            boolean externalStorage) {
12492        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12493        int[] uidArr = EmptyArray.INT;
12494
12495        final String[] list = PackageHelper.getSecureContainerList();
12496        if (ArrayUtils.isEmpty(list)) {
12497            Log.i(TAG, "No secure containers found");
12498        } else {
12499            // Process list of secure containers and categorize them
12500            // as active or stale based on their package internal state.
12501
12502            // reader
12503            synchronized (mPackages) {
12504                for (String cid : list) {
12505                    // Leave stages untouched for now; installer service owns them
12506                    if (PackageInstallerService.isStageName(cid)) continue;
12507
12508                    if (DEBUG_SD_INSTALL)
12509                        Log.i(TAG, "Processing container " + cid);
12510                    String pkgName = getAsecPackageName(cid);
12511                    if (pkgName == null) {
12512                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12513                        continue;
12514                    }
12515                    if (DEBUG_SD_INSTALL)
12516                        Log.i(TAG, "Looking for pkg : " + pkgName);
12517
12518                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12519                    if (ps == null) {
12520                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12521                        continue;
12522                    }
12523
12524                    /*
12525                     * Skip packages that are not external if we're unmounting
12526                     * external storage.
12527                     */
12528                    if (externalStorage && !isMounted && !isExternal(ps)) {
12529                        continue;
12530                    }
12531
12532                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12533                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12534                    // The package status is changed only if the code path
12535                    // matches between settings and the container id.
12536                    if (ps.codePathString != null
12537                            && ps.codePathString.startsWith(args.getCodePath())) {
12538                        if (DEBUG_SD_INSTALL) {
12539                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12540                                    + " at code path: " + ps.codePathString);
12541                        }
12542
12543                        // We do have a valid package installed on sdcard
12544                        processCids.put(args, ps.codePathString);
12545                        final int uid = ps.appId;
12546                        if (uid != -1) {
12547                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12548                        }
12549                    } else {
12550                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12551                                + ps.codePathString);
12552                    }
12553                }
12554            }
12555
12556            Arrays.sort(uidArr);
12557        }
12558
12559        // Process packages with valid entries.
12560        if (isMounted) {
12561            if (DEBUG_SD_INSTALL)
12562                Log.i(TAG, "Loading packages");
12563            loadMediaPackages(processCids, uidArr);
12564            startCleaningPackages();
12565            mInstallerService.onSecureContainersAvailable();
12566        } else {
12567            if (DEBUG_SD_INSTALL)
12568                Log.i(TAG, "Unloading packages");
12569            unloadMediaPackages(processCids, uidArr, reportStatus);
12570        }
12571    }
12572
12573    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12574            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12575        int size = pkgList.size();
12576        if (size > 0) {
12577            // Send broadcasts here
12578            Bundle extras = new Bundle();
12579            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12580                    .toArray(new String[size]));
12581            if (uidArr != null) {
12582                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12583            }
12584            if (replacing) {
12585                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12586            }
12587            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12588                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12589            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12590        }
12591    }
12592
12593   /*
12594     * Look at potentially valid container ids from processCids If package
12595     * information doesn't match the one on record or package scanning fails,
12596     * the cid is added to list of removeCids. We currently don't delete stale
12597     * containers.
12598     */
12599    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12600        ArrayList<String> pkgList = new ArrayList<String>();
12601        Set<AsecInstallArgs> keys = processCids.keySet();
12602
12603        for (AsecInstallArgs args : keys) {
12604            String codePath = processCids.get(args);
12605            if (DEBUG_SD_INSTALL)
12606                Log.i(TAG, "Loading container : " + args.cid);
12607            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12608            try {
12609                // Make sure there are no container errors first.
12610                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12611                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12612                            + " when installing from sdcard");
12613                    continue;
12614                }
12615                // Check code path here.
12616                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12617                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12618                            + " does not match one in settings " + codePath);
12619                    continue;
12620                }
12621                // Parse package
12622                int parseFlags = mDefParseFlags;
12623                if (args.isExternal()) {
12624                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12625                }
12626                if (args.isFwdLocked()) {
12627                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12628                }
12629
12630                synchronized (mInstallLock) {
12631                    PackageParser.Package pkg = null;
12632                    try {
12633                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12634                    } catch (PackageManagerException e) {
12635                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12636                    }
12637                    // Scan the package
12638                    if (pkg != null) {
12639                        /*
12640                         * TODO why is the lock being held? doPostInstall is
12641                         * called in other places without the lock. This needs
12642                         * to be straightened out.
12643                         */
12644                        // writer
12645                        synchronized (mPackages) {
12646                            retCode = PackageManager.INSTALL_SUCCEEDED;
12647                            pkgList.add(pkg.packageName);
12648                            // Post process args
12649                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12650                                    pkg.applicationInfo.uid);
12651                        }
12652                    } else {
12653                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12654                    }
12655                }
12656
12657            } finally {
12658                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12659                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12660                }
12661            }
12662        }
12663        // writer
12664        synchronized (mPackages) {
12665            // If the platform SDK has changed since the last time we booted,
12666            // we need to re-grant app permission to catch any new ones that
12667            // appear. This is really a hack, and means that apps can in some
12668            // cases get permissions that the user didn't initially explicitly
12669            // allow... it would be nice to have some better way to handle
12670            // this situation.
12671            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12672            if (regrantPermissions)
12673                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12674                        + mSdkVersion + "; regranting permissions for external storage");
12675            mSettings.mExternalSdkPlatform = mSdkVersion;
12676
12677            // Make sure group IDs have been assigned, and any permission
12678            // changes in other apps are accounted for
12679            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12680                    | (regrantPermissions
12681                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12682                            : 0));
12683
12684            mSettings.updateExternalDatabaseVersion();
12685
12686            // can downgrade to reader
12687            // Persist settings
12688            mSettings.writeLPr();
12689        }
12690        // Send a broadcast to let everyone know we are done processing
12691        if (pkgList.size() > 0) {
12692            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12693        }
12694    }
12695
12696   /*
12697     * Utility method to unload a list of specified containers
12698     */
12699    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12700        // Just unmount all valid containers.
12701        for (AsecInstallArgs arg : cidArgs) {
12702            synchronized (mInstallLock) {
12703                arg.doPostDeleteLI(false);
12704           }
12705       }
12706   }
12707
12708    /*
12709     * Unload packages mounted on external media. This involves deleting package
12710     * data from internal structures, sending broadcasts about diabled packages,
12711     * gc'ing to free up references, unmounting all secure containers
12712     * corresponding to packages on external media, and posting a
12713     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12714     * that we always have to post this message if status has been requested no
12715     * matter what.
12716     */
12717    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12718            final boolean reportStatus) {
12719        if (DEBUG_SD_INSTALL)
12720            Log.i(TAG, "unloading media packages");
12721        ArrayList<String> pkgList = new ArrayList<String>();
12722        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12723        final Set<AsecInstallArgs> keys = processCids.keySet();
12724        for (AsecInstallArgs args : keys) {
12725            String pkgName = args.getPackageName();
12726            if (DEBUG_SD_INSTALL)
12727                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12728            // Delete package internally
12729            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12730            synchronized (mInstallLock) {
12731                boolean res = deletePackageLI(pkgName, null, false, null, null,
12732                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12733                if (res) {
12734                    pkgList.add(pkgName);
12735                } else {
12736                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12737                    failedList.add(args);
12738                }
12739            }
12740        }
12741
12742        // reader
12743        synchronized (mPackages) {
12744            // We didn't update the settings after removing each package;
12745            // write them now for all packages.
12746            mSettings.writeLPr();
12747        }
12748
12749        // We have to absolutely send UPDATED_MEDIA_STATUS only
12750        // after confirming that all the receivers processed the ordered
12751        // broadcast when packages get disabled, force a gc to clean things up.
12752        // and unload all the containers.
12753        if (pkgList.size() > 0) {
12754            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12755                    new IIntentReceiver.Stub() {
12756                public void performReceive(Intent intent, int resultCode, String data,
12757                        Bundle extras, boolean ordered, boolean sticky,
12758                        int sendingUser) throws RemoteException {
12759                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12760                            reportStatus ? 1 : 0, 1, keys);
12761                    mHandler.sendMessage(msg);
12762                }
12763            });
12764        } else {
12765            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12766                    keys);
12767            mHandler.sendMessage(msg);
12768        }
12769    }
12770
12771    /** Binder call */
12772    @Override
12773    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12774            final int flags) {
12775        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12776        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12777        int returnCode = PackageManager.MOVE_SUCCEEDED;
12778        int currInstallFlags = 0;
12779        int newInstallFlags = 0;
12780
12781        File codeFile = null;
12782        String installerPackageName = null;
12783        String packageAbiOverride = null;
12784
12785        // reader
12786        synchronized (mPackages) {
12787            final PackageParser.Package pkg = mPackages.get(packageName);
12788            final PackageSetting ps = mSettings.mPackages.get(packageName);
12789            if (pkg == null || ps == null) {
12790                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12791            } else {
12792                // Disable moving fwd locked apps and system packages
12793                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12794                    Slog.w(TAG, "Cannot move system application");
12795                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12796                } else if (pkg.mOperationPending) {
12797                    Slog.w(TAG, "Attempt to move package which has pending operations");
12798                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12799                } else {
12800                    // Find install location first
12801                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12802                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12803                        Slog.w(TAG, "Ambigous flags specified for move location.");
12804                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12805                    } else {
12806                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12807                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12808                        currInstallFlags = isExternal(pkg)
12809                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12810
12811                        if (newInstallFlags == currInstallFlags) {
12812                            Slog.w(TAG, "No move required. Trying to move to same location");
12813                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12814                        } else {
12815                            if (isForwardLocked(pkg)) {
12816                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12817                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12818                            }
12819                        }
12820                    }
12821                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12822                        pkg.mOperationPending = true;
12823                    }
12824                }
12825
12826                codeFile = new File(pkg.codePath);
12827                installerPackageName = ps.installerPackageName;
12828                packageAbiOverride = ps.cpuAbiOverrideString;
12829            }
12830        }
12831
12832        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12833            try {
12834                observer.packageMoved(packageName, returnCode);
12835            } catch (RemoteException ignored) {
12836            }
12837            return;
12838        }
12839
12840        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12841            @Override
12842            public void onUserActionRequired(Intent intent) throws RemoteException {
12843                throw new IllegalStateException();
12844            }
12845
12846            @Override
12847            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12848                    Bundle extras) throws RemoteException {
12849                Slog.d(TAG, "Install result for move: "
12850                        + PackageManager.installStatusToString(returnCode, msg));
12851
12852                // We usually have a new package now after the install, but if
12853                // we failed we need to clear the pending flag on the original
12854                // package object.
12855                synchronized (mPackages) {
12856                    final PackageParser.Package pkg = mPackages.get(packageName);
12857                    if (pkg != null) {
12858                        pkg.mOperationPending = false;
12859                    }
12860                }
12861
12862                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12863                switch (status) {
12864                    case PackageInstaller.STATUS_SUCCESS:
12865                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12866                        break;
12867                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12868                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12869                        break;
12870                    default:
12871                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12872                        break;
12873                }
12874            }
12875        };
12876
12877        // Treat a move like reinstalling an existing app, which ensures that we
12878        // process everythign uniformly, like unpacking native libraries.
12879        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12880
12881        final Message msg = mHandler.obtainMessage(INIT_COPY);
12882        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12883        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12884                installerPackageName, null, user, packageAbiOverride);
12885        mHandler.sendMessage(msg);
12886    }
12887
12888    @Override
12889    public boolean setInstallLocation(int loc) {
12890        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12891                null);
12892        if (getInstallLocation() == loc) {
12893            return true;
12894        }
12895        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12896                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12897            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12898                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12899            return true;
12900        }
12901        return false;
12902   }
12903
12904    @Override
12905    public int getInstallLocation() {
12906        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12907                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12908                PackageHelper.APP_INSTALL_AUTO);
12909    }
12910
12911    /** Called by UserManagerService */
12912    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12913        mDirtyUsers.remove(userHandle);
12914        mSettings.removeUserLPw(userHandle);
12915        mPendingBroadcasts.remove(userHandle);
12916        if (mInstaller != null) {
12917            // Technically, we shouldn't be doing this with the package lock
12918            // held.  However, this is very rare, and there is already so much
12919            // other disk I/O going on, that we'll let it slide for now.
12920            mInstaller.removeUserDataDirs(userHandle);
12921        }
12922        mUserNeedsBadging.delete(userHandle);
12923        removeUnusedPackagesLILPw(userManager, userHandle);
12924    }
12925
12926    /**
12927     * We're removing userHandle and would like to remove any downloaded packages
12928     * that are no longer in use by any other user.
12929     * @param userHandle the user being removed
12930     */
12931    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
12932        final boolean DEBUG_CLEAN_APKS = false;
12933        int [] users = userManager.getUserIdsLPr();
12934        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
12935        while (psit.hasNext()) {
12936            PackageSetting ps = psit.next();
12937            if (ps.pkg == null) {
12938                continue;
12939            }
12940            final String packageName = ps.pkg.packageName;
12941            // Skip over if system app
12942            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12943                continue;
12944            }
12945            if (DEBUG_CLEAN_APKS) {
12946                Slog.i(TAG, "Checking package " + packageName);
12947            }
12948            boolean keep = false;
12949            for (int i = 0; i < users.length; i++) {
12950                if (users[i] != userHandle && ps.getInstalled(users[i])) {
12951                    keep = true;
12952                    if (DEBUG_CLEAN_APKS) {
12953                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
12954                                + users[i]);
12955                    }
12956                    break;
12957                }
12958            }
12959            if (!keep) {
12960                if (DEBUG_CLEAN_APKS) {
12961                    Slog.i(TAG, "  Removing package " + packageName);
12962                }
12963                mHandler.post(new Runnable() {
12964                    public void run() {
12965                        deletePackageX(packageName, userHandle, 0);
12966                    } //end run
12967                });
12968            }
12969        }
12970    }
12971
12972    /** Called by UserManagerService */
12973    void createNewUserLILPw(int userHandle, File path) {
12974        if (mInstaller != null) {
12975            mInstaller.createUserConfig(userHandle);
12976            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12977        }
12978    }
12979
12980    @Override
12981    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12982        mContext.enforceCallingOrSelfPermission(
12983                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12984                "Only package verification agents can read the verifier device identity");
12985
12986        synchronized (mPackages) {
12987            return mSettings.getVerifierDeviceIdentityLPw();
12988        }
12989    }
12990
12991    @Override
12992    public void setPermissionEnforced(String permission, boolean enforced) {
12993        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12994        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12995            synchronized (mPackages) {
12996                if (mSettings.mReadExternalStorageEnforced == null
12997                        || mSettings.mReadExternalStorageEnforced != enforced) {
12998                    mSettings.mReadExternalStorageEnforced = enforced;
12999                    mSettings.writeLPr();
13000                }
13001            }
13002            // kill any non-foreground processes so we restart them and
13003            // grant/revoke the GID.
13004            final IActivityManager am = ActivityManagerNative.getDefault();
13005            if (am != null) {
13006                final long token = Binder.clearCallingIdentity();
13007                try {
13008                    am.killProcessesBelowForeground("setPermissionEnforcement");
13009                } catch (RemoteException e) {
13010                } finally {
13011                    Binder.restoreCallingIdentity(token);
13012                }
13013            }
13014        } else {
13015            throw new IllegalArgumentException("No selective enforcement for " + permission);
13016        }
13017    }
13018
13019    @Override
13020    @Deprecated
13021    public boolean isPermissionEnforced(String permission) {
13022        return true;
13023    }
13024
13025    @Override
13026    public boolean isStorageLow() {
13027        final long token = Binder.clearCallingIdentity();
13028        try {
13029            final DeviceStorageMonitorInternal
13030                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13031            if (dsm != null) {
13032                return dsm.isMemoryLow();
13033            } else {
13034                return false;
13035            }
13036        } finally {
13037            Binder.restoreCallingIdentity(token);
13038        }
13039    }
13040
13041    @Override
13042    public IPackageInstaller getPackageInstaller() {
13043        return mInstallerService;
13044    }
13045
13046    private boolean userNeedsBadging(int userId) {
13047        int index = mUserNeedsBadging.indexOfKey(userId);
13048        if (index < 0) {
13049            final UserInfo userInfo;
13050            final long token = Binder.clearCallingIdentity();
13051            try {
13052                userInfo = sUserManager.getUserInfo(userId);
13053            } finally {
13054                Binder.restoreCallingIdentity(token);
13055            }
13056            final boolean b;
13057            if (userInfo != null && userInfo.isManagedProfile()) {
13058                b = true;
13059            } else {
13060                b = false;
13061            }
13062            mUserNeedsBadging.put(userId, b);
13063            return b;
13064        }
13065        return mUserNeedsBadging.valueAt(index);
13066    }
13067
13068    @Override
13069    public KeySet getKeySetByAlias(String packageName, String alias) {
13070        if (packageName == null || alias == null) {
13071            return null;
13072        }
13073        synchronized(mPackages) {
13074            final PackageParser.Package pkg = mPackages.get(packageName);
13075            if (pkg == null) {
13076                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13077                throw new IllegalArgumentException("Unknown package: " + packageName);
13078            }
13079            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13080            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13081        }
13082    }
13083
13084    @Override
13085    public KeySet getSigningKeySet(String packageName) {
13086        if (packageName == null) {
13087            return null;
13088        }
13089        synchronized(mPackages) {
13090            final PackageParser.Package pkg = mPackages.get(packageName);
13091            if (pkg == null) {
13092                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13093                throw new IllegalArgumentException("Unknown package: " + packageName);
13094            }
13095            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13096                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13097                throw new SecurityException("May not access signing KeySet of other apps.");
13098            }
13099            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13100            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13101        }
13102    }
13103
13104    @Override
13105    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13106        if (packageName == null || ks == null) {
13107            return false;
13108        }
13109        synchronized(mPackages) {
13110            final PackageParser.Package pkg = mPackages.get(packageName);
13111            if (pkg == null) {
13112                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13113                throw new IllegalArgumentException("Unknown package: " + packageName);
13114            }
13115            IBinder ksh = ks.getToken();
13116            if (ksh instanceof KeySetHandle) {
13117                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13118                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13119            }
13120            return false;
13121        }
13122    }
13123
13124    @Override
13125    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13126        if (packageName == null || ks == null) {
13127            return false;
13128        }
13129        synchronized(mPackages) {
13130            final PackageParser.Package pkg = mPackages.get(packageName);
13131            if (pkg == null) {
13132                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13133                throw new IllegalArgumentException("Unknown package: " + packageName);
13134            }
13135            IBinder ksh = ks.getToken();
13136            if (ksh instanceof KeySetHandle) {
13137                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13138                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13139            }
13140            return false;
13141        }
13142    }
13143}
13144