PackageManagerService.java revision 340ca8b7e81afe891b2d76a08e406eafc63c4fc8
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 android.system.OsConstants.S_IRGRP;
52import static android.system.OsConstants.S_IROTH;
53import static android.system.OsConstants.S_IRWXU;
54import static android.system.OsConstants.S_IXGRP;
55import static android.system.OsConstants.S_IXOTH;
56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
58import static com.android.internal.util.ArrayUtils.appendInt;
59import static com.android.internal.util.ArrayUtils.removeInt;
60
61import android.util.ArrayMap;
62
63import com.android.internal.R;
64import com.android.internal.app.IMediaContainerService;
65import com.android.internal.app.ResolverActivity;
66import com.android.internal.content.NativeLibraryHelper;
67import com.android.internal.content.PackageHelper;
68import com.android.internal.os.IParcelFileDescriptorFactory;
69import com.android.internal.util.ArrayUtils;
70import com.android.internal.util.FastPrintWriter;
71import com.android.internal.util.FastXmlSerializer;
72import com.android.internal.util.IndentingPrintWriter;
73import com.android.internal.util.Preconditions;
74import com.android.server.EventLogTags;
75import com.android.server.IntentResolver;
76import com.android.server.LocalServices;
77import com.android.server.ServiceThread;
78import com.android.server.SystemConfig;
79import com.android.server.Watchdog;
80import com.android.server.pm.Settings.DatabaseVersion;
81import com.android.server.storage.DeviceStorageMonitorInternal;
82
83import org.xmlpull.v1.XmlSerializer;
84
85import android.app.ActivityManager;
86import android.app.ActivityManagerNative;
87import android.app.IActivityManager;
88import android.app.admin.IDevicePolicyManager;
89import android.app.backup.IBackupManager;
90import android.content.BroadcastReceiver;
91import android.content.ComponentName;
92import android.content.Context;
93import android.content.IIntentReceiver;
94import android.content.Intent;
95import android.content.IntentFilter;
96import android.content.IntentSender;
97import android.content.IntentSender.SendIntentException;
98import android.content.ServiceConnection;
99import android.content.pm.ActivityInfo;
100import android.content.pm.ApplicationInfo;
101import android.content.pm.FeatureInfo;
102import android.content.pm.IPackageDataObserver;
103import android.content.pm.IPackageDeleteObserver;
104import android.content.pm.IPackageInstallObserver2;
105import android.content.pm.IPackageInstaller;
106import android.content.pm.IPackageManager;
107import android.content.pm.IPackageMoveObserver;
108import android.content.pm.IPackageStatsObserver;
109import android.content.pm.InstallSessionParams;
110import android.content.pm.InstrumentationInfo;
111import android.content.pm.ManifestDigest;
112import android.content.pm.PackageCleanItem;
113import android.content.pm.PackageInfo;
114import android.content.pm.PackageInfoLite;
115import android.content.pm.PackageManager;
116import android.content.pm.PackageParser.ActivityIntentInfo;
117import android.content.pm.PackageParser.PackageLite;
118import android.content.pm.PackageParser.PackageParserException;
119import android.content.pm.PackageParser;
120import android.content.pm.PackageStats;
121import android.content.pm.PackageUserState;
122import android.content.pm.ParceledListSlice;
123import android.content.pm.PermissionGroupInfo;
124import android.content.pm.PermissionInfo;
125import android.content.pm.ProviderInfo;
126import android.content.pm.ResolveInfo;
127import android.content.pm.ServiceInfo;
128import android.content.pm.Signature;
129import android.content.pm.UserInfo;
130import android.content.pm.VerificationParams;
131import android.content.pm.VerifierDeviceIdentity;
132import android.content.pm.VerifierInfo;
133import android.content.res.Resources;
134import android.hardware.display.DisplayManager;
135import android.net.Uri;
136import android.os.Binder;
137import android.os.Build;
138import android.os.Bundle;
139import android.os.Environment;
140import android.os.Environment.UserEnvironment;
141import android.os.FileUtils;
142import android.os.Handler;
143import android.os.IBinder;
144import android.os.Looper;
145import android.os.Message;
146import android.os.Parcel;
147import android.os.ParcelFileDescriptor;
148import android.os.Process;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.security.KeyStore;
157import android.security.SystemKeyStore;
158import android.system.ErrnoException;
159import android.system.Os;
160import android.system.StructStat;
161import android.text.TextUtils;
162import android.util.ArraySet;
163import android.util.AtomicFile;
164import android.util.DisplayMetrics;
165import android.util.EventLog;
166import android.util.ExceptionUtils;
167import android.util.Log;
168import android.util.LogPrinter;
169import android.util.PrintStreamPrinter;
170import android.util.Slog;
171import android.util.SparseArray;
172import android.util.SparseBooleanArray;
173import android.view.Display;
174
175import java.io.BufferedInputStream;
176import java.io.BufferedOutputStream;
177import java.io.File;
178import java.io.FileDescriptor;
179import java.io.FileInputStream;
180import java.io.FileNotFoundException;
181import java.io.FileOutputStream;
182import java.io.FilenameFilter;
183import java.io.IOException;
184import java.io.InputStream;
185import java.io.PrintWriter;
186import java.nio.charset.StandardCharsets;
187import java.security.NoSuchAlgorithmException;
188import java.security.PublicKey;
189import java.security.cert.CertificateEncodingException;
190import java.security.cert.CertificateException;
191import java.text.SimpleDateFormat;
192import java.util.ArrayList;
193import java.util.Arrays;
194import java.util.Collection;
195import java.util.Collections;
196import java.util.Comparator;
197import java.util.Date;
198import java.util.HashMap;
199import java.util.HashSet;
200import java.util.Iterator;
201import java.util.List;
202import java.util.Map;
203import java.util.Set;
204import java.util.concurrent.atomic.AtomicBoolean;
205import java.util.concurrent.atomic.AtomicLong;
206
207import dalvik.system.DexFile;
208import dalvik.system.StaleDexCacheError;
209import dalvik.system.VMRuntime;
210
211import libcore.io.IoUtils;
212
213/**
214 * Keep track of all those .apks everywhere.
215 *
216 * This is very central to the platform's security; please run the unit
217 * tests whenever making modifications here:
218 *
219mmm frameworks/base/tests/AndroidTests
220adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
221adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
222 *
223 * {@hide}
224 */
225public class PackageManagerService extends IPackageManager.Stub {
226    static final String TAG = "PackageManager";
227    static final boolean DEBUG_SETTINGS = false;
228    static final boolean DEBUG_PREFERRED = false;
229    static final boolean DEBUG_UPGRADE = false;
230    private static final boolean DEBUG_INSTALL = false;
231    private static final boolean DEBUG_REMOVE = false;
232    private static final boolean DEBUG_BROADCASTS = false;
233    private static final boolean DEBUG_SHOW_INFO = false;
234    private static final boolean DEBUG_PACKAGE_INFO = false;
235    private static final boolean DEBUG_INTENT_MATCHING = false;
236    private static final boolean DEBUG_PACKAGE_SCANNING = false;
237    private static final boolean DEBUG_VERIFY = false;
238    private static final boolean DEBUG_DEXOPT = false;
239    private static final boolean DEBUG_ABI_SELECTION = false;
240
241    private static final int RADIO_UID = Process.PHONE_UID;
242    private static final int LOG_UID = Process.LOG_UID;
243    private static final int NFC_UID = Process.NFC_UID;
244    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
245    private static final int SHELL_UID = Process.SHELL_UID;
246
247    // Cap the size of permission trees that 3rd party apps can define
248    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
249
250    // Suffix used during package installation when copying/moving
251    // package apks to install directory.
252    private static final String INSTALL_PACKAGE_SUFFIX = "-";
253
254    static final int SCAN_MONITOR = 1<<0;
255    static final int SCAN_NO_DEX = 1<<1;
256    static final int SCAN_FORCE_DEX = 1<<2;
257    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
258    static final int SCAN_NEW_INSTALL = 1<<4;
259    static final int SCAN_NO_PATHS = 1<<5;
260    static final int SCAN_UPDATE_TIME = 1<<6;
261    static final int SCAN_DEFER_DEX = 1<<7;
262    static final int SCAN_BOOTING = 1<<8;
263    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
264    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
265
266    static final int REMOVE_CHATTY = 1<<16;
267
268    /**
269     * Timeout (in milliseconds) after which the watchdog should declare that
270     * our handler thread is wedged.  The usual default for such things is one
271     * minute but we sometimes do very lengthy I/O operations on this thread,
272     * such as installing multi-gigabyte applications, so ours needs to be longer.
273     */
274    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
275
276    /**
277     * Whether verification is enabled by default.
278     */
279    private static final boolean DEFAULT_VERIFY_ENABLE = true;
280
281    /**
282     * The default maximum time to wait for the verification agent to return in
283     * milliseconds.
284     */
285    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
286
287    /**
288     * The default response for package verification timeout.
289     *
290     * This can be either PackageManager.VERIFICATION_ALLOW or
291     * PackageManager.VERIFICATION_REJECT.
292     */
293    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
294
295    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
296
297    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
298            DEFAULT_CONTAINER_PACKAGE,
299            "com.android.defcontainer.DefaultContainerService");
300
301    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
302
303    private static final String LIB_DIR_NAME = "lib";
304    private static final String LIB64_DIR_NAME = "lib64";
305
306    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
307
308    static final String mTempContainerPrefix = "smdl2tmp";
309
310    private static String sPreferredInstructionSet;
311
312    final ServiceThread mHandlerThread;
313
314    private static final String IDMAP_PREFIX = "/data/resource-cache/";
315    private static final String IDMAP_SUFFIX = "@idmap";
316
317    final PackageHandler mHandler;
318
319    final int mSdkVersion = Build.VERSION.SDK_INT;
320
321    final Context mContext;
322    final boolean mFactoryTest;
323    final boolean mOnlyCore;
324    final DisplayMetrics mMetrics;
325    final int mDefParseFlags;
326    final String[] mSeparateProcesses;
327
328    // This is where all application persistent data goes.
329    final File mAppDataDir;
330
331    // This is where all application persistent data goes for secondary users.
332    final File mUserAppDataDir;
333
334    /** The location for ASEC container files on internal storage. */
335    final String mAsecInternalPath;
336
337    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
338    // LOCK HELD.  Can be called with mInstallLock held.
339    final Installer mInstaller;
340
341    /** Directory where installed third-party apps stored */
342    final File mAppInstallDir;
343
344    /**
345     * Directory to which applications installed internally have their
346     * 32 bit native libraries copied.
347     */
348    private File mAppLib32InstallDir;
349
350    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
351    // apps.
352    final File mDrmAppPrivateInstallDir;
353
354    // ----------------------------------------------------------------
355
356    // Lock for state used when installing and doing other long running
357    // operations.  Methods that must be called with this lock held have
358    // the suffix "LI".
359    final Object mInstallLock = new Object();
360
361    // These are the directories in the 3rd party applications installed dir
362    // that we have currently loaded packages from.  Keys are the application's
363    // installed zip file (absolute codePath), and values are Package.
364    final HashMap<String, PackageParser.Package> mAppDirs =
365            new HashMap<String, PackageParser.Package>();
366
367    // ----------------------------------------------------------------
368
369    // Keys are String (package name), values are Package.  This also serves
370    // as the lock for the global state.  Methods that must be called with
371    // this lock held have the prefix "LP".
372    final HashMap<String, PackageParser.Package> mPackages =
373            new HashMap<String, PackageParser.Package>();
374
375    // Tracks available target package names -> overlay package paths.
376    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
377        new HashMap<String, HashMap<String, PackageParser.Package>>();
378
379    final Settings mSettings;
380    boolean mRestoredSettings;
381
382    // System configuration read by SystemConfig.
383    final int[] mGlobalGids;
384    final SparseArray<HashSet<String>> mSystemPermissions;
385    final HashMap<String, FeatureInfo> mAvailableFeatures;
386
387    // If mac_permissions.xml was found for seinfo labeling.
388    boolean mFoundPolicyFile;
389
390    // If a recursive restorecon of /data/data/<pkg> is needed.
391    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
392
393    public static final class SharedLibraryEntry {
394        public final String path;
395        public final String apk;
396
397        SharedLibraryEntry(String _path, String _apk) {
398            path = _path;
399            apk = _apk;
400        }
401    }
402
403    // Currently known shared libraries.
404    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
405            new HashMap<String, SharedLibraryEntry>();
406
407    // All available activities, for your resolving pleasure.
408    final ActivityIntentResolver mActivities =
409            new ActivityIntentResolver();
410
411    // All available receivers, for your resolving pleasure.
412    final ActivityIntentResolver mReceivers =
413            new ActivityIntentResolver();
414
415    // All available services, for your resolving pleasure.
416    final ServiceIntentResolver mServices = new ServiceIntentResolver();
417
418    // All available providers, for your resolving pleasure.
419    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
420
421    // Mapping from provider base names (first directory in content URI codePath)
422    // to the provider information.
423    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
424            new HashMap<String, PackageParser.Provider>();
425
426    // Mapping from instrumentation class names to info about them.
427    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
428            new HashMap<ComponentName, PackageParser.Instrumentation>();
429
430    // Mapping from permission names to info about them.
431    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
432            new HashMap<String, PackageParser.PermissionGroup>();
433
434    // Packages whose data we have transfered into another package, thus
435    // should no longer exist.
436    final HashSet<String> mTransferedPackages = new HashSet<String>();
437
438    // Broadcast actions that are only available to the system.
439    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
440
441    /** List of packages waiting for verification. */
442    final SparseArray<PackageVerificationState> mPendingVerification
443            = new SparseArray<PackageVerificationState>();
444
445    /** Set of packages associated with each app op permission. */
446    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
447
448    final PackageInstallerService mInstallerService;
449
450    HashSet<PackageParser.Package> mDeferredDexOpt = null;
451
452    // Cache of users who need badging.
453    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
454
455    /** Token for keys in mPendingVerification. */
456    private int mPendingVerificationToken = 0;
457
458    boolean mSystemReady;
459    boolean mSafeMode;
460    boolean mHasSystemUidErrors;
461
462    ApplicationInfo mAndroidApplication;
463    final ActivityInfo mResolveActivity = new ActivityInfo();
464    final ResolveInfo mResolveInfo = new ResolveInfo();
465    ComponentName mResolveComponentName;
466    PackageParser.Package mPlatformPackage;
467    ComponentName mCustomResolverComponentName;
468
469    boolean mResolverReplaced = false;
470
471    // Set of pending broadcasts for aggregating enable/disable of components.
472    static class PendingPackageBroadcasts {
473        // for each user id, a map of <package name -> components within that package>
474        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
475
476        public PendingPackageBroadcasts() {
477            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
478        }
479
480        public ArrayList<String> get(int userId, String packageName) {
481            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
482            return packages.get(packageName);
483        }
484
485        public void put(int userId, String packageName, ArrayList<String> components) {
486            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
487            packages.put(packageName, components);
488        }
489
490        public void remove(int userId, String packageName) {
491            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
492            if (packages != null) {
493                packages.remove(packageName);
494            }
495        }
496
497        public void remove(int userId) {
498            mUidMap.remove(userId);
499        }
500
501        public int userIdCount() {
502            return mUidMap.size();
503        }
504
505        public int userIdAt(int n) {
506            return mUidMap.keyAt(n);
507        }
508
509        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
510            return mUidMap.get(userId);
511        }
512
513        public int size() {
514            // total number of pending broadcast entries across all userIds
515            int num = 0;
516            for (int i = 0; i< mUidMap.size(); i++) {
517                num += mUidMap.valueAt(i).size();
518            }
519            return num;
520        }
521
522        public void clear() {
523            mUidMap.clear();
524        }
525
526        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
527            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
528            if (map == null) {
529                map = new HashMap<String, ArrayList<String>>();
530                mUidMap.put(userId, map);
531            }
532            return map;
533        }
534    }
535    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
536
537    // Service Connection to remote media container service to copy
538    // package uri's from external media onto secure containers
539    // or internal storage.
540    private IMediaContainerService mContainerService = null;
541
542    static final int SEND_PENDING_BROADCAST = 1;
543    static final int MCS_BOUND = 3;
544    static final int END_COPY = 4;
545    static final int INIT_COPY = 5;
546    static final int MCS_UNBIND = 6;
547    static final int START_CLEANING_PACKAGE = 7;
548    static final int FIND_INSTALL_LOC = 8;
549    static final int POST_INSTALL = 9;
550    static final int MCS_RECONNECT = 10;
551    static final int MCS_GIVE_UP = 11;
552    static final int UPDATED_MEDIA_STATUS = 12;
553    static final int WRITE_SETTINGS = 13;
554    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
555    static final int PACKAGE_VERIFIED = 15;
556    static final int CHECK_PENDING_VERIFICATION = 16;
557
558    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
559
560    // Delay time in millisecs
561    static final int BROADCAST_DELAY = 10 * 1000;
562
563    static UserManagerService sUserManager;
564
565    // Stores a list of users whose package restrictions file needs to be updated
566    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
567
568    final private DefaultContainerConnection mDefContainerConn =
569            new DefaultContainerConnection();
570    class DefaultContainerConnection implements ServiceConnection {
571        public void onServiceConnected(ComponentName name, IBinder service) {
572            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
573            IMediaContainerService imcs =
574                IMediaContainerService.Stub.asInterface(service);
575            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
576        }
577
578        public void onServiceDisconnected(ComponentName name) {
579            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
580        }
581    };
582
583    // Recordkeeping of restore-after-install operations that are currently in flight
584    // between the Package Manager and the Backup Manager
585    class PostInstallData {
586        public InstallArgs args;
587        public PackageInstalledInfo res;
588
589        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
590            args = _a;
591            res = _r;
592        }
593    };
594    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
595    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
596
597    private final String mRequiredVerifierPackage;
598
599    private final PackageUsage mPackageUsage = new PackageUsage();
600
601    private class PackageUsage {
602        private static final int WRITE_INTERVAL
603            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
604
605        private final Object mFileLock = new Object();
606        private final AtomicLong mLastWritten = new AtomicLong(0);
607        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
608
609        private boolean mIsHistoricalPackageUsageAvailable = true;
610
611        boolean isHistoricalPackageUsageAvailable() {
612            return mIsHistoricalPackageUsageAvailable;
613        }
614
615        void write(boolean force) {
616            if (force) {
617                writeInternal();
618                return;
619            }
620            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
621                && !DEBUG_DEXOPT) {
622                return;
623            }
624            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
625                new Thread("PackageUsage_DiskWriter") {
626                    @Override
627                    public void run() {
628                        try {
629                            writeInternal();
630                        } finally {
631                            mBackgroundWriteRunning.set(false);
632                        }
633                    }
634                }.start();
635            }
636        }
637
638        private void writeInternal() {
639            synchronized (mPackages) {
640                synchronized (mFileLock) {
641                    AtomicFile file = getFile();
642                    FileOutputStream f = null;
643                    try {
644                        f = file.startWrite();
645                        BufferedOutputStream out = new BufferedOutputStream(f);
646                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
647                        StringBuilder sb = new StringBuilder();
648                        for (PackageParser.Package pkg : mPackages.values()) {
649                            if (pkg.mLastPackageUsageTimeInMills == 0) {
650                                continue;
651                            }
652                            sb.setLength(0);
653                            sb.append(pkg.packageName);
654                            sb.append(' ');
655                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
656                            sb.append('\n');
657                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
658                        }
659                        out.flush();
660                        file.finishWrite(f);
661                    } catch (IOException e) {
662                        if (f != null) {
663                            file.failWrite(f);
664                        }
665                        Log.e(TAG, "Failed to write package usage times", e);
666                    }
667                }
668            }
669            mLastWritten.set(SystemClock.elapsedRealtime());
670        }
671
672        void readLP() {
673            synchronized (mFileLock) {
674                AtomicFile file = getFile();
675                BufferedInputStream in = null;
676                try {
677                    in = new BufferedInputStream(file.openRead());
678                    StringBuffer sb = new StringBuffer();
679                    while (true) {
680                        String packageName = readToken(in, sb, ' ');
681                        if (packageName == null) {
682                            break;
683                        }
684                        String timeInMillisString = readToken(in, sb, '\n');
685                        if (timeInMillisString == null) {
686                            throw new IOException("Failed to find last usage time for package "
687                                                  + packageName);
688                        }
689                        PackageParser.Package pkg = mPackages.get(packageName);
690                        if (pkg == null) {
691                            continue;
692                        }
693                        long timeInMillis;
694                        try {
695                            timeInMillis = Long.parseLong(timeInMillisString.toString());
696                        } catch (NumberFormatException e) {
697                            throw new IOException("Failed to parse " + timeInMillisString
698                                                  + " as a long.", e);
699                        }
700                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
701                    }
702                } catch (FileNotFoundException expected) {
703                    mIsHistoricalPackageUsageAvailable = false;
704                } catch (IOException e) {
705                    Log.w(TAG, "Failed to read package usage times", e);
706                } finally {
707                    IoUtils.closeQuietly(in);
708                }
709            }
710            mLastWritten.set(SystemClock.elapsedRealtime());
711        }
712
713        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
714                throws IOException {
715            sb.setLength(0);
716            while (true) {
717                int ch = in.read();
718                if (ch == -1) {
719                    if (sb.length() == 0) {
720                        return null;
721                    }
722                    throw new IOException("Unexpected EOF");
723                }
724                if (ch == endOfToken) {
725                    return sb.toString();
726                }
727                sb.append((char)ch);
728            }
729        }
730
731        private AtomicFile getFile() {
732            File dataDir = Environment.getDataDirectory();
733            File systemDir = new File(dataDir, "system");
734            File fname = new File(systemDir, "package-usage.list");
735            return new AtomicFile(fname);
736        }
737    }
738
739    class PackageHandler extends Handler {
740        private boolean mBound = false;
741        final ArrayList<HandlerParams> mPendingInstalls =
742            new ArrayList<HandlerParams>();
743
744        private boolean connectToService() {
745            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
746                    " DefaultContainerService");
747            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
748            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
749            if (mContext.bindServiceAsUser(service, mDefContainerConn,
750                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
751                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
752                mBound = true;
753                return true;
754            }
755            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
756            return false;
757        }
758
759        private void disconnectService() {
760            mContainerService = null;
761            mBound = false;
762            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
763            mContext.unbindService(mDefContainerConn);
764            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
765        }
766
767        PackageHandler(Looper looper) {
768            super(looper);
769        }
770
771        public void handleMessage(Message msg) {
772            try {
773                doHandleMessage(msg);
774            } finally {
775                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
776            }
777        }
778
779        void doHandleMessage(Message msg) {
780            switch (msg.what) {
781                case INIT_COPY: {
782                    HandlerParams params = (HandlerParams) msg.obj;
783                    int idx = mPendingInstalls.size();
784                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
785                    // If a bind was already initiated we dont really
786                    // need to do anything. The pending install
787                    // will be processed later on.
788                    if (!mBound) {
789                        // If this is the only one pending we might
790                        // have to bind to the service again.
791                        if (!connectToService()) {
792                            Slog.e(TAG, "Failed to bind to media container service");
793                            params.serviceError();
794                            return;
795                        } else {
796                            // Once we bind to the service, the first
797                            // pending request will be processed.
798                            mPendingInstalls.add(idx, params);
799                        }
800                    } else {
801                        mPendingInstalls.add(idx, params);
802                        // Already bound to the service. Just make
803                        // sure we trigger off processing the first request.
804                        if (idx == 0) {
805                            mHandler.sendEmptyMessage(MCS_BOUND);
806                        }
807                    }
808                    break;
809                }
810                case MCS_BOUND: {
811                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
812                    if (msg.obj != null) {
813                        mContainerService = (IMediaContainerService) msg.obj;
814                    }
815                    if (mContainerService == null) {
816                        // Something seriously wrong. Bail out
817                        Slog.e(TAG, "Cannot bind to media container service");
818                        for (HandlerParams params : mPendingInstalls) {
819                            // Indicate service bind error
820                            params.serviceError();
821                        }
822                        mPendingInstalls.clear();
823                    } else if (mPendingInstalls.size() > 0) {
824                        HandlerParams params = mPendingInstalls.get(0);
825                        if (params != null) {
826                            if (params.startCopy()) {
827                                // We are done...  look for more work or to
828                                // go idle.
829                                if (DEBUG_SD_INSTALL) Log.i(TAG,
830                                        "Checking for more work or unbind...");
831                                // Delete pending install
832                                if (mPendingInstalls.size() > 0) {
833                                    mPendingInstalls.remove(0);
834                                }
835                                if (mPendingInstalls.size() == 0) {
836                                    if (mBound) {
837                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
838                                                "Posting delayed MCS_UNBIND");
839                                        removeMessages(MCS_UNBIND);
840                                        Message ubmsg = obtainMessage(MCS_UNBIND);
841                                        // Unbind after a little delay, to avoid
842                                        // continual thrashing.
843                                        sendMessageDelayed(ubmsg, 10000);
844                                    }
845                                } else {
846                                    // There are more pending requests in queue.
847                                    // Just post MCS_BOUND message to trigger processing
848                                    // of next pending install.
849                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
850                                            "Posting MCS_BOUND for next work");
851                                    mHandler.sendEmptyMessage(MCS_BOUND);
852                                }
853                            }
854                        }
855                    } else {
856                        // Should never happen ideally.
857                        Slog.w(TAG, "Empty queue");
858                    }
859                    break;
860                }
861                case MCS_RECONNECT: {
862                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
863                    if (mPendingInstalls.size() > 0) {
864                        if (mBound) {
865                            disconnectService();
866                        }
867                        if (!connectToService()) {
868                            Slog.e(TAG, "Failed to bind to media container service");
869                            for (HandlerParams params : mPendingInstalls) {
870                                // Indicate service bind error
871                                params.serviceError();
872                            }
873                            mPendingInstalls.clear();
874                        }
875                    }
876                    break;
877                }
878                case MCS_UNBIND: {
879                    // If there is no actual work left, then time to unbind.
880                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
881
882                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
883                        if (mBound) {
884                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
885
886                            disconnectService();
887                        }
888                    } else if (mPendingInstalls.size() > 0) {
889                        // There are more pending requests in queue.
890                        // Just post MCS_BOUND message to trigger processing
891                        // of next pending install.
892                        mHandler.sendEmptyMessage(MCS_BOUND);
893                    }
894
895                    break;
896                }
897                case MCS_GIVE_UP: {
898                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
899                    mPendingInstalls.remove(0);
900                    break;
901                }
902                case SEND_PENDING_BROADCAST: {
903                    String packages[];
904                    ArrayList<String> components[];
905                    int size = 0;
906                    int uids[];
907                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
908                    synchronized (mPackages) {
909                        if (mPendingBroadcasts == null) {
910                            return;
911                        }
912                        size = mPendingBroadcasts.size();
913                        if (size <= 0) {
914                            // Nothing to be done. Just return
915                            return;
916                        }
917                        packages = new String[size];
918                        components = new ArrayList[size];
919                        uids = new int[size];
920                        int i = 0;  // filling out the above arrays
921
922                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
923                            int packageUserId = mPendingBroadcasts.userIdAt(n);
924                            Iterator<Map.Entry<String, ArrayList<String>>> it
925                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
926                                            .entrySet().iterator();
927                            while (it.hasNext() && i < size) {
928                                Map.Entry<String, ArrayList<String>> ent = it.next();
929                                packages[i] = ent.getKey();
930                                components[i] = ent.getValue();
931                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
932                                uids[i] = (ps != null)
933                                        ? UserHandle.getUid(packageUserId, ps.appId)
934                                        : -1;
935                                i++;
936                            }
937                        }
938                        size = i;
939                        mPendingBroadcasts.clear();
940                    }
941                    // Send broadcasts
942                    for (int i = 0; i < size; i++) {
943                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
944                    }
945                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
946                    break;
947                }
948                case START_CLEANING_PACKAGE: {
949                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
950                    final String packageName = (String)msg.obj;
951                    final int userId = msg.arg1;
952                    final boolean andCode = msg.arg2 != 0;
953                    synchronized (mPackages) {
954                        if (userId == UserHandle.USER_ALL) {
955                            int[] users = sUserManager.getUserIds();
956                            for (int user : users) {
957                                mSettings.addPackageToCleanLPw(
958                                        new PackageCleanItem(user, packageName, andCode));
959                            }
960                        } else {
961                            mSettings.addPackageToCleanLPw(
962                                    new PackageCleanItem(userId, packageName, andCode));
963                        }
964                    }
965                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
966                    startCleaningPackages();
967                } break;
968                case POST_INSTALL: {
969                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
970                    PostInstallData data = mRunningInstalls.get(msg.arg1);
971                    mRunningInstalls.delete(msg.arg1);
972                    boolean deleteOld = false;
973
974                    if (data != null) {
975                        InstallArgs args = data.args;
976                        PackageInstalledInfo res = data.res;
977
978                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
979                            res.removedInfo.sendBroadcast(false, true, false);
980                            Bundle extras = new Bundle(1);
981                            extras.putInt(Intent.EXTRA_UID, res.uid);
982                            // Determine the set of users who are adding this
983                            // package for the first time vs. those who are seeing
984                            // an update.
985                            int[] firstUsers;
986                            int[] updateUsers = new int[0];
987                            if (res.origUsers == null || res.origUsers.length == 0) {
988                                firstUsers = res.newUsers;
989                            } else {
990                                firstUsers = new int[0];
991                                for (int i=0; i<res.newUsers.length; i++) {
992                                    int user = res.newUsers[i];
993                                    boolean isNew = true;
994                                    for (int j=0; j<res.origUsers.length; j++) {
995                                        if (res.origUsers[j] == user) {
996                                            isNew = false;
997                                            break;
998                                        }
999                                    }
1000                                    if (isNew) {
1001                                        int[] newFirst = new int[firstUsers.length+1];
1002                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1003                                                firstUsers.length);
1004                                        newFirst[firstUsers.length] = user;
1005                                        firstUsers = newFirst;
1006                                    } else {
1007                                        int[] newUpdate = new int[updateUsers.length+1];
1008                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1009                                                updateUsers.length);
1010                                        newUpdate[updateUsers.length] = user;
1011                                        updateUsers = newUpdate;
1012                                    }
1013                                }
1014                            }
1015                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1016                                    res.pkg.applicationInfo.packageName,
1017                                    extras, null, null, firstUsers);
1018                            final boolean update = res.removedInfo.removedPackage != null;
1019                            if (update) {
1020                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1021                            }
1022                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1023                                    res.pkg.applicationInfo.packageName,
1024                                    extras, null, null, updateUsers);
1025                            if (update) {
1026                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1027                                        res.pkg.applicationInfo.packageName,
1028                                        extras, null, null, updateUsers);
1029                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1030                                        null, null,
1031                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1032
1033                                // treat asec-hosted packages like removable media on upgrade
1034                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1035                                    if (DEBUG_INSTALL) {
1036                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1037                                                + " is ASEC-hosted -> AVAILABLE");
1038                                    }
1039                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1040                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1041                                    pkgList.add(res.pkg.applicationInfo.packageName);
1042                                    sendResourcesChangedBroadcast(true, true,
1043                                            pkgList,uidArray, null);
1044                                }
1045                            }
1046                            if (res.removedInfo.args != null) {
1047                                // Remove the replaced package's older resources safely now
1048                                deleteOld = true;
1049                            }
1050
1051                            // Log current value of "unknown sources" setting
1052                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1053                                getUnknownSourcesSettings());
1054                        }
1055                        // Force a gc to clear up things
1056                        Runtime.getRuntime().gc();
1057                        // We delete after a gc for applications  on sdcard.
1058                        if (deleteOld) {
1059                            synchronized (mInstallLock) {
1060                                res.removedInfo.args.doPostDeleteLI(true);
1061                            }
1062                        }
1063                        if (args.observer != null) {
1064                            try {
1065                                Bundle extras = extrasForInstallResult(res);
1066                                args.observer.packageInstalled(res.name, extras, res.returnCode,
1067                                        res.returnMsg);
1068                            } catch (RemoteException e) {
1069                                Slog.i(TAG, "Observer no longer exists.");
1070                            }
1071                        }
1072                    } else {
1073                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1074                    }
1075                } break;
1076                case UPDATED_MEDIA_STATUS: {
1077                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1078                    boolean reportStatus = msg.arg1 == 1;
1079                    boolean doGc = msg.arg2 == 1;
1080                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1081                    if (doGc) {
1082                        // Force a gc to clear up stale containers.
1083                        Runtime.getRuntime().gc();
1084                    }
1085                    if (msg.obj != null) {
1086                        @SuppressWarnings("unchecked")
1087                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1088                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1089                        // Unload containers
1090                        unloadAllContainers(args);
1091                    }
1092                    if (reportStatus) {
1093                        try {
1094                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1095                            PackageHelper.getMountService().finishMediaUpdate();
1096                        } catch (RemoteException e) {
1097                            Log.e(TAG, "MountService not running?");
1098                        }
1099                    }
1100                } break;
1101                case WRITE_SETTINGS: {
1102                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1103                    synchronized (mPackages) {
1104                        removeMessages(WRITE_SETTINGS);
1105                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1106                        mSettings.writeLPr();
1107                        mDirtyUsers.clear();
1108                    }
1109                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1110                } break;
1111                case WRITE_PACKAGE_RESTRICTIONS: {
1112                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1113                    synchronized (mPackages) {
1114                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1115                        for (int userId : mDirtyUsers) {
1116                            mSettings.writePackageRestrictionsLPr(userId);
1117                        }
1118                        mDirtyUsers.clear();
1119                    }
1120                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1121                } break;
1122                case CHECK_PENDING_VERIFICATION: {
1123                    final int verificationId = msg.arg1;
1124                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1125
1126                    if ((state != null) && !state.timeoutExtended()) {
1127                        final InstallArgs args = state.getInstallArgs();
1128                        final Uri originUri = Uri.fromFile(args.originFile);
1129
1130                        Slog.i(TAG, "Verification timed out for " + originUri);
1131                        mPendingVerification.remove(verificationId);
1132
1133                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1134
1135                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1136                            Slog.i(TAG, "Continuing with installation of " + originUri);
1137                            state.setVerifierResponse(Binder.getCallingUid(),
1138                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1139                            broadcastPackageVerified(verificationId, originUri,
1140                                    PackageManager.VERIFICATION_ALLOW,
1141                                    state.getInstallArgs().getUser());
1142                            try {
1143                                ret = args.copyApk(mContainerService, true);
1144                            } catch (RemoteException e) {
1145                                Slog.e(TAG, "Could not contact the ContainerService");
1146                            }
1147                        } else {
1148                            broadcastPackageVerified(verificationId, originUri,
1149                                    PackageManager.VERIFICATION_REJECT,
1150                                    state.getInstallArgs().getUser());
1151                        }
1152
1153                        processPendingInstall(args, ret);
1154                        mHandler.sendEmptyMessage(MCS_UNBIND);
1155                    }
1156                    break;
1157                }
1158                case PACKAGE_VERIFIED: {
1159                    final int verificationId = msg.arg1;
1160
1161                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1162                    if (state == null) {
1163                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1164                        break;
1165                    }
1166
1167                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1168
1169                    state.setVerifierResponse(response.callerUid, response.code);
1170
1171                    if (state.isVerificationComplete()) {
1172                        mPendingVerification.remove(verificationId);
1173
1174                        final InstallArgs args = state.getInstallArgs();
1175                        final Uri originUri = Uri.fromFile(args.originFile);
1176
1177                        int ret;
1178                        if (state.isInstallAllowed()) {
1179                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1180                            broadcastPackageVerified(verificationId, originUri,
1181                                    response.code, state.getInstallArgs().getUser());
1182                            try {
1183                                ret = args.copyApk(mContainerService, true);
1184                            } catch (RemoteException e) {
1185                                Slog.e(TAG, "Could not contact the ContainerService");
1186                            }
1187                        } else {
1188                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1189                        }
1190
1191                        processPendingInstall(args, ret);
1192
1193                        mHandler.sendEmptyMessage(MCS_UNBIND);
1194                    }
1195
1196                    break;
1197                }
1198            }
1199        }
1200    }
1201
1202    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1203        Bundle extras = null;
1204        switch (res.returnCode) {
1205            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1206                extras = new Bundle();
1207                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1208                        res.origPermission);
1209                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1210                        res.origPackage);
1211                break;
1212            }
1213        }
1214        return extras;
1215    }
1216
1217    void scheduleWriteSettingsLocked() {
1218        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1219            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1220        }
1221    }
1222
1223    void scheduleWritePackageRestrictionsLocked(int userId) {
1224        if (!sUserManager.exists(userId)) return;
1225        mDirtyUsers.add(userId);
1226        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1227            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1228        }
1229    }
1230
1231    public static final PackageManagerService main(Context context, Installer installer,
1232            boolean factoryTest, boolean onlyCore) {
1233        PackageManagerService m = new PackageManagerService(context, installer,
1234                factoryTest, onlyCore);
1235        ServiceManager.addService("package", m);
1236        return m;
1237    }
1238
1239    static String[] splitString(String str, char sep) {
1240        int count = 1;
1241        int i = 0;
1242        while ((i=str.indexOf(sep, i)) >= 0) {
1243            count++;
1244            i++;
1245        }
1246
1247        String[] res = new String[count];
1248        i=0;
1249        count = 0;
1250        int lastI=0;
1251        while ((i=str.indexOf(sep, i)) >= 0) {
1252            res[count] = str.substring(lastI, i);
1253            count++;
1254            i++;
1255            lastI = i;
1256        }
1257        res[count] = str.substring(lastI, str.length());
1258        return res;
1259    }
1260
1261    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1262        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1263                Context.DISPLAY_SERVICE);
1264        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1265    }
1266
1267    public PackageManagerService(Context context, Installer installer,
1268            boolean factoryTest, boolean onlyCore) {
1269        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1270                SystemClock.uptimeMillis());
1271
1272        if (mSdkVersion <= 0) {
1273            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1274        }
1275
1276        mContext = context;
1277        mFactoryTest = factoryTest;
1278        mOnlyCore = onlyCore;
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, null, 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 scanMode = SCAN_MONITOR | 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            String bootClassPath = System.getProperty("java.boot.class.path");
1392            if (bootClassPath != null) {
1393                String[] paths = splitString(bootClassPath, ':');
1394                for (int i=0; i<paths.length; i++) {
1395                    alreadyDexOpted.add(paths[i]);
1396                }
1397            } else {
1398                Slog.w(TAG, "No BOOTCLASSPATH found!");
1399            }
1400
1401            boolean didDexOptLibraryOrTool = false;
1402
1403            final List<String> instructionSets = getAllInstructionSets();
1404
1405            /**
1406             * Ensure all external libraries have had dexopt run on them.
1407             */
1408            if (mSharedLibraries.size() > 0) {
1409                // NOTE: For now, we're compiling these system "shared libraries"
1410                // (and framework jars) into all available architectures. It's possible
1411                // to compile them only when we come across an app that uses them (there's
1412                // already logic for that in scanPackageLI) but that adds some complexity.
1413                for (String instructionSet : instructionSets) {
1414                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1415                        final String lib = libEntry.path;
1416                        if (lib == null) {
1417                            continue;
1418                        }
1419
1420                        try {
1421                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1422                                alreadyDexOpted.add(lib);
1423
1424                                // The list of "shared libraries" we have at this point is
1425                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1426                                didDexOptLibraryOrTool = true;
1427                            }
1428                        } catch (FileNotFoundException e) {
1429                            Slog.w(TAG, "Library not found: " + lib);
1430                        } catch (IOException e) {
1431                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1432                                    + e.getMessage());
1433                        }
1434                    }
1435                }
1436            }
1437
1438            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1439
1440            // Gross hack for now: we know this file doesn't contain any
1441            // code, so don't dexopt it to avoid the resulting log spew.
1442            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1443
1444            // Gross hack for now: we know this file is only part of
1445            // the boot class path for art, so don't dexopt it to
1446            // avoid the resulting log spew.
1447            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1448
1449            /**
1450             * And there are a number of commands implemented in Java, which
1451             * we currently need to do the dexopt on so that they can be
1452             * run from a non-root shell.
1453             */
1454            String[] frameworkFiles = frameworkDir.list();
1455            if (frameworkFiles != null) {
1456                // TODO: We could compile these only for the most preferred ABI. We should
1457                // first double check that the dex files for these commands are not referenced
1458                // by other system apps.
1459                for (String instructionSet : instructionSets) {
1460                    for (int i=0; i<frameworkFiles.length; i++) {
1461                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1462                        String path = libPath.getPath();
1463                        // Skip the file if we already did it.
1464                        if (alreadyDexOpted.contains(path)) {
1465                            continue;
1466                        }
1467                        // Skip the file if it is not a type we want to dexopt.
1468                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1469                            continue;
1470                        }
1471                        try {
1472                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1473                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1474                                didDexOptLibraryOrTool = true;
1475                            }
1476                        } catch (FileNotFoundException e) {
1477                            Slog.w(TAG, "Jar not found: " + path);
1478                        } catch (IOException e) {
1479                            Slog.w(TAG, "Exception reading jar: " + path, e);
1480                        }
1481                    }
1482                }
1483            }
1484
1485            if (didDexOptLibraryOrTool) {
1486                // If we dexopted a library or tool, then something on the system has
1487                // changed. Consider this significant, and wipe away all other
1488                // existing dexopt files to ensure we don't leave any dangling around.
1489                //
1490                // TODO: This should be revisited because it isn't as good an indicator
1491                // as it used to be. It used to include the boot classpath but at some point
1492                // DexFile.isDexOptNeeded started returning false for the boot
1493                // class path files in all cases. It is very possible in a
1494                // small maintenance release update that the library and tool
1495                // jars may be unchanged but APK could be removed resulting in
1496                // unused dalvik-cache files.
1497                for (String instructionSet : instructionSets) {
1498                    mInstaller.pruneDexCache(instructionSet);
1499                }
1500
1501                // Additionally, delete all dex files from the root directory
1502                // since there shouldn't be any there anyway, unless we're upgrading
1503                // from an older OS version or a build that contained the "old" style
1504                // flat scheme.
1505                mInstaller.pruneDexCache(".");
1506            }
1507
1508            // Collect vendor overlay packages.
1509            // (Do this before scanning any apps.)
1510            // For security and version matching reason, only consider
1511            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1512            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1513            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1514                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1515
1516            // Find base frameworks (resource packages without code).
1517            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1518                    | PackageParser.PARSE_IS_SYSTEM_DIR
1519                    | PackageParser.PARSE_IS_PRIVILEGED,
1520                    scanMode | SCAN_NO_DEX, 0);
1521
1522            // Collected privileged system packages.
1523            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1524            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1525                    | PackageParser.PARSE_IS_SYSTEM_DIR
1526                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1527
1528            // Collect ordinary system packages.
1529            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1530            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1531                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1532
1533            // Collect all vendor packages.
1534            File vendorAppDir = new File("/vendor/app");
1535            try {
1536                vendorAppDir = vendorAppDir.getCanonicalFile();
1537            } catch (IOException e) {
1538                // failed to look up canonical path, continue with original one
1539            }
1540            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1541                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1542
1543            // Collect all OEM packages.
1544            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1545            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1547
1548            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1549            mInstaller.moveFiles();
1550
1551            // Prune any system packages that no longer exist.
1552            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1553            if (!mOnlyCore) {
1554                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1555                while (psit.hasNext()) {
1556                    PackageSetting ps = psit.next();
1557
1558                    /*
1559                     * If this is not a system app, it can't be a
1560                     * disable system app.
1561                     */
1562                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1563                        continue;
1564                    }
1565
1566                    /*
1567                     * If the package is scanned, it's not erased.
1568                     */
1569                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1570                    if (scannedPkg != null) {
1571                        /*
1572                         * If the system app is both scanned and in the
1573                         * disabled packages list, then it must have been
1574                         * added via OTA. Remove it from the currently
1575                         * scanned package so the previously user-installed
1576                         * application can be scanned.
1577                         */
1578                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1579                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1580                                    + "; removing system app");
1581                            removePackageLI(ps, true);
1582                        }
1583
1584                        continue;
1585                    }
1586
1587                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1588                        psit.remove();
1589                        String msg = "System package " + ps.name
1590                                + " no longer exists; wiping its data";
1591                        reportSettingsProblem(Log.WARN, msg);
1592                        removeDataDirsLI(ps.name);
1593                    } else {
1594                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1595                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1596                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1597                        }
1598                    }
1599                }
1600            }
1601
1602            //look for any incomplete package installations
1603            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1604            //clean up list
1605            for(int i = 0; i < deletePkgsList.size(); i++) {
1606                //clean up here
1607                cleanupInstallFailedPackage(deletePkgsList.get(i));
1608            }
1609            //delete tmp files
1610            deleteTempPackageFiles();
1611
1612            // Remove any shared userIDs that have no associated packages
1613            mSettings.pruneSharedUsersLPw();
1614
1615            if (!mOnlyCore) {
1616                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1617                        SystemClock.uptimeMillis());
1618                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1619
1620                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1621                        scanMode, 0);
1622
1623                /**
1624                 * Remove disable package settings for any updated system
1625                 * apps that were removed via an OTA. If they're not a
1626                 * previously-updated app, remove them completely.
1627                 * Otherwise, just revoke their system-level permissions.
1628                 */
1629                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1630                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1631                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1632
1633                    String msg;
1634                    if (deletedPkg == null) {
1635                        msg = "Updated system package " + deletedAppName
1636                                + " no longer exists; wiping its data";
1637                        removeDataDirsLI(deletedAppName);
1638                    } else {
1639                        msg = "Updated system app + " + deletedAppName
1640                                + " no longer present; removing system privileges for "
1641                                + deletedAppName;
1642
1643                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1644
1645                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1646                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1647                    }
1648                    reportSettingsProblem(Log.WARN, msg);
1649                }
1650            }
1651
1652            // Now that we know all of the shared libraries, update all clients to have
1653            // the correct library paths.
1654            updateAllSharedLibrariesLPw();
1655
1656            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1657                // NOTE: We ignore potential failures here during a system scan (like
1658                // the rest of the commands above) because there's precious little we
1659                // can do about it. A settings error is reported, though.
1660                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1661                        false /* force dexopt */, false /* defer dexopt */);
1662            }
1663
1664            // Now that we know all the packages we are keeping,
1665            // read and update their last usage times.
1666            mPackageUsage.readLP();
1667
1668            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1669                    SystemClock.uptimeMillis());
1670            Slog.i(TAG, "Time to scan packages: "
1671                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1672                    + " seconds");
1673
1674            // If the platform SDK has changed since the last time we booted,
1675            // we need to re-grant app permission to catch any new ones that
1676            // appear.  This is really a hack, and means that apps can in some
1677            // cases get permissions that the user didn't initially explicitly
1678            // allow...  it would be nice to have some better way to handle
1679            // this situation.
1680            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1681                    != mSdkVersion;
1682            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1683                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1684                    + "; regranting permissions for internal storage");
1685            mSettings.mInternalSdkPlatform = mSdkVersion;
1686
1687            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1688                    | (regrantPermissions
1689                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1690                            : 0));
1691
1692            // If this is the first boot, and it is a normal boot, then
1693            // we need to initialize the default preferred apps.
1694            if (!mRestoredSettings && !onlyCore) {
1695                mSettings.readDefaultPreferredAppsLPw(this, 0);
1696            }
1697
1698            // If this is first boot after an OTA, and a normal boot, then
1699            // we need to clear code cache directories.
1700            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1701                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1702                for (String pkgName : mSettings.mPackages.keySet()) {
1703                    deleteCodeCacheDirsLI(pkgName);
1704                }
1705                mSettings.mFingerprint = Build.FINGERPRINT;
1706            }
1707
1708            // All the changes are done during package scanning.
1709            mSettings.updateInternalDatabaseVersion();
1710
1711            // can downgrade to reader
1712            mSettings.writeLPr();
1713
1714            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1715                    SystemClock.uptimeMillis());
1716
1717
1718            mRequiredVerifierPackage = getRequiredVerifierLPr();
1719        } // synchronized (mPackages)
1720        } // synchronized (mInstallLock)
1721
1722        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1723
1724        // Now after opening every single application zip, make sure they
1725        // are all flushed.  Not really needed, but keeps things nice and
1726        // tidy.
1727        Runtime.getRuntime().gc();
1728    }
1729
1730    @Override
1731    public boolean isFirstBoot() {
1732        return !mRestoredSettings;
1733    }
1734
1735    @Override
1736    public boolean isOnlyCoreApps() {
1737        return mOnlyCore;
1738    }
1739
1740    private String getRequiredVerifierLPr() {
1741        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1742        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1743                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1744
1745        String requiredVerifier = null;
1746
1747        final int N = receivers.size();
1748        for (int i = 0; i < N; i++) {
1749            final ResolveInfo info = receivers.get(i);
1750
1751            if (info.activityInfo == null) {
1752                continue;
1753            }
1754
1755            final String packageName = info.activityInfo.packageName;
1756
1757            final PackageSetting ps = mSettings.mPackages.get(packageName);
1758            if (ps == null) {
1759                continue;
1760            }
1761
1762            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1763            if (!gp.grantedPermissions
1764                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1765                continue;
1766            }
1767
1768            if (requiredVerifier != null) {
1769                throw new RuntimeException("There can be only one required verifier");
1770            }
1771
1772            requiredVerifier = packageName;
1773        }
1774
1775        return requiredVerifier;
1776    }
1777
1778    @Override
1779    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1780            throws RemoteException {
1781        try {
1782            return super.onTransact(code, data, reply, flags);
1783        } catch (RuntimeException e) {
1784            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1785                Slog.wtf(TAG, "Package Manager Crash", e);
1786            }
1787            throw e;
1788        }
1789    }
1790
1791    void cleanupInstallFailedPackage(PackageSetting ps) {
1792        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1793        removeDataDirsLI(ps.name);
1794
1795        // TODO: try cleaning up codePath directory contents first, since it
1796        // might be a cluster
1797
1798        if (ps.codePath != null) {
1799            if (!ps.codePath.delete()) {
1800                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1801            }
1802        }
1803        if (ps.resourcePath != null) {
1804            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1805                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1806            }
1807        }
1808        mSettings.removePackageLPw(ps.name);
1809    }
1810
1811    static int[] appendInts(int[] cur, int[] add) {
1812        if (add == null) return cur;
1813        if (cur == null) return add;
1814        final int N = add.length;
1815        for (int i=0; i<N; i++) {
1816            cur = appendInt(cur, add[i]);
1817        }
1818        return cur;
1819    }
1820
1821    static int[] removeInts(int[] cur, int[] rem) {
1822        if (rem == null) return cur;
1823        if (cur == null) return cur;
1824        final int N = rem.length;
1825        for (int i=0; i<N; i++) {
1826            cur = removeInt(cur, rem[i]);
1827        }
1828        return cur;
1829    }
1830
1831    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1832        if (!sUserManager.exists(userId)) return null;
1833        final PackageSetting ps = (PackageSetting) p.mExtras;
1834        if (ps == null) {
1835            return null;
1836        }
1837        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1838        final PackageUserState state = ps.readUserState(userId);
1839        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1840                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1841                state, userId);
1842    }
1843
1844    @Override
1845    public boolean isPackageAvailable(String packageName, int userId) {
1846        if (!sUserManager.exists(userId)) return false;
1847        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1848        synchronized (mPackages) {
1849            PackageParser.Package p = mPackages.get(packageName);
1850            if (p != null) {
1851                final PackageSetting ps = (PackageSetting) p.mExtras;
1852                if (ps != null) {
1853                    final PackageUserState state = ps.readUserState(userId);
1854                    if (state != null) {
1855                        return PackageParser.isAvailable(state);
1856                    }
1857                }
1858            }
1859        }
1860        return false;
1861    }
1862
1863    @Override
1864    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1865        if (!sUserManager.exists(userId)) return null;
1866        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1867        // reader
1868        synchronized (mPackages) {
1869            PackageParser.Package p = mPackages.get(packageName);
1870            if (DEBUG_PACKAGE_INFO)
1871                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1872            if (p != null) {
1873                return generatePackageInfo(p, flags, userId);
1874            }
1875            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1876                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1877            }
1878        }
1879        return null;
1880    }
1881
1882    @Override
1883    public String[] currentToCanonicalPackageNames(String[] names) {
1884        String[] out = new String[names.length];
1885        // reader
1886        synchronized (mPackages) {
1887            for (int i=names.length-1; i>=0; i--) {
1888                PackageSetting ps = mSettings.mPackages.get(names[i]);
1889                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1890            }
1891        }
1892        return out;
1893    }
1894
1895    @Override
1896    public String[] canonicalToCurrentPackageNames(String[] names) {
1897        String[] out = new String[names.length];
1898        // reader
1899        synchronized (mPackages) {
1900            for (int i=names.length-1; i>=0; i--) {
1901                String cur = mSettings.mRenamedPackages.get(names[i]);
1902                out[i] = cur != null ? cur : names[i];
1903            }
1904        }
1905        return out;
1906    }
1907
1908    @Override
1909    public int getPackageUid(String packageName, int userId) {
1910        if (!sUserManager.exists(userId)) return -1;
1911        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1912        // reader
1913        synchronized (mPackages) {
1914            PackageParser.Package p = mPackages.get(packageName);
1915            if(p != null) {
1916                return UserHandle.getUid(userId, p.applicationInfo.uid);
1917            }
1918            PackageSetting ps = mSettings.mPackages.get(packageName);
1919            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1920                return -1;
1921            }
1922            p = ps.pkg;
1923            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1924        }
1925    }
1926
1927    @Override
1928    public int[] getPackageGids(String packageName) {
1929        // reader
1930        synchronized (mPackages) {
1931            PackageParser.Package p = mPackages.get(packageName);
1932            if (DEBUG_PACKAGE_INFO)
1933                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1934            if (p != null) {
1935                final PackageSetting ps = (PackageSetting)p.mExtras;
1936                return ps.getGids();
1937            }
1938        }
1939        // stupid thing to indicate an error.
1940        return new int[0];
1941    }
1942
1943    static final PermissionInfo generatePermissionInfo(
1944            BasePermission bp, int flags) {
1945        if (bp.perm != null) {
1946            return PackageParser.generatePermissionInfo(bp.perm, flags);
1947        }
1948        PermissionInfo pi = new PermissionInfo();
1949        pi.name = bp.name;
1950        pi.packageName = bp.sourcePackage;
1951        pi.nonLocalizedLabel = bp.name;
1952        pi.protectionLevel = bp.protectionLevel;
1953        return pi;
1954    }
1955
1956    @Override
1957    public PermissionInfo getPermissionInfo(String name, int flags) {
1958        // reader
1959        synchronized (mPackages) {
1960            final BasePermission p = mSettings.mPermissions.get(name);
1961            if (p != null) {
1962                return generatePermissionInfo(p, flags);
1963            }
1964            return null;
1965        }
1966    }
1967
1968    @Override
1969    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1970        // reader
1971        synchronized (mPackages) {
1972            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1973            for (BasePermission p : mSettings.mPermissions.values()) {
1974                if (group == null) {
1975                    if (p.perm == null || p.perm.info.group == null) {
1976                        out.add(generatePermissionInfo(p, flags));
1977                    }
1978                } else {
1979                    if (p.perm != null && group.equals(p.perm.info.group)) {
1980                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1981                    }
1982                }
1983            }
1984
1985            if (out.size() > 0) {
1986                return out;
1987            }
1988            return mPermissionGroups.containsKey(group) ? out : null;
1989        }
1990    }
1991
1992    @Override
1993    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1994        // reader
1995        synchronized (mPackages) {
1996            return PackageParser.generatePermissionGroupInfo(
1997                    mPermissionGroups.get(name), flags);
1998        }
1999    }
2000
2001    @Override
2002    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2003        // reader
2004        synchronized (mPackages) {
2005            final int N = mPermissionGroups.size();
2006            ArrayList<PermissionGroupInfo> out
2007                    = new ArrayList<PermissionGroupInfo>(N);
2008            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2009                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2010            }
2011            return out;
2012        }
2013    }
2014
2015    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2016            int userId) {
2017        if (!sUserManager.exists(userId)) return null;
2018        PackageSetting ps = mSettings.mPackages.get(packageName);
2019        if (ps != null) {
2020            if (ps.pkg == null) {
2021                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2022                        flags, userId);
2023                if (pInfo != null) {
2024                    return pInfo.applicationInfo;
2025                }
2026                return null;
2027            }
2028            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2029                    ps.readUserState(userId), userId);
2030        }
2031        return null;
2032    }
2033
2034    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2035            int userId) {
2036        if (!sUserManager.exists(userId)) return null;
2037        PackageSetting ps = mSettings.mPackages.get(packageName);
2038        if (ps != null) {
2039            PackageParser.Package pkg = ps.pkg;
2040            if (pkg == null) {
2041                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2042                    return null;
2043                }
2044                // Only data remains, so we aren't worried about code paths
2045                pkg = new PackageParser.Package(packageName);
2046                pkg.applicationInfo.packageName = packageName;
2047                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2048                pkg.applicationInfo.dataDir =
2049                        getDataPathForPackage(packageName, 0).getPath();
2050                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2051                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2052            }
2053            return generatePackageInfo(pkg, flags, userId);
2054        }
2055        return null;
2056    }
2057
2058    @Override
2059    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2060        if (!sUserManager.exists(userId)) return null;
2061        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2062        // writer
2063        synchronized (mPackages) {
2064            PackageParser.Package p = mPackages.get(packageName);
2065            if (DEBUG_PACKAGE_INFO) Log.v(
2066                    TAG, "getApplicationInfo " + packageName
2067                    + ": " + p);
2068            if (p != null) {
2069                PackageSetting ps = mSettings.mPackages.get(packageName);
2070                if (ps == null) return null;
2071                // Note: isEnabledLP() does not apply here - always return info
2072                return PackageParser.generateApplicationInfo(
2073                        p, flags, ps.readUserState(userId), userId);
2074            }
2075            if ("android".equals(packageName)||"system".equals(packageName)) {
2076                return mAndroidApplication;
2077            }
2078            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2079                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2080            }
2081        }
2082        return null;
2083    }
2084
2085
2086    @Override
2087    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2088        mContext.enforceCallingOrSelfPermission(
2089                android.Manifest.permission.CLEAR_APP_CACHE, null);
2090        // Queue up an async operation since clearing cache may take a little while.
2091        mHandler.post(new Runnable() {
2092            public void run() {
2093                mHandler.removeCallbacks(this);
2094                int retCode = -1;
2095                synchronized (mInstallLock) {
2096                    retCode = mInstaller.freeCache(freeStorageSize);
2097                    if (retCode < 0) {
2098                        Slog.w(TAG, "Couldn't clear application caches");
2099                    }
2100                }
2101                if (observer != null) {
2102                    try {
2103                        observer.onRemoveCompleted(null, (retCode >= 0));
2104                    } catch (RemoteException e) {
2105                        Slog.w(TAG, "RemoveException when invoking call back");
2106                    }
2107                }
2108            }
2109        });
2110    }
2111
2112    @Override
2113    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2114        mContext.enforceCallingOrSelfPermission(
2115                android.Manifest.permission.CLEAR_APP_CACHE, null);
2116        // Queue up an async operation since clearing cache may take a little while.
2117        mHandler.post(new Runnable() {
2118            public void run() {
2119                mHandler.removeCallbacks(this);
2120                int retCode = -1;
2121                synchronized (mInstallLock) {
2122                    retCode = mInstaller.freeCache(freeStorageSize);
2123                    if (retCode < 0) {
2124                        Slog.w(TAG, "Couldn't clear application caches");
2125                    }
2126                }
2127                if(pi != null) {
2128                    try {
2129                        // Callback via pending intent
2130                        int code = (retCode >= 0) ? 1 : 0;
2131                        pi.sendIntent(null, code, null,
2132                                null, null);
2133                    } catch (SendIntentException e1) {
2134                        Slog.i(TAG, "Failed to send pending intent");
2135                    }
2136                }
2137            }
2138        });
2139    }
2140
2141    void freeStorage(long freeStorageSize) throws IOException {
2142        synchronized (mInstallLock) {
2143            if (mInstaller.freeCache(freeStorageSize) < 0) {
2144                throw new IOException("Failed to free enough space");
2145            }
2146        }
2147    }
2148
2149    @Override
2150    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2151        if (!sUserManager.exists(userId)) return null;
2152        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2153        synchronized (mPackages) {
2154            PackageParser.Activity a = mActivities.mActivities.get(component);
2155
2156            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2157            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2158                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2159                if (ps == null) return null;
2160                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2161                        userId);
2162            }
2163            if (mResolveComponentName.equals(component)) {
2164                return mResolveActivity;
2165            }
2166        }
2167        return null;
2168    }
2169
2170    @Override
2171    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2172            String resolvedType) {
2173        synchronized (mPackages) {
2174            PackageParser.Activity a = mActivities.mActivities.get(component);
2175            if (a == null) {
2176                return false;
2177            }
2178            for (int i=0; i<a.intents.size(); i++) {
2179                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2180                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2181                    return true;
2182                }
2183            }
2184            return false;
2185        }
2186    }
2187
2188    @Override
2189    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2190        if (!sUserManager.exists(userId)) return null;
2191        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2192        synchronized (mPackages) {
2193            PackageParser.Activity a = mReceivers.mActivities.get(component);
2194            if (DEBUG_PACKAGE_INFO) Log.v(
2195                TAG, "getReceiverInfo " + component + ": " + a);
2196            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2197                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2198                if (ps == null) return null;
2199                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2200                        userId);
2201            }
2202        }
2203        return null;
2204    }
2205
2206    @Override
2207    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2208        if (!sUserManager.exists(userId)) return null;
2209        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2210        synchronized (mPackages) {
2211            PackageParser.Service s = mServices.mServices.get(component);
2212            if (DEBUG_PACKAGE_INFO) Log.v(
2213                TAG, "getServiceInfo " + component + ": " + s);
2214            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2215                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2216                if (ps == null) return null;
2217                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2218                        userId);
2219            }
2220        }
2221        return null;
2222    }
2223
2224    @Override
2225    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2226        if (!sUserManager.exists(userId)) return null;
2227        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2228        synchronized (mPackages) {
2229            PackageParser.Provider p = mProviders.mProviders.get(component);
2230            if (DEBUG_PACKAGE_INFO) Log.v(
2231                TAG, "getProviderInfo " + component + ": " + p);
2232            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2233                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2234                if (ps == null) return null;
2235                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2236                        userId);
2237            }
2238        }
2239        return null;
2240    }
2241
2242    @Override
2243    public String[] getSystemSharedLibraryNames() {
2244        Set<String> libSet;
2245        synchronized (mPackages) {
2246            libSet = mSharedLibraries.keySet();
2247            int size = libSet.size();
2248            if (size > 0) {
2249                String[] libs = new String[size];
2250                libSet.toArray(libs);
2251                return libs;
2252            }
2253        }
2254        return null;
2255    }
2256
2257    @Override
2258    public FeatureInfo[] getSystemAvailableFeatures() {
2259        Collection<FeatureInfo> featSet;
2260        synchronized (mPackages) {
2261            featSet = mAvailableFeatures.values();
2262            int size = featSet.size();
2263            if (size > 0) {
2264                FeatureInfo[] features = new FeatureInfo[size+1];
2265                featSet.toArray(features);
2266                FeatureInfo fi = new FeatureInfo();
2267                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2268                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2269                features[size] = fi;
2270                return features;
2271            }
2272        }
2273        return null;
2274    }
2275
2276    @Override
2277    public boolean hasSystemFeature(String name) {
2278        synchronized (mPackages) {
2279            return mAvailableFeatures.containsKey(name);
2280        }
2281    }
2282
2283    private void checkValidCaller(int uid, int userId) {
2284        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2285            return;
2286
2287        throw new SecurityException("Caller uid=" + uid
2288                + " is not privileged to communicate with user=" + userId);
2289    }
2290
2291    @Override
2292    public int checkPermission(String permName, String pkgName) {
2293        synchronized (mPackages) {
2294            PackageParser.Package p = mPackages.get(pkgName);
2295            if (p != null && p.mExtras != null) {
2296                PackageSetting ps = (PackageSetting)p.mExtras;
2297                if (ps.sharedUser != null) {
2298                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2299                        return PackageManager.PERMISSION_GRANTED;
2300                    }
2301                } else if (ps.grantedPermissions.contains(permName)) {
2302                    return PackageManager.PERMISSION_GRANTED;
2303                }
2304            }
2305        }
2306        return PackageManager.PERMISSION_DENIED;
2307    }
2308
2309    @Override
2310    public int checkUidPermission(String permName, int uid) {
2311        synchronized (mPackages) {
2312            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2313            if (obj != null) {
2314                GrantedPermissions gp = (GrantedPermissions)obj;
2315                if (gp.grantedPermissions.contains(permName)) {
2316                    return PackageManager.PERMISSION_GRANTED;
2317                }
2318            } else {
2319                HashSet<String> perms = mSystemPermissions.get(uid);
2320                if (perms != null && perms.contains(permName)) {
2321                    return PackageManager.PERMISSION_GRANTED;
2322                }
2323            }
2324        }
2325        return PackageManager.PERMISSION_DENIED;
2326    }
2327
2328    /**
2329     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2330     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2331     * @param message the message to log on security exception
2332     */
2333    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2334            String message) {
2335        if (userId < 0) {
2336            throw new IllegalArgumentException("Invalid userId " + userId);
2337        }
2338        if (userId == UserHandle.getUserId(callingUid)) return;
2339        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2340            if (requireFullPermission) {
2341                mContext.enforceCallingOrSelfPermission(
2342                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2343            } else {
2344                try {
2345                    mContext.enforceCallingOrSelfPermission(
2346                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2347                } catch (SecurityException se) {
2348                    mContext.enforceCallingOrSelfPermission(
2349                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2350                }
2351            }
2352        }
2353    }
2354
2355    private BasePermission findPermissionTreeLP(String permName) {
2356        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2357            if (permName.startsWith(bp.name) &&
2358                    permName.length() > bp.name.length() &&
2359                    permName.charAt(bp.name.length()) == '.') {
2360                return bp;
2361            }
2362        }
2363        return null;
2364    }
2365
2366    private BasePermission checkPermissionTreeLP(String permName) {
2367        if (permName != null) {
2368            BasePermission bp = findPermissionTreeLP(permName);
2369            if (bp != null) {
2370                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2371                    return bp;
2372                }
2373                throw new SecurityException("Calling uid "
2374                        + Binder.getCallingUid()
2375                        + " is not allowed to add to permission tree "
2376                        + bp.name + " owned by uid " + bp.uid);
2377            }
2378        }
2379        throw new SecurityException("No permission tree found for " + permName);
2380    }
2381
2382    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2383        if (s1 == null) {
2384            return s2 == null;
2385        }
2386        if (s2 == null) {
2387            return false;
2388        }
2389        if (s1.getClass() != s2.getClass()) {
2390            return false;
2391        }
2392        return s1.equals(s2);
2393    }
2394
2395    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2396        if (pi1.icon != pi2.icon) return false;
2397        if (pi1.logo != pi2.logo) return false;
2398        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2399        if (!compareStrings(pi1.name, pi2.name)) return false;
2400        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2401        // We'll take care of setting this one.
2402        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2403        // These are not currently stored in settings.
2404        //if (!compareStrings(pi1.group, pi2.group)) return false;
2405        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2406        //if (pi1.labelRes != pi2.labelRes) return false;
2407        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2408        return true;
2409    }
2410
2411    int permissionInfoFootprint(PermissionInfo info) {
2412        int size = info.name.length();
2413        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2414        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2415        return size;
2416    }
2417
2418    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2419        int size = 0;
2420        for (BasePermission perm : mSettings.mPermissions.values()) {
2421            if (perm.uid == tree.uid) {
2422                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2423            }
2424        }
2425        return size;
2426    }
2427
2428    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2429        // We calculate the max size of permissions defined by this uid and throw
2430        // if that plus the size of 'info' would exceed our stated maximum.
2431        if (tree.uid != Process.SYSTEM_UID) {
2432            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2433            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2434                throw new SecurityException("Permission tree size cap exceeded");
2435            }
2436        }
2437    }
2438
2439    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2440        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2441            throw new SecurityException("Label must be specified in permission");
2442        }
2443        BasePermission tree = checkPermissionTreeLP(info.name);
2444        BasePermission bp = mSettings.mPermissions.get(info.name);
2445        boolean added = bp == null;
2446        boolean changed = true;
2447        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2448        if (added) {
2449            enforcePermissionCapLocked(info, tree);
2450            bp = new BasePermission(info.name, tree.sourcePackage,
2451                    BasePermission.TYPE_DYNAMIC);
2452        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2453            throw new SecurityException(
2454                    "Not allowed to modify non-dynamic permission "
2455                    + info.name);
2456        } else {
2457            if (bp.protectionLevel == fixedLevel
2458                    && bp.perm.owner.equals(tree.perm.owner)
2459                    && bp.uid == tree.uid
2460                    && comparePermissionInfos(bp.perm.info, info)) {
2461                changed = false;
2462            }
2463        }
2464        bp.protectionLevel = fixedLevel;
2465        info = new PermissionInfo(info);
2466        info.protectionLevel = fixedLevel;
2467        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2468        bp.perm.info.packageName = tree.perm.info.packageName;
2469        bp.uid = tree.uid;
2470        if (added) {
2471            mSettings.mPermissions.put(info.name, bp);
2472        }
2473        if (changed) {
2474            if (!async) {
2475                mSettings.writeLPr();
2476            } else {
2477                scheduleWriteSettingsLocked();
2478            }
2479        }
2480        return added;
2481    }
2482
2483    @Override
2484    public boolean addPermission(PermissionInfo info) {
2485        synchronized (mPackages) {
2486            return addPermissionLocked(info, false);
2487        }
2488    }
2489
2490    @Override
2491    public boolean addPermissionAsync(PermissionInfo info) {
2492        synchronized (mPackages) {
2493            return addPermissionLocked(info, true);
2494        }
2495    }
2496
2497    @Override
2498    public void removePermission(String name) {
2499        synchronized (mPackages) {
2500            checkPermissionTreeLP(name);
2501            BasePermission bp = mSettings.mPermissions.get(name);
2502            if (bp != null) {
2503                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2504                    throw new SecurityException(
2505                            "Not allowed to modify non-dynamic permission "
2506                            + name);
2507                }
2508                mSettings.mPermissions.remove(name);
2509                mSettings.writeLPr();
2510            }
2511        }
2512    }
2513
2514    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2515        int index = pkg.requestedPermissions.indexOf(bp.name);
2516        if (index == -1) {
2517            throw new SecurityException("Package " + pkg.packageName
2518                    + " has not requested permission " + bp.name);
2519        }
2520        boolean isNormal =
2521                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2522                        == PermissionInfo.PROTECTION_NORMAL);
2523        boolean isDangerous =
2524                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2525                        == PermissionInfo.PROTECTION_DANGEROUS);
2526        boolean isDevelopment =
2527                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2528
2529        if (!isNormal && !isDangerous && !isDevelopment) {
2530            throw new SecurityException("Permission " + bp.name
2531                    + " is not a changeable permission type");
2532        }
2533
2534        if (isNormal || isDangerous) {
2535            if (pkg.requestedPermissionsRequired.get(index)) {
2536                throw new SecurityException("Can't change " + bp.name
2537                        + ". It is required by the application");
2538            }
2539        }
2540    }
2541
2542    @Override
2543    public void grantPermission(String packageName, String permissionName) {
2544        mContext.enforceCallingOrSelfPermission(
2545                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2546        synchronized (mPackages) {
2547            final PackageParser.Package pkg = mPackages.get(packageName);
2548            if (pkg == null) {
2549                throw new IllegalArgumentException("Unknown package: " + packageName);
2550            }
2551            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2552            if (bp == null) {
2553                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2554            }
2555
2556            checkGrantRevokePermissions(pkg, bp);
2557
2558            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2559            if (ps == null) {
2560                return;
2561            }
2562            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2563            if (gp.grantedPermissions.add(permissionName)) {
2564                if (ps.haveGids) {
2565                    gp.gids = appendInts(gp.gids, bp.gids);
2566                }
2567                mSettings.writeLPr();
2568            }
2569        }
2570    }
2571
2572    @Override
2573    public void revokePermission(String packageName, String permissionName) {
2574        int changedAppId = -1;
2575
2576        synchronized (mPackages) {
2577            final PackageParser.Package pkg = mPackages.get(packageName);
2578            if (pkg == null) {
2579                throw new IllegalArgumentException("Unknown package: " + packageName);
2580            }
2581            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2582                mContext.enforceCallingOrSelfPermission(
2583                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2584            }
2585            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2586            if (bp == null) {
2587                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2588            }
2589
2590            checkGrantRevokePermissions(pkg, bp);
2591
2592            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2593            if (ps == null) {
2594                return;
2595            }
2596            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2597            if (gp.grantedPermissions.remove(permissionName)) {
2598                gp.grantedPermissions.remove(permissionName);
2599                if (ps.haveGids) {
2600                    gp.gids = removeInts(gp.gids, bp.gids);
2601                }
2602                mSettings.writeLPr();
2603                changedAppId = ps.appId;
2604            }
2605        }
2606
2607        if (changedAppId >= 0) {
2608            // We changed the perm on someone, kill its processes.
2609            IActivityManager am = ActivityManagerNative.getDefault();
2610            if (am != null) {
2611                final int callingUserId = UserHandle.getCallingUserId();
2612                final long ident = Binder.clearCallingIdentity();
2613                try {
2614                    //XXX we should only revoke for the calling user's app permissions,
2615                    // but for now we impact all users.
2616                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2617                    //        "revoke " + permissionName);
2618                    int[] users = sUserManager.getUserIds();
2619                    for (int user : users) {
2620                        am.killUid(UserHandle.getUid(user, changedAppId),
2621                                "revoke " + permissionName);
2622                    }
2623                } catch (RemoteException e) {
2624                } finally {
2625                    Binder.restoreCallingIdentity(ident);
2626                }
2627            }
2628        }
2629    }
2630
2631    @Override
2632    public boolean isProtectedBroadcast(String actionName) {
2633        synchronized (mPackages) {
2634            return mProtectedBroadcasts.contains(actionName);
2635        }
2636    }
2637
2638    @Override
2639    public int checkSignatures(String pkg1, String pkg2) {
2640        synchronized (mPackages) {
2641            final PackageParser.Package p1 = mPackages.get(pkg1);
2642            final PackageParser.Package p2 = mPackages.get(pkg2);
2643            if (p1 == null || p1.mExtras == null
2644                    || p2 == null || p2.mExtras == null) {
2645                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2646            }
2647            return compareSignatures(p1.mSignatures, p2.mSignatures);
2648        }
2649    }
2650
2651    @Override
2652    public int checkUidSignatures(int uid1, int uid2) {
2653        // Map to base uids.
2654        uid1 = UserHandle.getAppId(uid1);
2655        uid2 = UserHandle.getAppId(uid2);
2656        // reader
2657        synchronized (mPackages) {
2658            Signature[] s1;
2659            Signature[] s2;
2660            Object obj = mSettings.getUserIdLPr(uid1);
2661            if (obj != null) {
2662                if (obj instanceof SharedUserSetting) {
2663                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2664                } else if (obj instanceof PackageSetting) {
2665                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2666                } else {
2667                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2668                }
2669            } else {
2670                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2671            }
2672            obj = mSettings.getUserIdLPr(uid2);
2673            if (obj != null) {
2674                if (obj instanceof SharedUserSetting) {
2675                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2676                } else if (obj instanceof PackageSetting) {
2677                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2678                } else {
2679                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2680                }
2681            } else {
2682                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2683            }
2684            return compareSignatures(s1, s2);
2685        }
2686    }
2687
2688    /**
2689     * Compares two sets of signatures. Returns:
2690     * <br />
2691     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2692     * <br />
2693     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2694     * <br />
2695     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2696     * <br />
2697     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2698     * <br />
2699     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2700     */
2701    static int compareSignatures(Signature[] s1, Signature[] s2) {
2702        if (s1 == null) {
2703            return s2 == null
2704                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2705                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2706        }
2707
2708        if (s2 == null) {
2709            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2710        }
2711
2712        if (s1.length != s2.length) {
2713            return PackageManager.SIGNATURE_NO_MATCH;
2714        }
2715
2716        // Since both signature sets are of size 1, we can compare without HashSets.
2717        if (s1.length == 1) {
2718            return s1[0].equals(s2[0]) ?
2719                    PackageManager.SIGNATURE_MATCH :
2720                    PackageManager.SIGNATURE_NO_MATCH;
2721        }
2722
2723        HashSet<Signature> set1 = new HashSet<Signature>();
2724        for (Signature sig : s1) {
2725            set1.add(sig);
2726        }
2727        HashSet<Signature> set2 = new HashSet<Signature>();
2728        for (Signature sig : s2) {
2729            set2.add(sig);
2730        }
2731        // Make sure s2 contains all signatures in s1.
2732        if (set1.equals(set2)) {
2733            return PackageManager.SIGNATURE_MATCH;
2734        }
2735        return PackageManager.SIGNATURE_NO_MATCH;
2736    }
2737
2738    /**
2739     * If the database version for this type of package (internal storage or
2740     * external storage) is less than the version where package signatures
2741     * were updated, return true.
2742     */
2743    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2744        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2745                DatabaseVersion.SIGNATURE_END_ENTITY))
2746                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2747                        DatabaseVersion.SIGNATURE_END_ENTITY));
2748    }
2749
2750    /**
2751     * Used for backward compatibility to make sure any packages with
2752     * certificate chains get upgraded to the new style. {@code existingSigs}
2753     * will be in the old format (since they were stored on disk from before the
2754     * system upgrade) and {@code scannedSigs} will be in the newer format.
2755     */
2756    private int compareSignaturesCompat(PackageSignatures existingSigs,
2757            PackageParser.Package scannedPkg) {
2758        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2759            return PackageManager.SIGNATURE_NO_MATCH;
2760        }
2761
2762        HashSet<Signature> existingSet = new HashSet<Signature>();
2763        for (Signature sig : existingSigs.mSignatures) {
2764            existingSet.add(sig);
2765        }
2766        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2767        for (Signature sig : scannedPkg.mSignatures) {
2768            try {
2769                Signature[] chainSignatures = sig.getChainSignatures();
2770                for (Signature chainSig : chainSignatures) {
2771                    scannedCompatSet.add(chainSig);
2772                }
2773            } catch (CertificateEncodingException e) {
2774                scannedCompatSet.add(sig);
2775            }
2776        }
2777        /*
2778         * Make sure the expanded scanned set contains all signatures in the
2779         * existing one.
2780         */
2781        if (scannedCompatSet.equals(existingSet)) {
2782            // Migrate the old signatures to the new scheme.
2783            existingSigs.assignSignatures(scannedPkg.mSignatures);
2784            // The new KeySets will be re-added later in the scanning process.
2785            synchronized (mPackages) {
2786                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2787            }
2788            return PackageManager.SIGNATURE_MATCH;
2789        }
2790        return PackageManager.SIGNATURE_NO_MATCH;
2791    }
2792
2793    @Override
2794    public String[] getPackagesForUid(int uid) {
2795        uid = UserHandle.getAppId(uid);
2796        // reader
2797        synchronized (mPackages) {
2798            Object obj = mSettings.getUserIdLPr(uid);
2799            if (obj instanceof SharedUserSetting) {
2800                final SharedUserSetting sus = (SharedUserSetting) obj;
2801                final int N = sus.packages.size();
2802                final String[] res = new String[N];
2803                final Iterator<PackageSetting> it = sus.packages.iterator();
2804                int i = 0;
2805                while (it.hasNext()) {
2806                    res[i++] = it.next().name;
2807                }
2808                return res;
2809            } else if (obj instanceof PackageSetting) {
2810                final PackageSetting ps = (PackageSetting) obj;
2811                return new String[] { ps.name };
2812            }
2813        }
2814        return null;
2815    }
2816
2817    @Override
2818    public String getNameForUid(int uid) {
2819        // reader
2820        synchronized (mPackages) {
2821            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2822            if (obj instanceof SharedUserSetting) {
2823                final SharedUserSetting sus = (SharedUserSetting) obj;
2824                return sus.name + ":" + sus.userId;
2825            } else if (obj instanceof PackageSetting) {
2826                final PackageSetting ps = (PackageSetting) obj;
2827                return ps.name;
2828            }
2829        }
2830        return null;
2831    }
2832
2833    @Override
2834    public int getUidForSharedUser(String sharedUserName) {
2835        if(sharedUserName == null) {
2836            return -1;
2837        }
2838        // reader
2839        synchronized (mPackages) {
2840            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2841            if (suid == null) {
2842                return -1;
2843            }
2844            return suid.userId;
2845        }
2846    }
2847
2848    @Override
2849    public int getFlagsForUid(int uid) {
2850        synchronized (mPackages) {
2851            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2852            if (obj instanceof SharedUserSetting) {
2853                final SharedUserSetting sus = (SharedUserSetting) obj;
2854                return sus.pkgFlags;
2855            } else if (obj instanceof PackageSetting) {
2856                final PackageSetting ps = (PackageSetting) obj;
2857                return ps.pkgFlags;
2858            }
2859        }
2860        return 0;
2861    }
2862
2863    @Override
2864    public String[] getAppOpPermissionPackages(String permissionName) {
2865        synchronized (mPackages) {
2866            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2867            if (pkgs == null) {
2868                return null;
2869            }
2870            return pkgs.toArray(new String[pkgs.size()]);
2871        }
2872    }
2873
2874    @Override
2875    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2876            int flags, int userId) {
2877        if (!sUserManager.exists(userId)) return null;
2878        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2879        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2880        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2881    }
2882
2883    @Override
2884    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2885            IntentFilter filter, int match, ComponentName activity) {
2886        final int userId = UserHandle.getCallingUserId();
2887        if (DEBUG_PREFERRED) {
2888            Log.v(TAG, "setLastChosenActivity intent=" + intent
2889                + " resolvedType=" + resolvedType
2890                + " flags=" + flags
2891                + " filter=" + filter
2892                + " match=" + match
2893                + " activity=" + activity);
2894            filter.dump(new PrintStreamPrinter(System.out), "    ");
2895        }
2896        intent.setComponent(null);
2897        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2898        // Find any earlier preferred or last chosen entries and nuke them
2899        findPreferredActivity(intent, resolvedType,
2900                flags, query, 0, false, true, false, userId);
2901        // Add the new activity as the last chosen for this filter
2902        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2903    }
2904
2905    @Override
2906    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2907        final int userId = UserHandle.getCallingUserId();
2908        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2909        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2910        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2911                false, false, false, userId);
2912    }
2913
2914    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2915            int flags, List<ResolveInfo> query, int userId) {
2916        if (query != null) {
2917            final int N = query.size();
2918            if (N == 1) {
2919                return query.get(0);
2920            } else if (N > 1) {
2921                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2922                // If there is more than one activity with the same priority,
2923                // then let the user decide between them.
2924                ResolveInfo r0 = query.get(0);
2925                ResolveInfo r1 = query.get(1);
2926                if (DEBUG_INTENT_MATCHING || debug) {
2927                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2928                            + r1.activityInfo.name + "=" + r1.priority);
2929                }
2930                // If the first activity has a higher priority, or a different
2931                // default, then it is always desireable to pick it.
2932                if (r0.priority != r1.priority
2933                        || r0.preferredOrder != r1.preferredOrder
2934                        || r0.isDefault != r1.isDefault) {
2935                    return query.get(0);
2936                }
2937                // If we have saved a preference for a preferred activity for
2938                // this Intent, use that.
2939                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2940                        flags, query, r0.priority, true, false, debug, userId);
2941                if (ri != null) {
2942                    return ri;
2943                }
2944                if (userId != 0) {
2945                    ri = new ResolveInfo(mResolveInfo);
2946                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2947                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2948                            ri.activityInfo.applicationInfo);
2949                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2950                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2951                    return ri;
2952                }
2953                return mResolveInfo;
2954            }
2955        }
2956        return null;
2957    }
2958
2959    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2960            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2961        final int N = query.size();
2962        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2963                .get(userId);
2964        // Get the list of persistent preferred activities that handle the intent
2965        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2966        List<PersistentPreferredActivity> pprefs = ppir != null
2967                ? ppir.queryIntent(intent, resolvedType,
2968                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2969                : null;
2970        if (pprefs != null && pprefs.size() > 0) {
2971            final int M = pprefs.size();
2972            for (int i=0; i<M; i++) {
2973                final PersistentPreferredActivity ppa = pprefs.get(i);
2974                if (DEBUG_PREFERRED || debug) {
2975                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2976                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2977                            + "\n  component=" + ppa.mComponent);
2978                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2979                }
2980                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2981                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2982                if (DEBUG_PREFERRED || debug) {
2983                    Slog.v(TAG, "Found persistent preferred activity:");
2984                    if (ai != null) {
2985                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2986                    } else {
2987                        Slog.v(TAG, "  null");
2988                    }
2989                }
2990                if (ai == null) {
2991                    // This previously registered persistent preferred activity
2992                    // component is no longer known. Ignore it and do NOT remove it.
2993                    continue;
2994                }
2995                for (int j=0; j<N; j++) {
2996                    final ResolveInfo ri = query.get(j);
2997                    if (!ri.activityInfo.applicationInfo.packageName
2998                            .equals(ai.applicationInfo.packageName)) {
2999                        continue;
3000                    }
3001                    if (!ri.activityInfo.name.equals(ai.name)) {
3002                        continue;
3003                    }
3004                    //  Found a persistent preference that can handle the intent.
3005                    if (DEBUG_PREFERRED || debug) {
3006                        Slog.v(TAG, "Returning persistent preferred activity: " +
3007                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3008                    }
3009                    return ri;
3010                }
3011            }
3012        }
3013        return null;
3014    }
3015
3016    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3017            List<ResolveInfo> query, int priority, boolean always,
3018            boolean removeMatches, boolean debug, int userId) {
3019        if (!sUserManager.exists(userId)) return null;
3020        // writer
3021        synchronized (mPackages) {
3022            if (intent.getSelector() != null) {
3023                intent = intent.getSelector();
3024            }
3025            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3026
3027            // Try to find a matching persistent preferred activity.
3028            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3029                    debug, userId);
3030
3031            // If a persistent preferred activity matched, use it.
3032            if (pri != null) {
3033                return pri;
3034            }
3035
3036            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3037            // Get the list of preferred activities that handle the intent
3038            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3039            List<PreferredActivity> prefs = pir != null
3040                    ? pir.queryIntent(intent, resolvedType,
3041                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3042                    : null;
3043            if (prefs != null && prefs.size() > 0) {
3044                // First figure out how good the original match set is.
3045                // We will only allow preferred activities that came
3046                // from the same match quality.
3047                int match = 0;
3048
3049                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3050
3051                final int N = query.size();
3052                for (int j=0; j<N; j++) {
3053                    final ResolveInfo ri = query.get(j);
3054                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3055                            + ": 0x" + Integer.toHexString(match));
3056                    if (ri.match > match) {
3057                        match = ri.match;
3058                    }
3059                }
3060
3061                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3062                        + Integer.toHexString(match));
3063
3064                match &= IntentFilter.MATCH_CATEGORY_MASK;
3065                final int M = prefs.size();
3066                for (int i=0; i<M; i++) {
3067                    final PreferredActivity pa = prefs.get(i);
3068                    if (DEBUG_PREFERRED || debug) {
3069                        Slog.v(TAG, "Checking PreferredActivity ds="
3070                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3071                                + "\n  component=" + pa.mPref.mComponent);
3072                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3073                    }
3074                    if (pa.mPref.mMatch != match) {
3075                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3076                                + Integer.toHexString(pa.mPref.mMatch));
3077                        continue;
3078                    }
3079                    // If it's not an "always" type preferred activity and that's what we're
3080                    // looking for, skip it.
3081                    if (always && !pa.mPref.mAlways) {
3082                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3083                        continue;
3084                    }
3085                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3086                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3087                    if (DEBUG_PREFERRED || debug) {
3088                        Slog.v(TAG, "Found preferred activity:");
3089                        if (ai != null) {
3090                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3091                        } else {
3092                            Slog.v(TAG, "  null");
3093                        }
3094                    }
3095                    if (ai == null) {
3096                        // This previously registered preferred activity
3097                        // component is no longer known.  Most likely an update
3098                        // to the app was installed and in the new version this
3099                        // component no longer exists.  Clean it up by removing
3100                        // it from the preferred activities list, and skip it.
3101                        Slog.w(TAG, "Removing dangling preferred activity: "
3102                                + pa.mPref.mComponent);
3103                        pir.removeFilter(pa);
3104                        continue;
3105                    }
3106                    for (int j=0; j<N; j++) {
3107                        final ResolveInfo ri = query.get(j);
3108                        if (!ri.activityInfo.applicationInfo.packageName
3109                                .equals(ai.applicationInfo.packageName)) {
3110                            continue;
3111                        }
3112                        if (!ri.activityInfo.name.equals(ai.name)) {
3113                            continue;
3114                        }
3115
3116                        if (removeMatches) {
3117                            pir.removeFilter(pa);
3118                            if (DEBUG_PREFERRED) {
3119                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3120                            }
3121                            break;
3122                        }
3123
3124                        // Okay we found a previously set preferred or last chosen app.
3125                        // If the result set is different from when this
3126                        // was created, we need to clear it and re-ask the
3127                        // user their preference, if we're looking for an "always" type entry.
3128                        if (always && !pa.mPref.sameSet(query, priority)) {
3129                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3130                                    + intent + " type " + resolvedType);
3131                            if (DEBUG_PREFERRED) {
3132                                Slog.v(TAG, "Removing preferred activity since set changed "
3133                                        + pa.mPref.mComponent);
3134                            }
3135                            pir.removeFilter(pa);
3136                            // Re-add the filter as a "last chosen" entry (!always)
3137                            PreferredActivity lastChosen = new PreferredActivity(
3138                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3139                            pir.addFilter(lastChosen);
3140                            mSettings.writePackageRestrictionsLPr(userId);
3141                            return null;
3142                        }
3143
3144                        // Yay! Either the set matched or we're looking for the last chosen
3145                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3146                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3147                        mSettings.writePackageRestrictionsLPr(userId);
3148                        return ri;
3149                    }
3150                }
3151            }
3152            mSettings.writePackageRestrictionsLPr(userId);
3153        }
3154        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3155        return null;
3156    }
3157
3158    /*
3159     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3160     */
3161    @Override
3162    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3163            int targetUserId) {
3164        mContext.enforceCallingOrSelfPermission(
3165                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3166        List<CrossProfileIntentFilter> matches =
3167                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3168        if (matches != null) {
3169            int size = matches.size();
3170            for (int i = 0; i < size; i++) {
3171                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3172            }
3173        }
3174
3175        ArrayList<String> packageNames = null;
3176        SparseArray<ArrayList<String>> fromSource =
3177                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3178        if (fromSource != null) {
3179            packageNames = fromSource.get(targetUserId);
3180        }
3181        if (packageNames.contains(intent.getPackage())) {
3182            return true;
3183        }
3184        // We need the package name, so we try to resolve with the loosest flags possible
3185        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3186                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3187        int count = resolveInfos.size();
3188        for (int i = 0; i < count; i++) {
3189            ResolveInfo resolveInfo = resolveInfos.get(i);
3190            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3191                return true;
3192            }
3193        }
3194        return false;
3195    }
3196
3197    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3198            String resolvedType, int userId) {
3199        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3200        if (resolver != null) {
3201            return resolver.queryIntent(intent, resolvedType, false, userId);
3202        }
3203        return null;
3204    }
3205
3206    @Override
3207    public List<ResolveInfo> queryIntentActivities(Intent intent,
3208            String resolvedType, int flags, int userId) {
3209        if (!sUserManager.exists(userId)) return Collections.emptyList();
3210        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3211        ComponentName comp = intent.getComponent();
3212        if (comp == null) {
3213            if (intent.getSelector() != null) {
3214                intent = intent.getSelector();
3215                comp = intent.getComponent();
3216            }
3217        }
3218
3219        if (comp != null) {
3220            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3221            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3222            if (ai != null) {
3223                final ResolveInfo ri = new ResolveInfo();
3224                ri.activityInfo = ai;
3225                list.add(ri);
3226            }
3227            return list;
3228        }
3229
3230        // reader
3231        synchronized (mPackages) {
3232            final String pkgName = intent.getPackage();
3233            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3234            if (pkgName == null) {
3235                ResolveInfo resolveInfo = null;
3236                if (queryCrossProfile) {
3237                    // Check if the intent needs to be forwarded to another user for this package
3238                    ArrayList<ResolveInfo> crossProfileResult =
3239                            queryIntentActivitiesCrossProfilePackage(
3240                                    intent, resolvedType, flags, userId);
3241                    if (!crossProfileResult.isEmpty()) {
3242                        // Skip the current profile
3243                        return crossProfileResult;
3244                    }
3245                    List<CrossProfileIntentFilter> matchingFilters =
3246                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3247                    // Check for results that need to skip the current profile.
3248                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3249                            resolvedType, flags, userId);
3250                    if (resolveInfo != null) {
3251                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3252                        result.add(resolveInfo);
3253                        return result;
3254                    }
3255                    // Check for cross profile results.
3256                    resolveInfo = queryCrossProfileIntents(
3257                            matchingFilters, intent, resolvedType, flags, userId);
3258                }
3259                // Check for results in the current profile.
3260                List<ResolveInfo> result = mActivities.queryIntent(
3261                        intent, resolvedType, flags, userId);
3262                if (resolveInfo != null) {
3263                    result.add(resolveInfo);
3264                }
3265                return result;
3266            }
3267            final PackageParser.Package pkg = mPackages.get(pkgName);
3268            if (pkg != null) {
3269                if (queryCrossProfile) {
3270                    ArrayList<ResolveInfo> crossProfileResult =
3271                            queryIntentActivitiesCrossProfilePackage(
3272                                    intent, resolvedType, flags, userId, pkg, pkgName);
3273                    if (!crossProfileResult.isEmpty()) {
3274                        // Skip the current profile
3275                        return crossProfileResult;
3276                    }
3277                }
3278                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3279                        pkg.activities, userId);
3280            }
3281            return new ArrayList<ResolveInfo>();
3282        }
3283    }
3284
3285    private ResolveInfo querySkipCurrentProfileIntents(
3286            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3287            int flags, int sourceUserId) {
3288        if (matchingFilters != null) {
3289            int size = matchingFilters.size();
3290            for (int i = 0; i < size; i ++) {
3291                CrossProfileIntentFilter filter = matchingFilters.get(i);
3292                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3293                    // Checking if there are activities in the target user that can handle the
3294                    // intent.
3295                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3296                            flags, sourceUserId);
3297                    if (resolveInfo != null) {
3298                        return resolveInfo;
3299                    }
3300                }
3301            }
3302        }
3303        return null;
3304    }
3305
3306    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3307            Intent intent, String resolvedType, int flags, int userId) {
3308        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3309        SparseArray<ArrayList<String>> sourceForwardingInfo =
3310                mSettings.mCrossProfilePackageInfo.get(userId);
3311        if (sourceForwardingInfo != null) {
3312            int NI = sourceForwardingInfo.size();
3313            for (int i = 0; i < NI; i++) {
3314                int targetUserId = sourceForwardingInfo.keyAt(i);
3315                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3316                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3317                        intent, resolvedType, flags, targetUserId);
3318                int NJ = resolveInfos.size();
3319                for (int j = 0; j < NJ; j++) {
3320                    ResolveInfo resolveInfo = resolveInfos.get(j);
3321                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3322                        matchingResolveInfos.add(createForwardingResolveInfo(
3323                                resolveInfo.filter, userId, targetUserId));
3324                    }
3325                }
3326            }
3327        }
3328        return matchingResolveInfos;
3329    }
3330
3331    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3332            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3333            String packageName) {
3334        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3335        SparseArray<ArrayList<String>> sourceForwardingInfo =
3336                mSettings.mCrossProfilePackageInfo.get(userId);
3337        if (sourceForwardingInfo != null) {
3338            int NI = sourceForwardingInfo.size();
3339            for (int i = 0; i < NI; i++) {
3340                int targetUserId = sourceForwardingInfo.keyAt(i);
3341                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3342                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3343                            intent, resolvedType, flags, pkg.activities, targetUserId);
3344                    int NJ = resolveInfos.size();
3345                    for (int j = 0; j < NJ; j++) {
3346                        ResolveInfo resolveInfo = resolveInfos.get(j);
3347                        matchingResolveInfos.add(createForwardingResolveInfo(
3348                                resolveInfo.filter, userId, targetUserId));
3349                    }
3350                }
3351            }
3352        }
3353        return matchingResolveInfos;
3354    }
3355
3356    // Return matching ResolveInfo if any for skip current profile intent filters.
3357    private ResolveInfo queryCrossProfileIntents(
3358            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3359            int flags, int sourceUserId) {
3360        if (matchingFilters != null) {
3361            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3362            // match the same intent. For performance reasons, it is better not to
3363            // run queryIntent twice for the same userId
3364            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3365            int size = matchingFilters.size();
3366            for (int i = 0; i < size; i++) {
3367                CrossProfileIntentFilter filter = matchingFilters.get(i);
3368                int targetUserId = filter.getTargetUserId();
3369                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3370                        && !alreadyTriedUserIds.get(targetUserId)) {
3371                    // Checking if there are activities in the target user that can handle the
3372                    // intent.
3373                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3374                            flags, sourceUserId);
3375                    if (resolveInfo != null) return resolveInfo;
3376                    alreadyTriedUserIds.put(targetUserId, true);
3377                }
3378            }
3379        }
3380        return null;
3381    }
3382
3383    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3384            String resolvedType, int flags, int sourceUserId) {
3385        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3386                resolvedType, flags, filter.getTargetUserId());
3387        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3388            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3389        }
3390        return null;
3391    }
3392
3393    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3394            int sourceUserId, int targetUserId) {
3395        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3396        String className;
3397        if (targetUserId == UserHandle.USER_OWNER) {
3398            className = FORWARD_INTENT_TO_USER_OWNER;
3399        } else {
3400            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3401        }
3402        ComponentName forwardingActivityComponentName = new ComponentName(
3403                mAndroidApplication.packageName, className);
3404        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3405                sourceUserId);
3406        if (targetUserId == UserHandle.USER_OWNER) {
3407            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3408            forwardingResolveInfo.noResourceId = true;
3409        }
3410        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3411        forwardingResolveInfo.priority = 0;
3412        forwardingResolveInfo.preferredOrder = 0;
3413        forwardingResolveInfo.match = 0;
3414        forwardingResolveInfo.isDefault = true;
3415        forwardingResolveInfo.filter = filter;
3416        forwardingResolveInfo.targetUserId = targetUserId;
3417        return forwardingResolveInfo;
3418    }
3419
3420    @Override
3421    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3422            Intent[] specifics, String[] specificTypes, Intent intent,
3423            String resolvedType, int flags, int userId) {
3424        if (!sUserManager.exists(userId)) return Collections.emptyList();
3425        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3426                "query intent activity options");
3427        final String resultsAction = intent.getAction();
3428
3429        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3430                | PackageManager.GET_RESOLVED_FILTER, userId);
3431
3432        if (DEBUG_INTENT_MATCHING) {
3433            Log.v(TAG, "Query " + intent + ": " + results);
3434        }
3435
3436        int specificsPos = 0;
3437        int N;
3438
3439        // todo: note that the algorithm used here is O(N^2).  This
3440        // isn't a problem in our current environment, but if we start running
3441        // into situations where we have more than 5 or 10 matches then this
3442        // should probably be changed to something smarter...
3443
3444        // First we go through and resolve each of the specific items
3445        // that were supplied, taking care of removing any corresponding
3446        // duplicate items in the generic resolve list.
3447        if (specifics != null) {
3448            for (int i=0; i<specifics.length; i++) {
3449                final Intent sintent = specifics[i];
3450                if (sintent == null) {
3451                    continue;
3452                }
3453
3454                if (DEBUG_INTENT_MATCHING) {
3455                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3456                }
3457
3458                String action = sintent.getAction();
3459                if (resultsAction != null && resultsAction.equals(action)) {
3460                    // If this action was explicitly requested, then don't
3461                    // remove things that have it.
3462                    action = null;
3463                }
3464
3465                ResolveInfo ri = null;
3466                ActivityInfo ai = null;
3467
3468                ComponentName comp = sintent.getComponent();
3469                if (comp == null) {
3470                    ri = resolveIntent(
3471                        sintent,
3472                        specificTypes != null ? specificTypes[i] : null,
3473                            flags, userId);
3474                    if (ri == null) {
3475                        continue;
3476                    }
3477                    if (ri == mResolveInfo) {
3478                        // ACK!  Must do something better with this.
3479                    }
3480                    ai = ri.activityInfo;
3481                    comp = new ComponentName(ai.applicationInfo.packageName,
3482                            ai.name);
3483                } else {
3484                    ai = getActivityInfo(comp, flags, userId);
3485                    if (ai == null) {
3486                        continue;
3487                    }
3488                }
3489
3490                // Look for any generic query activities that are duplicates
3491                // of this specific one, and remove them from the results.
3492                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3493                N = results.size();
3494                int j;
3495                for (j=specificsPos; j<N; j++) {
3496                    ResolveInfo sri = results.get(j);
3497                    if ((sri.activityInfo.name.equals(comp.getClassName())
3498                            && sri.activityInfo.applicationInfo.packageName.equals(
3499                                    comp.getPackageName()))
3500                        || (action != null && sri.filter.matchAction(action))) {
3501                        results.remove(j);
3502                        if (DEBUG_INTENT_MATCHING) Log.v(
3503                            TAG, "Removing duplicate item from " + j
3504                            + " due to specific " + specificsPos);
3505                        if (ri == null) {
3506                            ri = sri;
3507                        }
3508                        j--;
3509                        N--;
3510                    }
3511                }
3512
3513                // Add this specific item to its proper place.
3514                if (ri == null) {
3515                    ri = new ResolveInfo();
3516                    ri.activityInfo = ai;
3517                }
3518                results.add(specificsPos, ri);
3519                ri.specificIndex = i;
3520                specificsPos++;
3521            }
3522        }
3523
3524        // Now we go through the remaining generic results and remove any
3525        // duplicate actions that are found here.
3526        N = results.size();
3527        for (int i=specificsPos; i<N-1; i++) {
3528            final ResolveInfo rii = results.get(i);
3529            if (rii.filter == null) {
3530                continue;
3531            }
3532
3533            // Iterate over all of the actions of this result's intent
3534            // filter...  typically this should be just one.
3535            final Iterator<String> it = rii.filter.actionsIterator();
3536            if (it == null) {
3537                continue;
3538            }
3539            while (it.hasNext()) {
3540                final String action = it.next();
3541                if (resultsAction != null && resultsAction.equals(action)) {
3542                    // If this action was explicitly requested, then don't
3543                    // remove things that have it.
3544                    continue;
3545                }
3546                for (int j=i+1; j<N; j++) {
3547                    final ResolveInfo rij = results.get(j);
3548                    if (rij.filter != null && rij.filter.hasAction(action)) {
3549                        results.remove(j);
3550                        if (DEBUG_INTENT_MATCHING) Log.v(
3551                            TAG, "Removing duplicate item from " + j
3552                            + " due to action " + action + " at " + i);
3553                        j--;
3554                        N--;
3555                    }
3556                }
3557            }
3558
3559            // If the caller didn't request filter information, drop it now
3560            // so we don't have to marshall/unmarshall it.
3561            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3562                rii.filter = null;
3563            }
3564        }
3565
3566        // Filter out the caller activity if so requested.
3567        if (caller != null) {
3568            N = results.size();
3569            for (int i=0; i<N; i++) {
3570                ActivityInfo ainfo = results.get(i).activityInfo;
3571                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3572                        && caller.getClassName().equals(ainfo.name)) {
3573                    results.remove(i);
3574                    break;
3575                }
3576            }
3577        }
3578
3579        // If the caller didn't request filter information,
3580        // drop them now so we don't have to
3581        // marshall/unmarshall it.
3582        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3583            N = results.size();
3584            for (int i=0; i<N; i++) {
3585                results.get(i).filter = null;
3586            }
3587        }
3588
3589        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3590        return results;
3591    }
3592
3593    @Override
3594    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3595            int userId) {
3596        if (!sUserManager.exists(userId)) return Collections.emptyList();
3597        ComponentName comp = intent.getComponent();
3598        if (comp == null) {
3599            if (intent.getSelector() != null) {
3600                intent = intent.getSelector();
3601                comp = intent.getComponent();
3602            }
3603        }
3604        if (comp != null) {
3605            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3606            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3607            if (ai != null) {
3608                ResolveInfo ri = new ResolveInfo();
3609                ri.activityInfo = ai;
3610                list.add(ri);
3611            }
3612            return list;
3613        }
3614
3615        // reader
3616        synchronized (mPackages) {
3617            String pkgName = intent.getPackage();
3618            if (pkgName == null) {
3619                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3620            }
3621            final PackageParser.Package pkg = mPackages.get(pkgName);
3622            if (pkg != null) {
3623                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3624                        userId);
3625            }
3626            return null;
3627        }
3628    }
3629
3630    @Override
3631    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3632        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3633        if (!sUserManager.exists(userId)) return null;
3634        if (query != null) {
3635            if (query.size() >= 1) {
3636                // If there is more than one service with the same priority,
3637                // just arbitrarily pick the first one.
3638                return query.get(0);
3639            }
3640        }
3641        return null;
3642    }
3643
3644    @Override
3645    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3646            int userId) {
3647        if (!sUserManager.exists(userId)) return Collections.emptyList();
3648        ComponentName comp = intent.getComponent();
3649        if (comp == null) {
3650            if (intent.getSelector() != null) {
3651                intent = intent.getSelector();
3652                comp = intent.getComponent();
3653            }
3654        }
3655        if (comp != null) {
3656            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3657            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3658            if (si != null) {
3659                final ResolveInfo ri = new ResolveInfo();
3660                ri.serviceInfo = si;
3661                list.add(ri);
3662            }
3663            return list;
3664        }
3665
3666        // reader
3667        synchronized (mPackages) {
3668            String pkgName = intent.getPackage();
3669            if (pkgName == null) {
3670                return mServices.queryIntent(intent, resolvedType, flags, userId);
3671            }
3672            final PackageParser.Package pkg = mPackages.get(pkgName);
3673            if (pkg != null) {
3674                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3675                        userId);
3676            }
3677            return null;
3678        }
3679    }
3680
3681    @Override
3682    public List<ResolveInfo> queryIntentContentProviders(
3683            Intent intent, String resolvedType, int flags, int userId) {
3684        if (!sUserManager.exists(userId)) return Collections.emptyList();
3685        ComponentName comp = intent.getComponent();
3686        if (comp == null) {
3687            if (intent.getSelector() != null) {
3688                intent = intent.getSelector();
3689                comp = intent.getComponent();
3690            }
3691        }
3692        if (comp != null) {
3693            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3694            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3695            if (pi != null) {
3696                final ResolveInfo ri = new ResolveInfo();
3697                ri.providerInfo = pi;
3698                list.add(ri);
3699            }
3700            return list;
3701        }
3702
3703        // reader
3704        synchronized (mPackages) {
3705            String pkgName = intent.getPackage();
3706            if (pkgName == null) {
3707                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3708            }
3709            final PackageParser.Package pkg = mPackages.get(pkgName);
3710            if (pkg != null) {
3711                return mProviders.queryIntentForPackage(
3712                        intent, resolvedType, flags, pkg.providers, userId);
3713            }
3714            return null;
3715        }
3716    }
3717
3718    @Override
3719    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3720        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3721
3722        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3723
3724        // writer
3725        synchronized (mPackages) {
3726            ArrayList<PackageInfo> list;
3727            if (listUninstalled) {
3728                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3729                for (PackageSetting ps : mSettings.mPackages.values()) {
3730                    PackageInfo pi;
3731                    if (ps.pkg != null) {
3732                        pi = generatePackageInfo(ps.pkg, flags, userId);
3733                    } else {
3734                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3735                    }
3736                    if (pi != null) {
3737                        list.add(pi);
3738                    }
3739                }
3740            } else {
3741                list = new ArrayList<PackageInfo>(mPackages.size());
3742                for (PackageParser.Package p : mPackages.values()) {
3743                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3744                    if (pi != null) {
3745                        list.add(pi);
3746                    }
3747                }
3748            }
3749
3750            return new ParceledListSlice<PackageInfo>(list);
3751        }
3752    }
3753
3754    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3755            String[] permissions, boolean[] tmp, int flags, int userId) {
3756        int numMatch = 0;
3757        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3758        for (int i=0; i<permissions.length; i++) {
3759            if (gp.grantedPermissions.contains(permissions[i])) {
3760                tmp[i] = true;
3761                numMatch++;
3762            } else {
3763                tmp[i] = false;
3764            }
3765        }
3766        if (numMatch == 0) {
3767            return;
3768        }
3769        PackageInfo pi;
3770        if (ps.pkg != null) {
3771            pi = generatePackageInfo(ps.pkg, flags, userId);
3772        } else {
3773            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3774        }
3775        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3776            if (numMatch == permissions.length) {
3777                pi.requestedPermissions = permissions;
3778            } else {
3779                pi.requestedPermissions = new String[numMatch];
3780                numMatch = 0;
3781                for (int i=0; i<permissions.length; i++) {
3782                    if (tmp[i]) {
3783                        pi.requestedPermissions[numMatch] = permissions[i];
3784                        numMatch++;
3785                    }
3786                }
3787            }
3788        }
3789        list.add(pi);
3790    }
3791
3792    @Override
3793    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3794            String[] permissions, int flags, int userId) {
3795        if (!sUserManager.exists(userId)) return null;
3796        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3797
3798        // writer
3799        synchronized (mPackages) {
3800            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3801            boolean[] tmpBools = new boolean[permissions.length];
3802            if (listUninstalled) {
3803                for (PackageSetting ps : mSettings.mPackages.values()) {
3804                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3805                }
3806            } else {
3807                for (PackageParser.Package pkg : mPackages.values()) {
3808                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3809                    if (ps != null) {
3810                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3811                                userId);
3812                    }
3813                }
3814            }
3815
3816            return new ParceledListSlice<PackageInfo>(list);
3817        }
3818    }
3819
3820    @Override
3821    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3822        if (!sUserManager.exists(userId)) return null;
3823        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3824
3825        // writer
3826        synchronized (mPackages) {
3827            ArrayList<ApplicationInfo> list;
3828            if (listUninstalled) {
3829                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3830                for (PackageSetting ps : mSettings.mPackages.values()) {
3831                    ApplicationInfo ai;
3832                    if (ps.pkg != null) {
3833                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3834                                ps.readUserState(userId), userId);
3835                    } else {
3836                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3837                    }
3838                    if (ai != null) {
3839                        list.add(ai);
3840                    }
3841                }
3842            } else {
3843                list = new ArrayList<ApplicationInfo>(mPackages.size());
3844                for (PackageParser.Package p : mPackages.values()) {
3845                    if (p.mExtras != null) {
3846                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3847                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3848                        if (ai != null) {
3849                            list.add(ai);
3850                        }
3851                    }
3852                }
3853            }
3854
3855            return new ParceledListSlice<ApplicationInfo>(list);
3856        }
3857    }
3858
3859    public List<ApplicationInfo> getPersistentApplications(int flags) {
3860        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3861
3862        // reader
3863        synchronized (mPackages) {
3864            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3865            final int userId = UserHandle.getCallingUserId();
3866            while (i.hasNext()) {
3867                final PackageParser.Package p = i.next();
3868                if (p.applicationInfo != null
3869                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3870                        && (!mSafeMode || isSystemApp(p))) {
3871                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3872                    if (ps != null) {
3873                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3874                                ps.readUserState(userId), userId);
3875                        if (ai != null) {
3876                            finalList.add(ai);
3877                        }
3878                    }
3879                }
3880            }
3881        }
3882
3883        return finalList;
3884    }
3885
3886    @Override
3887    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3888        if (!sUserManager.exists(userId)) return null;
3889        // reader
3890        synchronized (mPackages) {
3891            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3892            PackageSetting ps = provider != null
3893                    ? mSettings.mPackages.get(provider.owner.packageName)
3894                    : null;
3895            return ps != null
3896                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3897                    && (!mSafeMode || (provider.info.applicationInfo.flags
3898                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3899                    ? PackageParser.generateProviderInfo(provider, flags,
3900                            ps.readUserState(userId), userId)
3901                    : null;
3902        }
3903    }
3904
3905    /**
3906     * @deprecated
3907     */
3908    @Deprecated
3909    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3910        // reader
3911        synchronized (mPackages) {
3912            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3913                    .entrySet().iterator();
3914            final int userId = UserHandle.getCallingUserId();
3915            while (i.hasNext()) {
3916                Map.Entry<String, PackageParser.Provider> entry = i.next();
3917                PackageParser.Provider p = entry.getValue();
3918                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3919
3920                if (ps != null && p.syncable
3921                        && (!mSafeMode || (p.info.applicationInfo.flags
3922                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3923                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3924                            ps.readUserState(userId), userId);
3925                    if (info != null) {
3926                        outNames.add(entry.getKey());
3927                        outInfo.add(info);
3928                    }
3929                }
3930            }
3931        }
3932    }
3933
3934    @Override
3935    public List<ProviderInfo> queryContentProviders(String processName,
3936            int uid, int flags) {
3937        ArrayList<ProviderInfo> finalList = null;
3938        // reader
3939        synchronized (mPackages) {
3940            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3941            final int userId = processName != null ?
3942                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3943            while (i.hasNext()) {
3944                final PackageParser.Provider p = i.next();
3945                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3946                if (ps != null && p.info.authority != null
3947                        && (processName == null
3948                                || (p.info.processName.equals(processName)
3949                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3950                        && mSettings.isEnabledLPr(p.info, flags, userId)
3951                        && (!mSafeMode
3952                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3953                    if (finalList == null) {
3954                        finalList = new ArrayList<ProviderInfo>(3);
3955                    }
3956                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3957                            ps.readUserState(userId), userId);
3958                    if (info != null) {
3959                        finalList.add(info);
3960                    }
3961                }
3962            }
3963        }
3964
3965        if (finalList != null) {
3966            Collections.sort(finalList, mProviderInitOrderSorter);
3967        }
3968
3969        return finalList;
3970    }
3971
3972    @Override
3973    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3974            int flags) {
3975        // reader
3976        synchronized (mPackages) {
3977            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3978            return PackageParser.generateInstrumentationInfo(i, flags);
3979        }
3980    }
3981
3982    @Override
3983    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3984            int flags) {
3985        ArrayList<InstrumentationInfo> finalList =
3986            new ArrayList<InstrumentationInfo>();
3987
3988        // reader
3989        synchronized (mPackages) {
3990            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3991            while (i.hasNext()) {
3992                final PackageParser.Instrumentation p = i.next();
3993                if (targetPackage == null
3994                        || targetPackage.equals(p.info.targetPackage)) {
3995                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3996                            flags);
3997                    if (ii != null) {
3998                        finalList.add(ii);
3999                    }
4000                }
4001            }
4002        }
4003
4004        return finalList;
4005    }
4006
4007    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4008        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4009        if (overlays == null) {
4010            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4011            return;
4012        }
4013        for (PackageParser.Package opkg : overlays.values()) {
4014            // Not much to do if idmap fails: we already logged the error
4015            // and we certainly don't want to abort installation of pkg simply
4016            // because an overlay didn't fit properly. For these reasons,
4017            // ignore the return value of createIdmapForPackagePairLI.
4018            createIdmapForPackagePairLI(pkg, opkg);
4019        }
4020    }
4021
4022    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4023            PackageParser.Package opkg) {
4024        if (!opkg.mTrustedOverlay) {
4025            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4026                    opkg.baseCodePath + ": overlay not trusted");
4027            return false;
4028        }
4029        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4030        if (overlaySet == null) {
4031            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4032                    opkg.baseCodePath + " but target package has no known overlays");
4033            return false;
4034        }
4035        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4036        // TODO: generate idmap for split APKs
4037        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4038            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4039                    + opkg.baseCodePath);
4040            return false;
4041        }
4042        PackageParser.Package[] overlayArray =
4043            overlaySet.values().toArray(new PackageParser.Package[0]);
4044        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4045            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4046                return p1.mOverlayPriority - p2.mOverlayPriority;
4047            }
4048        };
4049        Arrays.sort(overlayArray, cmp);
4050
4051        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4052        int i = 0;
4053        for (PackageParser.Package p : overlayArray) {
4054            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4055        }
4056        return true;
4057    }
4058
4059    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4060        final File[] files = dir.listFiles();
4061        if (ArrayUtils.isEmpty(files)) {
4062            Log.d(TAG, "No files in app dir " + dir);
4063            return;
4064        }
4065
4066        if (DEBUG_PACKAGE_SCANNING) {
4067            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4068                    + " flags=0x" + Integer.toHexString(flags));
4069        }
4070
4071        for (File file : files) {
4072            final boolean isPackage = isApkFile(file) || file.isDirectory();
4073            if (!isPackage) {
4074                // Ignore entries which are not apk's
4075                continue;
4076            }
4077            try {
4078                scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime,
4079                        null, null);
4080            } catch (PackageManagerException e) {
4081                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4082
4083                // Don't mess around with apps in system partition.
4084                if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4085                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4086                    // Delete the apk
4087                    Slog.w(TAG, "Cleaning up failed install of " + file);
4088                    file.delete();
4089                }
4090            }
4091        }
4092    }
4093
4094    private static File getSettingsProblemFile() {
4095        File dataDir = Environment.getDataDirectory();
4096        File systemDir = new File(dataDir, "system");
4097        File fname = new File(systemDir, "uiderrors.txt");
4098        return fname;
4099    }
4100
4101    static void reportSettingsProblem(int priority, String msg) {
4102        try {
4103            File fname = getSettingsProblemFile();
4104            FileOutputStream out = new FileOutputStream(fname, true);
4105            PrintWriter pw = new FastPrintWriter(out);
4106            SimpleDateFormat formatter = new SimpleDateFormat();
4107            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4108            pw.println(dateString + ": " + msg);
4109            pw.close();
4110            FileUtils.setPermissions(
4111                    fname.toString(),
4112                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4113                    -1, -1);
4114        } catch (java.io.IOException e) {
4115        }
4116        Slog.println(priority, TAG, msg);
4117    }
4118
4119    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4120            PackageParser.Package pkg, File srcFile, int parseFlags)
4121            throws PackageManagerException {
4122        if (ps != null
4123                && ps.codePath.equals(srcFile)
4124                && ps.timeStamp == srcFile.lastModified()
4125                && !isCompatSignatureUpdateNeeded(pkg)) {
4126            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4127            if (ps.signatures.mSignatures != null
4128                    && ps.signatures.mSignatures.length != 0
4129                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4130                // Optimization: reuse the existing cached certificates
4131                // if the package appears to be unchanged.
4132                pkg.mSignatures = ps.signatures.mSignatures;
4133                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4134                synchronized (mPackages) {
4135                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4136                }
4137                return;
4138            }
4139
4140            Slog.w(TAG, "PackageSetting for " + ps.name
4141                    + " is missing signatures.  Collecting certs again to recover them.");
4142        } else {
4143            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4144        }
4145
4146        try {
4147            pp.collectCertificates(pkg, parseFlags);
4148            pp.collectManifestDigest(pkg);
4149        } catch (PackageParserException e) {
4150            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4151                    + pkg.packageName + ": " + e.getMessage());
4152        }
4153    }
4154
4155    /*
4156     *  Scan a package and return the newly parsed package.
4157     *  Returns null in case of errors and the error code is stored in mLastScanError
4158     */
4159    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode,
4160            long currentTime, UserHandle user, String abiOverride) throws PackageManagerException {
4161        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4162        parseFlags |= mDefParseFlags;
4163        PackageParser pp = new PackageParser();
4164        pp.setSeparateProcesses(mSeparateProcesses);
4165        pp.setOnlyCoreApps(mOnlyCore);
4166        pp.setDisplayMetrics(mMetrics);
4167
4168        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4169            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4170        }
4171
4172        final PackageParser.Package pkg;
4173        try {
4174            pkg = pp.parsePackage(scanFile, parseFlags);
4175        } catch (PackageParserException e) {
4176            throw new PackageManagerException(e.error,
4177                    "Failed to scan " + scanFile + ": " + e.getMessage());
4178        }
4179
4180        PackageSetting ps = null;
4181        PackageSetting updatedPkg;
4182        // reader
4183        synchronized (mPackages) {
4184            // Look to see if we already know about this package.
4185            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4186            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4187                // This package has been renamed to its original name.  Let's
4188                // use that.
4189                ps = mSettings.peekPackageLPr(oldName);
4190            }
4191            // If there was no original package, see one for the real package name.
4192            if (ps == null) {
4193                ps = mSettings.peekPackageLPr(pkg.packageName);
4194            }
4195            // Check to see if this package could be hiding/updating a system
4196            // package.  Must look for it either under the original or real
4197            // package name depending on our state.
4198            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4199            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4200        }
4201        boolean updatedPkgBetter = false;
4202        // First check if this is a system package that may involve an update
4203        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4204            if (ps != null && !ps.codePath.equals(scanFile)) {
4205                // The path has changed from what was last scanned...  check the
4206                // version of the new path against what we have stored to determine
4207                // what to do.
4208                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4209                if (pkg.mVersionCode < ps.versionCode) {
4210                    // The system package has been updated and the code path does not match
4211                    // Ignore entry. Skip it.
4212                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4213                            + " ignored: updated version " + ps.versionCode
4214                            + " better than this " + pkg.mVersionCode);
4215                    if (!updatedPkg.codePath.equals(scanFile)) {
4216                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4217                                + ps.name + " changing from " + updatedPkg.codePathString
4218                                + " to " + scanFile);
4219                        updatedPkg.codePath = scanFile;
4220                        updatedPkg.codePathString = scanFile.toString();
4221                        // This is the point at which we know that the system-disk APK
4222                        // for this package has moved during a reboot (e.g. due to an OTA),
4223                        // so we need to reevaluate it for privilege policy.
4224                        if (locationIsPrivileged(scanFile)) {
4225                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4226                        }
4227                    }
4228                    updatedPkg.pkg = pkg;
4229                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4230                } else {
4231                    // The current app on the system partition is better than
4232                    // what we have updated to on the data partition; switch
4233                    // back to the system partition version.
4234                    // At this point, its safely assumed that package installation for
4235                    // apps in system partition will go through. If not there won't be a working
4236                    // version of the app
4237                    // writer
4238                    synchronized (mPackages) {
4239                        // Just remove the loaded entries from package lists.
4240                        mPackages.remove(ps.name);
4241                    }
4242                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4243                            + "reverting from " + ps.codePathString
4244                            + ": new version " + pkg.mVersionCode
4245                            + " better than installed " + ps.versionCode);
4246
4247                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4248                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4249                            getAppDexInstructionSets(ps), isMultiArch(ps));
4250                    synchronized (mInstallLock) {
4251                        args.cleanUpResourcesLI();
4252                    }
4253                    synchronized (mPackages) {
4254                        mSettings.enableSystemPackageLPw(ps.name);
4255                    }
4256                    updatedPkgBetter = true;
4257                }
4258            }
4259        }
4260
4261        if (updatedPkg != null) {
4262            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4263            // initially
4264            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4265
4266            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4267            // flag set initially
4268            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4269                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4270            }
4271        }
4272
4273        // Verify certificates against what was last scanned
4274        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4275
4276        /*
4277         * A new system app appeared, but we already had a non-system one of the
4278         * same name installed earlier.
4279         */
4280        boolean shouldHideSystemApp = false;
4281        if (updatedPkg == null && ps != null
4282                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4283            /*
4284             * Check to make sure the signatures match first. If they don't,
4285             * wipe the installed application and its data.
4286             */
4287            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4288                    != PackageManager.SIGNATURE_MATCH) {
4289                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4290                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4291                ps = null;
4292            } else {
4293                /*
4294                 * If the newly-added system app is an older version than the
4295                 * already installed version, hide it. It will be scanned later
4296                 * and re-added like an update.
4297                 */
4298                if (pkg.mVersionCode < ps.versionCode) {
4299                    shouldHideSystemApp = true;
4300                } else {
4301                    /*
4302                     * The newly found system app is a newer version that the
4303                     * one previously installed. Simply remove the
4304                     * already-installed application and replace it with our own
4305                     * while keeping the application data.
4306                     */
4307                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4308                            + ps.codePathString + ": new version " + pkg.mVersionCode
4309                            + " better than installed " + ps.versionCode);
4310                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4311                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4312                            getAppDexInstructionSets(ps), isMultiArch(ps));
4313                    synchronized (mInstallLock) {
4314                        args.cleanUpResourcesLI();
4315                    }
4316                }
4317            }
4318        }
4319
4320        // The apk is forward locked (not public) if its code and resources
4321        // are kept in different files. (except for app in either system or
4322        // vendor path).
4323        // TODO grab this value from PackageSettings
4324        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4325            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4326                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4327            }
4328        }
4329
4330        // TODO: extend to support forward-locked splits
4331        String resourcePath = null;
4332        String baseResourcePath = null;
4333        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4334            if (ps != null && ps.resourcePathString != null) {
4335                resourcePath = ps.resourcePathString;
4336                baseResourcePath = ps.resourcePathString;
4337            } else {
4338                // Should not happen at all. Just log an error.
4339                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4340            }
4341        } else {
4342            resourcePath = pkg.codePath;
4343            baseResourcePath = pkg.baseCodePath;
4344        }
4345
4346        // Set application objects path explicitly.
4347        pkg.applicationInfo.setCodePath(pkg.codePath);
4348        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4349        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4350        pkg.applicationInfo.setResourcePath(resourcePath);
4351        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4352        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4353
4354        // Note that we invoke the following method only if we are about to unpack an application
4355        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4356                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4357
4358        /*
4359         * If the system app should be overridden by a previously installed
4360         * data, hide the system app now and let the /data/app scan pick it up
4361         * again.
4362         */
4363        if (shouldHideSystemApp) {
4364            synchronized (mPackages) {
4365                /*
4366                 * We have to grant systems permissions before we hide, because
4367                 * grantPermissions will assume the package update is trying to
4368                 * expand its permissions.
4369                 */
4370                grantPermissionsLPw(pkg, true);
4371                mSettings.disableSystemPackageLPw(pkg.packageName);
4372            }
4373        }
4374
4375        return scannedPkg;
4376    }
4377
4378    private static String fixProcessName(String defProcessName,
4379            String processName, int uid) {
4380        if (processName == null) {
4381            return defProcessName;
4382        }
4383        return processName;
4384    }
4385
4386    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4387            throws PackageManagerException {
4388        if (pkgSetting.signatures.mSignatures != null) {
4389            // Already existing package. Make sure signatures match
4390            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4391                    == PackageManager.SIGNATURE_MATCH;
4392            if (!match) {
4393                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4394                        == PackageManager.SIGNATURE_MATCH;
4395            }
4396            if (!match) {
4397                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4398                        + pkg.packageName + " signatures do not match the "
4399                        + "previously installed version; ignoring!");
4400            }
4401        }
4402
4403        // Check for shared user signatures
4404        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4405            // Already existing package. Make sure signatures match
4406            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4407                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4408            if (!match) {
4409                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4410                        == PackageManager.SIGNATURE_MATCH;
4411            }
4412            if (!match) {
4413                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4414                        "Package " + pkg.packageName
4415                        + " has no signatures that match those in shared user "
4416                        + pkgSetting.sharedUser.name + "; ignoring!");
4417            }
4418        }
4419    }
4420
4421    /**
4422     * Enforces that only the system UID or root's UID can call a method exposed
4423     * via Binder.
4424     *
4425     * @param message used as message if SecurityException is thrown
4426     * @throws SecurityException if the caller is not system or root
4427     */
4428    private static final void enforceSystemOrRoot(String message) {
4429        final int uid = Binder.getCallingUid();
4430        if (uid != Process.SYSTEM_UID && uid != 0) {
4431            throw new SecurityException(message);
4432        }
4433    }
4434
4435    @Override
4436    public void performBootDexOpt() {
4437        enforceSystemOrRoot("Only the system can request dexopt be performed");
4438
4439        final HashSet<PackageParser.Package> pkgs;
4440        synchronized (mPackages) {
4441            pkgs = mDeferredDexOpt;
4442            mDeferredDexOpt = null;
4443        }
4444
4445        if (pkgs != null) {
4446            // Filter out packages that aren't recently used.
4447            //
4448            // The exception is first boot of a non-eng device, which
4449            // should do a full dexopt.
4450            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4451            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4452                // TODO: add a property to control this?
4453                long dexOptLRUThresholdInMinutes;
4454                if (eng) {
4455                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4456                } else {
4457                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4458                }
4459                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4460
4461                int total = pkgs.size();
4462                int skipped = 0;
4463                long now = System.currentTimeMillis();
4464                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4465                    PackageParser.Package pkg = i.next();
4466                    long then = pkg.mLastPackageUsageTimeInMills;
4467                    if (then + dexOptLRUThresholdInMills < now) {
4468                        if (DEBUG_DEXOPT) {
4469                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4470                                  ((then == 0) ? "never" : new Date(then)));
4471                        }
4472                        i.remove();
4473                        skipped++;
4474                    }
4475                }
4476                if (DEBUG_DEXOPT) {
4477                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4478                }
4479            }
4480
4481            int i = 0;
4482            for (PackageParser.Package pkg : pkgs) {
4483                i++;
4484                if (DEBUG_DEXOPT) {
4485                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4486                          + ": " + pkg.packageName);
4487                }
4488                if (!isFirstBoot()) {
4489                    try {
4490                        ActivityManagerNative.getDefault().showBootMessage(
4491                                mContext.getResources().getString(
4492                                        R.string.android_upgrading_apk,
4493                                        i, pkgs.size()), true);
4494                    } catch (RemoteException e) {
4495                    }
4496                }
4497                PackageParser.Package p = pkg;
4498                synchronized (mInstallLock) {
4499                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4500                            true /* include dependencies */);
4501                }
4502            }
4503        }
4504    }
4505
4506    @Override
4507    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4508        return performDexOpt(packageName, instructionSet, true);
4509    }
4510
4511    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4512        if (info.primaryCpuAbi == null) {
4513            return getPreferredInstructionSet();
4514        }
4515
4516        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4517    }
4518
4519    public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) {
4520        PackageParser.Package p;
4521        final String targetInstructionSet;
4522        synchronized (mPackages) {
4523            p = mPackages.get(packageName);
4524            if (p == null) {
4525                return false;
4526            }
4527            if (updateUsage) {
4528                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4529            }
4530            mPackageUsage.write(false);
4531
4532            targetInstructionSet = instructionSet != null ? instructionSet :
4533                    getPrimaryInstructionSet(p.applicationInfo);
4534            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4535                return false;
4536            }
4537        }
4538
4539        synchronized (mInstallLock) {
4540            final String[] instructionSets = new String[] { targetInstructionSet };
4541            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4542                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4543        }
4544    }
4545
4546    public HashSet<String> getPackagesThatNeedDexOpt() {
4547        HashSet<String> pkgs = null;
4548        synchronized (mPackages) {
4549            for (PackageParser.Package p : mPackages.values()) {
4550                if (DEBUG_DEXOPT) {
4551                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4552                }
4553                if (!p.mDexOptPerformed.isEmpty()) {
4554                    continue;
4555                }
4556                if (pkgs == null) {
4557                    pkgs = new HashSet<String>();
4558                }
4559                pkgs.add(p.packageName);
4560            }
4561        }
4562        return pkgs;
4563    }
4564
4565    public void shutdown() {
4566        mPackageUsage.write(true);
4567    }
4568
4569    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4570             boolean forceDex, boolean defer, HashSet<String> done) {
4571        for (int i=0; i<libs.size(); i++) {
4572            PackageParser.Package libPkg;
4573            String libName;
4574            synchronized (mPackages) {
4575                libName = libs.get(i);
4576                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4577                if (lib != null && lib.apk != null) {
4578                    libPkg = mPackages.get(lib.apk);
4579                } else {
4580                    libPkg = null;
4581                }
4582            }
4583            if (libPkg != null && !done.contains(libName)) {
4584                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4585            }
4586        }
4587    }
4588
4589    static final int DEX_OPT_SKIPPED = 0;
4590    static final int DEX_OPT_PERFORMED = 1;
4591    static final int DEX_OPT_DEFERRED = 2;
4592    static final int DEX_OPT_FAILED = -1;
4593
4594    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4595            boolean forceDex, boolean defer, HashSet<String> done) {
4596        final String[] instructionSets = targetInstructionSets != null ?
4597                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4598
4599        if (done != null) {
4600            done.add(pkg.packageName);
4601            if (pkg.usesLibraries != null) {
4602                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4603            }
4604            if (pkg.usesOptionalLibraries != null) {
4605                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4606            }
4607        }
4608
4609        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4610            return DEX_OPT_SKIPPED;
4611        }
4612
4613        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4614        boolean performedDexOpt = false;
4615        // There are three basic cases here:
4616        // 1.) we need to dexopt, either because we are forced or it is needed
4617        // 2.) we are defering a needed dexopt
4618        // 3.) we are skipping an unneeded dexopt
4619        for (String path : paths) {
4620            for (String instructionSet : instructionSets) {
4621                if (!forceDex && pkg.mDexOptPerformed.contains(instructionSet)) {
4622                    continue;
4623                }
4624
4625                try {
4626                    final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4627                            pkg.packageName, instructionSet, defer);
4628                    if (forceDex || (!defer && isDexOptNeeded)) {
4629                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4630                                + pkg.applicationInfo.packageName + " isa=" + instructionSet);
4631                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4632                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4633                                pkg.packageName, instructionSet);
4634
4635                        if (ret < 0) {
4636                            // Don't bother running dexopt again if we failed, it will probably
4637                            // just result in an error again. Also, don't bother dexopting for other
4638                            // paths & ISAs.
4639                            return DEX_OPT_FAILED;
4640                        } else {
4641                            performedDexOpt = true;
4642                            pkg.mDexOptPerformed.add(instructionSet);
4643                        }
4644                    }
4645
4646                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4647                    // paths and instruction sets. We'll deal with them all together when we process
4648                    // our list of deferred dexopts.
4649                    if (defer && isDexOptNeeded) {
4650                        if (mDeferredDexOpt == null) {
4651                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4652                        }
4653                        mDeferredDexOpt.add(pkg);
4654                        return DEX_OPT_DEFERRED;
4655                    }
4656                } catch (FileNotFoundException e) {
4657                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4658                    return DEX_OPT_FAILED;
4659                } catch (IOException e) {
4660                    Slog.w(TAG, "IOException reading apk: " + path, e);
4661                    return DEX_OPT_FAILED;
4662                } catch (StaleDexCacheError e) {
4663                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4664                    return DEX_OPT_FAILED;
4665                } catch (Exception e) {
4666                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4667                    return DEX_OPT_FAILED;
4668                }
4669            }
4670        }
4671
4672        // If we've gotten here, we're sure that no error occurred and that we haven't
4673        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4674        // we've skipped all of them because they are up to date. In both cases this
4675        // package doesn't need dexopt any longer.
4676        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4677    }
4678
4679    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4680        if (info.primaryCpuAbi != null) {
4681            if (info.secondaryCpuAbi != null) {
4682                return new String[] {
4683                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4684                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4685            } else {
4686                return new String[] {
4687                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4688            }
4689        }
4690
4691        return new String[] { getPreferredInstructionSet() };
4692    }
4693
4694    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4695        if (ps.primaryCpuAbiString != null) {
4696            if (ps.secondaryCpuAbiString != null) {
4697                return new String[] {
4698                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4699                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4700            } else {
4701                return new String[] {
4702                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4703            }
4704        }
4705
4706        return new String[] { getPreferredInstructionSet() };
4707    }
4708
4709    private static String getPreferredInstructionSet() {
4710        if (sPreferredInstructionSet == null) {
4711            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4712        }
4713
4714        return sPreferredInstructionSet;
4715    }
4716
4717    private static List<String> getAllInstructionSets() {
4718        final String[] allAbis = Build.SUPPORTED_ABIS;
4719        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4720
4721        for (String abi : allAbis) {
4722            final String instructionSet = VMRuntime.getInstructionSet(abi);
4723            if (!allInstructionSets.contains(instructionSet)) {
4724                allInstructionSets.add(instructionSet);
4725            }
4726        }
4727
4728        return allInstructionSets;
4729    }
4730
4731    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4732                                boolean forceDex, boolean defer, boolean inclDependencies) {
4733        HashSet<String> done;
4734        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4735            done = new HashSet<String>();
4736            done.add(pkg.packageName);
4737        } else {
4738            done = null;
4739        }
4740        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4741    }
4742
4743    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4744        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4745            Slog.w(TAG, "Unable to update from " + oldPkg.name
4746                    + " to " + newPkg.packageName
4747                    + ": old package not in system partition");
4748            return false;
4749        } else if (mPackages.get(oldPkg.name) != null) {
4750            Slog.w(TAG, "Unable to update from " + oldPkg.name
4751                    + " to " + newPkg.packageName
4752                    + ": old package still exists");
4753            return false;
4754        }
4755        return true;
4756    }
4757
4758    File getDataPathForUser(int userId) {
4759        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4760    }
4761
4762    private File getDataPathForPackage(String packageName, int userId) {
4763        /*
4764         * Until we fully support multiple users, return the directory we
4765         * previously would have. The PackageManagerTests will need to be
4766         * revised when this is changed back..
4767         */
4768        if (userId == 0) {
4769            return new File(mAppDataDir, packageName);
4770        } else {
4771            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4772                + File.separator + packageName);
4773        }
4774    }
4775
4776    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4777        int[] users = sUserManager.getUserIds();
4778        int res = mInstaller.install(packageName, uid, uid, seinfo);
4779        if (res < 0) {
4780            return res;
4781        }
4782        for (int user : users) {
4783            if (user != 0) {
4784                res = mInstaller.createUserData(packageName,
4785                        UserHandle.getUid(user, uid), user, seinfo);
4786                if (res < 0) {
4787                    return res;
4788                }
4789            }
4790        }
4791        return res;
4792    }
4793
4794    private int removeDataDirsLI(String packageName) {
4795        int[] users = sUserManager.getUserIds();
4796        int res = 0;
4797        for (int user : users) {
4798            int resInner = mInstaller.remove(packageName, user);
4799            if (resInner < 0) {
4800                res = resInner;
4801            }
4802        }
4803
4804        return res;
4805    }
4806
4807    private int deleteCodeCacheDirsLI(String packageName) {
4808        int[] users = sUserManager.getUserIds();
4809        int res = 0;
4810        for (int user : users) {
4811            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4812            if (resInner < 0) {
4813                res = resInner;
4814            }
4815        }
4816        return res;
4817    }
4818
4819    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4820            PackageParser.Package changingLib) {
4821        if (file.path != null) {
4822            usesLibraryFiles.add(file.path);
4823            return;
4824        }
4825        PackageParser.Package p = mPackages.get(file.apk);
4826        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4827            // If we are doing this while in the middle of updating a library apk,
4828            // then we need to make sure to use that new apk for determining the
4829            // dependencies here.  (We haven't yet finished committing the new apk
4830            // to the package manager state.)
4831            if (p == null || p.packageName.equals(changingLib.packageName)) {
4832                p = changingLib;
4833            }
4834        }
4835        if (p != null) {
4836            usesLibraryFiles.addAll(p.getAllCodePaths());
4837        }
4838    }
4839
4840    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4841            PackageParser.Package changingLib) throws PackageManagerException {
4842        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4843            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4844            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4845            for (int i=0; i<N; i++) {
4846                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4847                if (file == null) {
4848                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4849                            "Package " + pkg.packageName + " requires unavailable shared library "
4850                            + pkg.usesLibraries.get(i) + "; failing!");
4851                }
4852                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4853            }
4854            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4855            for (int i=0; i<N; i++) {
4856                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4857                if (file == null) {
4858                    Slog.w(TAG, "Package " + pkg.packageName
4859                            + " desires unavailable shared library "
4860                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4861                } else {
4862                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4863                }
4864            }
4865            N = usesLibraryFiles.size();
4866            if (N > 0) {
4867                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4868            } else {
4869                pkg.usesLibraryFiles = null;
4870            }
4871        }
4872    }
4873
4874    private static boolean hasString(List<String> list, List<String> which) {
4875        if (list == null) {
4876            return false;
4877        }
4878        for (int i=list.size()-1; i>=0; i--) {
4879            for (int j=which.size()-1; j>=0; j--) {
4880                if (which.get(j).equals(list.get(i))) {
4881                    return true;
4882                }
4883            }
4884        }
4885        return false;
4886    }
4887
4888    private void updateAllSharedLibrariesLPw() {
4889        for (PackageParser.Package pkg : mPackages.values()) {
4890            try {
4891                updateSharedLibrariesLPw(pkg, null);
4892            } catch (PackageManagerException e) {
4893                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4894            }
4895        }
4896    }
4897
4898    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4899            PackageParser.Package changingPkg) {
4900        ArrayList<PackageParser.Package> res = null;
4901        for (PackageParser.Package pkg : mPackages.values()) {
4902            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4903                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4904                if (res == null) {
4905                    res = new ArrayList<PackageParser.Package>();
4906                }
4907                res.add(pkg);
4908                try {
4909                    updateSharedLibrariesLPw(pkg, changingPkg);
4910                } catch (PackageManagerException e) {
4911                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4912                }
4913            }
4914        }
4915        return res;
4916    }
4917
4918    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4919            int scanMode, long currentTime, UserHandle user, String abiOverride)
4920            throws PackageManagerException {
4921        final File scanFile = new File(pkg.codePath);
4922        if (pkg.applicationInfo.getCodePath() == null ||
4923                pkg.applicationInfo.getResourcePath() == null) {
4924            // Bail out. The resource and code paths haven't been set.
4925            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4926                    "Code and resource paths haven't been set correctly");
4927        }
4928
4929        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4930            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4931        }
4932
4933        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4934            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4935        }
4936
4937        if (mCustomResolverComponentName != null &&
4938                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4939            setUpCustomResolverActivity(pkg);
4940        }
4941
4942        if (pkg.packageName.equals("android")) {
4943            synchronized (mPackages) {
4944                if (mAndroidApplication != null) {
4945                    Slog.w(TAG, "*************************************************");
4946                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4947                    Slog.w(TAG, " file=" + scanFile);
4948                    Slog.w(TAG, "*************************************************");
4949                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
4950                            "Core android package being redefined.  Skipping.");
4951                }
4952
4953                // Set up information for our fall-back user intent resolution activity.
4954                mPlatformPackage = pkg;
4955                pkg.mVersionCode = mSdkVersion;
4956                mAndroidApplication = pkg.applicationInfo;
4957
4958                if (!mResolverReplaced) {
4959                    mResolveActivity.applicationInfo = mAndroidApplication;
4960                    mResolveActivity.name = ResolverActivity.class.getName();
4961                    mResolveActivity.packageName = mAndroidApplication.packageName;
4962                    mResolveActivity.processName = "system:ui";
4963                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4964                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4965                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4966                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4967                    mResolveActivity.exported = true;
4968                    mResolveActivity.enabled = true;
4969                    mResolveInfo.activityInfo = mResolveActivity;
4970                    mResolveInfo.priority = 0;
4971                    mResolveInfo.preferredOrder = 0;
4972                    mResolveInfo.match = 0;
4973                    mResolveComponentName = new ComponentName(
4974                            mAndroidApplication.packageName, mResolveActivity.name);
4975                }
4976            }
4977        }
4978
4979        if (DEBUG_PACKAGE_SCANNING) {
4980            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4981                Log.d(TAG, "Scanning package " + pkg.packageName);
4982        }
4983
4984        if (mPackages.containsKey(pkg.packageName)
4985                || mSharedLibraries.containsKey(pkg.packageName)) {
4986            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
4987                    "Application package " + pkg.packageName
4988                    + " already installed.  Skipping duplicate.");
4989        }
4990
4991        // Initialize package source and resource directories
4992        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
4993        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
4994
4995        SharedUserSetting suid = null;
4996        PackageSetting pkgSetting = null;
4997
4998        if (!isSystemApp(pkg)) {
4999            // Only system apps can use these features.
5000            pkg.mOriginalPackages = null;
5001            pkg.mRealPackage = null;
5002            pkg.mAdoptPermissions = null;
5003        }
5004
5005        // writer
5006        synchronized (mPackages) {
5007            if (pkg.mSharedUserId != null) {
5008                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5009                if (suid == null) {
5010                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5011                            "Creating application package " + pkg.packageName
5012                            + " for shared user failed");
5013                }
5014                if (DEBUG_PACKAGE_SCANNING) {
5015                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5016                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5017                                + "): packages=" + suid.packages);
5018                }
5019            }
5020
5021            // Check if we are renaming from an original package name.
5022            PackageSetting origPackage = null;
5023            String realName = null;
5024            if (pkg.mOriginalPackages != null) {
5025                // This package may need to be renamed to a previously
5026                // installed name.  Let's check on that...
5027                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5028                if (pkg.mOriginalPackages.contains(renamed)) {
5029                    // This package had originally been installed as the
5030                    // original name, and we have already taken care of
5031                    // transitioning to the new one.  Just update the new
5032                    // one to continue using the old name.
5033                    realName = pkg.mRealPackage;
5034                    if (!pkg.packageName.equals(renamed)) {
5035                        // Callers into this function may have already taken
5036                        // care of renaming the package; only do it here if
5037                        // it is not already done.
5038                        pkg.setPackageName(renamed);
5039                    }
5040
5041                } else {
5042                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5043                        if ((origPackage = mSettings.peekPackageLPr(
5044                                pkg.mOriginalPackages.get(i))) != null) {
5045                            // We do have the package already installed under its
5046                            // original name...  should we use it?
5047                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5048                                // New package is not compatible with original.
5049                                origPackage = null;
5050                                continue;
5051                            } else if (origPackage.sharedUser != null) {
5052                                // Make sure uid is compatible between packages.
5053                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5054                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5055                                            + " to " + pkg.packageName + ": old uid "
5056                                            + origPackage.sharedUser.name
5057                                            + " differs from " + pkg.mSharedUserId);
5058                                    origPackage = null;
5059                                    continue;
5060                                }
5061                            } else {
5062                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5063                                        + pkg.packageName + " to old name " + origPackage.name);
5064                            }
5065                            break;
5066                        }
5067                    }
5068                }
5069            }
5070
5071            if (mTransferedPackages.contains(pkg.packageName)) {
5072                Slog.w(TAG, "Package " + pkg.packageName
5073                        + " was transferred to another, but its .apk remains");
5074            }
5075
5076            // Just create the setting, don't add it yet. For already existing packages
5077            // the PkgSetting exists already and doesn't have to be created.
5078            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5079                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5080                    pkg.applicationInfo.primaryCpuAbi,
5081                    pkg.applicationInfo.secondaryCpuAbi,
5082                    pkg.applicationInfo.flags, user, false);
5083            if (pkgSetting == null) {
5084                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5085                        "Creating application package " + pkg.packageName + " failed");
5086            }
5087
5088            if (pkgSetting.origPackage != null) {
5089                // If we are first transitioning from an original package,
5090                // fix up the new package's name now.  We need to do this after
5091                // looking up the package under its new name, so getPackageLP
5092                // can take care of fiddling things correctly.
5093                pkg.setPackageName(origPackage.name);
5094
5095                // File a report about this.
5096                String msg = "New package " + pkgSetting.realName
5097                        + " renamed to replace old package " + pkgSetting.name;
5098                reportSettingsProblem(Log.WARN, msg);
5099
5100                // Make a note of it.
5101                mTransferedPackages.add(origPackage.name);
5102
5103                // No longer need to retain this.
5104                pkgSetting.origPackage = null;
5105            }
5106
5107            if (realName != null) {
5108                // Make a note of it.
5109                mTransferedPackages.add(pkg.packageName);
5110            }
5111
5112            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5113                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5114            }
5115
5116            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5117                // Check all shared libraries and map to their actual file path.
5118                // We only do this here for apps not on a system dir, because those
5119                // are the only ones that can fail an install due to this.  We
5120                // will take care of the system apps by updating all of their
5121                // library paths after the scan is done.
5122                updateSharedLibrariesLPw(pkg, null);
5123            }
5124
5125            if (mFoundPolicyFile) {
5126                SELinuxMMAC.assignSeinfoValue(pkg);
5127            }
5128
5129            pkg.applicationInfo.uid = pkgSetting.appId;
5130            pkg.mExtras = pkgSetting;
5131            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5132                try {
5133                    verifySignaturesLP(pkgSetting, pkg);
5134                } catch (PackageManagerException e) {
5135                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5136                        throw e;
5137                    }
5138                    // The signature has changed, but this package is in the system
5139                    // image...  let's recover!
5140                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5141                    // However...  if this package is part of a shared user, but it
5142                    // doesn't match the signature of the shared user, let's fail.
5143                    // What this means is that you can't change the signatures
5144                    // associated with an overall shared user, which doesn't seem all
5145                    // that unreasonable.
5146                    if (pkgSetting.sharedUser != null) {
5147                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5148                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5149                            throw new PackageManagerException(
5150                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5151                                            "Signature mismatch for shared user : "
5152                                            + pkgSetting.sharedUser);
5153                        }
5154                    }
5155                    // File a report about this.
5156                    String msg = "System package " + pkg.packageName
5157                        + " signature changed; retaining data.";
5158                    reportSettingsProblem(Log.WARN, msg);
5159                }
5160            } else {
5161                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5162                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5163                            + pkg.packageName + " upgrade keys do not match the "
5164                            + "previously installed version");
5165                } else {
5166                    // signatures may have changed as result of upgrade
5167                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5168                }
5169            }
5170            // Verify that this new package doesn't have any content providers
5171            // that conflict with existing packages.  Only do this if the
5172            // package isn't already installed, since we don't want to break
5173            // things that are installed.
5174            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5175                final int N = pkg.providers.size();
5176                int i;
5177                for (i=0; i<N; i++) {
5178                    PackageParser.Provider p = pkg.providers.get(i);
5179                    if (p.info.authority != null) {
5180                        String names[] = p.info.authority.split(";");
5181                        for (int j = 0; j < names.length; j++) {
5182                            if (mProvidersByAuthority.containsKey(names[j])) {
5183                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5184                                final String otherPackageName =
5185                                        ((other != null && other.getComponentName() != null) ?
5186                                                other.getComponentName().getPackageName() : "?");
5187                                throw new PackageManagerException(
5188                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5189                                                "Can't install because provider name " + names[j]
5190                                                + " (in package " + pkg.applicationInfo.packageName
5191                                                + ") is already used by " + otherPackageName);
5192                            }
5193                        }
5194                    }
5195                }
5196            }
5197
5198            if (pkg.mAdoptPermissions != null) {
5199                // This package wants to adopt ownership of permissions from
5200                // another package.
5201                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5202                    final String origName = pkg.mAdoptPermissions.get(i);
5203                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5204                    if (orig != null) {
5205                        if (verifyPackageUpdateLPr(orig, pkg)) {
5206                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5207                                    + pkg.packageName);
5208                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5209                        }
5210                    }
5211                }
5212            }
5213        }
5214
5215        final String pkgName = pkg.packageName;
5216
5217        final long scanFileTime = scanFile.lastModified();
5218        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5219        pkg.applicationInfo.processName = fixProcessName(
5220                pkg.applicationInfo.packageName,
5221                pkg.applicationInfo.processName,
5222                pkg.applicationInfo.uid);
5223
5224        File dataPath;
5225        if (mPlatformPackage == pkg) {
5226            // The system package is special.
5227            dataPath = new File (Environment.getDataDirectory(), "system");
5228            pkg.applicationInfo.dataDir = dataPath.getPath();
5229
5230        } else {
5231            // This is a normal package, need to make its data directory.
5232            dataPath = getDataPathForPackage(pkg.packageName, 0);
5233
5234            boolean uidError = false;
5235
5236            if (dataPath.exists()) {
5237                int currentUid = 0;
5238                try {
5239                    StructStat stat = Os.stat(dataPath.getPath());
5240                    currentUid = stat.st_uid;
5241                } catch (ErrnoException e) {
5242                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5243                }
5244
5245                // If we have mismatched owners for the data path, we have a problem.
5246                if (currentUid != pkg.applicationInfo.uid) {
5247                    boolean recovered = false;
5248                    if (currentUid == 0) {
5249                        // The directory somehow became owned by root.  Wow.
5250                        // This is probably because the system was stopped while
5251                        // installd was in the middle of messing with its libs
5252                        // directory.  Ask installd to fix that.
5253                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5254                                pkg.applicationInfo.uid);
5255                        if (ret >= 0) {
5256                            recovered = true;
5257                            String msg = "Package " + pkg.packageName
5258                                    + " unexpectedly changed to uid 0; recovered to " +
5259                                    + pkg.applicationInfo.uid;
5260                            reportSettingsProblem(Log.WARN, msg);
5261                        }
5262                    }
5263                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5264                            || (scanMode&SCAN_BOOTING) != 0)) {
5265                        // If this is a system app, we can at least delete its
5266                        // current data so the application will still work.
5267                        int ret = removeDataDirsLI(pkgName);
5268                        if (ret >= 0) {
5269                            // TODO: Kill the processes first
5270                            // Old data gone!
5271                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5272                                    ? "System package " : "Third party package ";
5273                            String msg = prefix + pkg.packageName
5274                                    + " has changed from uid: "
5275                                    + currentUid + " to "
5276                                    + pkg.applicationInfo.uid + "; old data erased";
5277                            reportSettingsProblem(Log.WARN, msg);
5278                            recovered = true;
5279
5280                            // And now re-install the app.
5281                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5282                                                   pkg.applicationInfo.seinfo);
5283                            if (ret == -1) {
5284                                // Ack should not happen!
5285                                msg = prefix + pkg.packageName
5286                                        + " could not have data directory re-created after delete.";
5287                                reportSettingsProblem(Log.WARN, msg);
5288                                throw new PackageManagerException(
5289                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5290                            }
5291                        }
5292                        if (!recovered) {
5293                            mHasSystemUidErrors = true;
5294                        }
5295                    } else if (!recovered) {
5296                        // If we allow this install to proceed, we will be broken.
5297                        // Abort, abort!
5298                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5299                                "scanPackageLI");
5300                    }
5301                    if (!recovered) {
5302                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5303                            + pkg.applicationInfo.uid + "/fs_"
5304                            + currentUid;
5305                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5306                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5307                        String msg = "Package " + pkg.packageName
5308                                + " has mismatched uid: "
5309                                + currentUid + " on disk, "
5310                                + pkg.applicationInfo.uid + " in settings";
5311                        // writer
5312                        synchronized (mPackages) {
5313                            mSettings.mReadMessages.append(msg);
5314                            mSettings.mReadMessages.append('\n');
5315                            uidError = true;
5316                            if (!pkgSetting.uidError) {
5317                                reportSettingsProblem(Log.ERROR, msg);
5318                            }
5319                        }
5320                    }
5321                }
5322                pkg.applicationInfo.dataDir = dataPath.getPath();
5323                if (mShouldRestoreconData) {
5324                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5325                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5326                                pkg.applicationInfo.uid);
5327                }
5328            } else {
5329                if (DEBUG_PACKAGE_SCANNING) {
5330                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5331                        Log.v(TAG, "Want this data dir: " + dataPath);
5332                }
5333                //invoke installer to do the actual installation
5334                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5335                                           pkg.applicationInfo.seinfo);
5336                if (ret < 0) {
5337                    // Error from installer
5338                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5339                            "Unable to create data dirs [errorCode=" + ret + "]");
5340                }
5341
5342                if (dataPath.exists()) {
5343                    pkg.applicationInfo.dataDir = dataPath.getPath();
5344                } else {
5345                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5346                    pkg.applicationInfo.dataDir = null;
5347                }
5348            }
5349
5350            pkgSetting.uidError = uidError;
5351        }
5352
5353        final String path = scanFile.getPath();
5354        final String codePath = pkg.applicationInfo.getCodePath();
5355        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5356            // For the case where we had previously uninstalled an update, get rid
5357            // of any native binaries we might have unpackaged. Note that this assumes
5358            // that system app updates were not installed via ASEC.
5359            //
5360            // TODO(multiArch): Is this cleanup really necessary ?
5361            NativeLibraryHelper.removeNativeBinariesFromDirLI(
5362                    new File(codePath, LIB_DIR_NAME), false /* delete dirs */);
5363            setBundledAppAbisAndRoots(pkg, pkgSetting);
5364
5365            // If we haven't found any native libraries for the app, check if it has
5366            // renderscript code. We'll need to force the app to 32 bit if it has
5367            // renderscript bitcode.
5368            if (pkg.applicationInfo.primaryCpuAbi == null
5369                    && pkg.applicationInfo.secondaryCpuAbi == null
5370                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5371                NativeLibraryHelper.Handle handle = null;
5372                try {
5373                    handle = NativeLibraryHelper.Handle.create(scanFile);
5374                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5375                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5376                    }
5377                } catch (IOException ioe) {
5378                    Slog.w(TAG, "Error scanning system app : " + ioe);
5379                } finally {
5380                    IoUtils.closeQuietly(handle);
5381                }
5382            }
5383
5384            setNativeLibraryPaths(pkg);
5385        } else {
5386            // TODO: We can probably be smarter about this stuff. For installed apps,
5387            // we can calculate this information at install time once and for all. For
5388            // system apps, we can probably assume that this information doesn't change
5389            // after the first boot scan. As things stand, we do lots of unnecessary work.
5390
5391            // Give ourselves some initial paths; we'll come back for another
5392            // pass once we've determined ABI below.
5393            setNativeLibraryPaths(pkg);
5394
5395            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5396            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5397            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5398
5399            NativeLibraryHelper.Handle handle = null;
5400            try {
5401                handle = NativeLibraryHelper.Handle.create(scanFile);
5402                // TODO(multiArch): This can be null for apps that didn't go through the
5403                // usual installation process. We can calculate it again, like we
5404                // do during install time.
5405                //
5406                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5407                // unnecessary.
5408                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5409
5410                // Null out the abis so that they can be recalculated.
5411                pkg.applicationInfo.primaryCpuAbi = null;
5412                pkg.applicationInfo.secondaryCpuAbi = null;
5413                if (isMultiArch(pkg.applicationInfo)) {
5414                    // Warn if we've set an abiOverride for multi-lib packages..
5415                    // By definition, we need to copy both 32 and 64 bit libraries for
5416                    // such packages.
5417                    if (abiOverride != null) {
5418                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5419                    }
5420
5421                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5422                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5423                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5424                        if (isAsec) {
5425                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5426                        } else {
5427                            abi32 = copyNativeLibrariesForInternalApp(handle,
5428                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs);
5429                        }
5430                    }
5431
5432                    maybeThrowExceptionForMultiArchCopy(
5433                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5434
5435                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5436                        if (isAsec) {
5437                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5438                        } else {
5439                            abi64 = copyNativeLibrariesForInternalApp(handle,
5440                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs);
5441                        }
5442                    }
5443
5444                    maybeThrowExceptionForMultiArchCopy(
5445                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5446
5447                    if (abi64 >= 0) {
5448                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5449                    }
5450
5451                    if (abi32 >= 0) {
5452                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5453                        if (abi64 >= 0) {
5454                            pkg.applicationInfo.secondaryCpuAbi = abi;
5455                        } else {
5456                            pkg.applicationInfo.primaryCpuAbi = abi;
5457                        }
5458                    }
5459                } else {
5460                    String[] abiList = (abiOverride != null) ?
5461                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
5462
5463                    // Enable gross and lame hacks for apps that are built with old
5464                    // SDK tools. We must scan their APKs for renderscript bitcode and
5465                    // not launch them if it's present. Don't bother checking on devices
5466                    // that don't have 64 bit support.
5467                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
5468                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5469                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5470                    }
5471
5472                    final int copyRet;
5473                    if (isAsec) {
5474                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5475                    } else {
5476                        copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList,
5477                                useIsaSpecificSubdirs);
5478                    }
5479
5480                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5481                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5482                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5483                    }
5484
5485                    if (copyRet >= 0) {
5486                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5487                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) {
5488                        pkg.applicationInfo.primaryCpuAbi = abiOverride;
5489                    }
5490                }
5491            } catch (IOException ioe) {
5492                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5493            } finally {
5494                IoUtils.closeQuietly(handle);
5495            }
5496
5497            // Now that we've calculated the ABIs and determined if it's an internal app,
5498            // we will go ahead and populate the nativeLibraryPath.
5499            setNativeLibraryPaths(pkg);
5500
5501            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5502            final int[] userIds = sUserManager.getUserIds();
5503            synchronized (mInstallLock) {
5504                // Create a native library symlink only if we have native libraries
5505                // and if the native libraries are 32 bit libraries. We do not provide
5506                // this symlink for 64 bit libraries.
5507                if (pkg.applicationInfo.primaryCpuAbi != null &&
5508                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5509                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5510                    for (int userId : userIds) {
5511                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5512                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5513                                    "Failed linking native library dir (user=" + userId + ")");
5514                        }
5515                    }
5516                }
5517            }
5518        }
5519
5520        // This is a special case for the "system" package, where the ABI is
5521        // dictated by the zygote configuration (and init.rc). We should keep track
5522        // of this ABI so that we can deal with "normal" applications that run under
5523        // the same UID correctly.
5524        if (mPlatformPackage == pkg) {
5525            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5526                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5527        }
5528
5529        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5530        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5531
5532        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5533                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5534                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5535
5536        // Push the derived path down into PackageSettings so we know what to
5537        // clean up at uninstall time.
5538        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5539
5540        if (DEBUG_ABI_SELECTION) {
5541            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5542                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5543                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5544        }
5545
5546        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5547            // We don't do this here during boot because we can do it all
5548            // at once after scanning all existing packages.
5549            //
5550            // We also do this *before* we perform dexopt on this package, so that
5551            // we can avoid redundant dexopts, and also to make sure we've got the
5552            // code and package path correct.
5553            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5554                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5555        }
5556
5557        if ((scanMode&SCAN_NO_DEX) == 0) {
5558            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5559                    == DEX_OPT_FAILED) {
5560                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5561                    removeDataDirsLI(pkg.packageName);
5562                }
5563
5564                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5565            }
5566        }
5567
5568        if (mFactoryTest && pkg.requestedPermissions.contains(
5569                android.Manifest.permission.FACTORY_TEST)) {
5570            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5571        }
5572
5573        ArrayList<PackageParser.Package> clientLibPkgs = null;
5574
5575        // writer
5576        synchronized (mPackages) {
5577            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5578                // Only system apps can add new shared libraries.
5579                if (pkg.libraryNames != null) {
5580                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5581                        String name = pkg.libraryNames.get(i);
5582                        boolean allowed = false;
5583                        if (isUpdatedSystemApp(pkg)) {
5584                            // New library entries can only be added through the
5585                            // system image.  This is important to get rid of a lot
5586                            // of nasty edge cases: for example if we allowed a non-
5587                            // system update of the app to add a library, then uninstalling
5588                            // the update would make the library go away, and assumptions
5589                            // we made such as through app install filtering would now
5590                            // have allowed apps on the device which aren't compatible
5591                            // with it.  Better to just have the restriction here, be
5592                            // conservative, and create many fewer cases that can negatively
5593                            // impact the user experience.
5594                            final PackageSetting sysPs = mSettings
5595                                    .getDisabledSystemPkgLPr(pkg.packageName);
5596                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5597                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5598                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5599                                        allowed = true;
5600                                        allowed = true;
5601                                        break;
5602                                    }
5603                                }
5604                            }
5605                        } else {
5606                            allowed = true;
5607                        }
5608                        if (allowed) {
5609                            if (!mSharedLibraries.containsKey(name)) {
5610                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5611                            } else if (!name.equals(pkg.packageName)) {
5612                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5613                                        + name + " already exists; skipping");
5614                            }
5615                        } else {
5616                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5617                                    + name + " that is not declared on system image; skipping");
5618                        }
5619                    }
5620                    if ((scanMode&SCAN_BOOTING) == 0) {
5621                        // If we are not booting, we need to update any applications
5622                        // that are clients of our shared library.  If we are booting,
5623                        // this will all be done once the scan is complete.
5624                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5625                    }
5626                }
5627            }
5628        }
5629
5630        // We also need to dexopt any apps that are dependent on this library.  Note that
5631        // if these fail, we should abort the install since installing the library will
5632        // result in some apps being broken.
5633        if (clientLibPkgs != null) {
5634            if ((scanMode&SCAN_NO_DEX) == 0) {
5635                for (int i=0; i<clientLibPkgs.size(); i++) {
5636                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5637                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5638                            forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5639                            == DEX_OPT_FAILED) {
5640                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5641                            removeDataDirsLI(pkg.packageName);
5642                        }
5643
5644                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5645                                "scanPackageLI failed to dexopt clientLibPkgs");
5646                    }
5647                }
5648            }
5649        }
5650
5651        // Request the ActivityManager to kill the process(only for existing packages)
5652        // so that we do not end up in a confused state while the user is still using the older
5653        // version of the application while the new one gets installed.
5654        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5655            // If the package lives in an asec, tell everyone that the container is going
5656            // away so they can clean up any references to its resources (which would prevent
5657            // vold from being able to unmount the asec)
5658            if (isForwardLocked(pkg) || isExternal(pkg)) {
5659                if (DEBUG_INSTALL) {
5660                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5661                }
5662                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5663                final ArrayList<String> pkgList = new ArrayList<String>(1);
5664                pkgList.add(pkg.applicationInfo.packageName);
5665                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5666            }
5667
5668            // Post the request that it be killed now that the going-away broadcast is en route
5669            killApplication(pkg.applicationInfo.packageName,
5670                        pkg.applicationInfo.uid, "update pkg");
5671        }
5672
5673        // Also need to kill any apps that are dependent on the library.
5674        if (clientLibPkgs != null) {
5675            for (int i=0; i<clientLibPkgs.size(); i++) {
5676                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5677                killApplication(clientPkg.applicationInfo.packageName,
5678                        clientPkg.applicationInfo.uid, "update lib");
5679            }
5680        }
5681
5682        // writer
5683        synchronized (mPackages) {
5684            // We don't expect installation to fail beyond this point,
5685            if ((scanMode&SCAN_MONITOR) != 0) {
5686                mAppDirs.put(pkg.codePath, pkg);
5687            }
5688            // Add the new setting to mSettings
5689            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5690            // Add the new setting to mPackages
5691            mPackages.put(pkg.applicationInfo.packageName, pkg);
5692            // Make sure we don't accidentally delete its data.
5693            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5694            while (iter.hasNext()) {
5695                PackageCleanItem item = iter.next();
5696                if (pkgName.equals(item.packageName)) {
5697                    iter.remove();
5698                }
5699            }
5700
5701            // Take care of first install / last update times.
5702            if (currentTime != 0) {
5703                if (pkgSetting.firstInstallTime == 0) {
5704                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5705                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5706                    pkgSetting.lastUpdateTime = currentTime;
5707                }
5708            } else if (pkgSetting.firstInstallTime == 0) {
5709                // We need *something*.  Take time time stamp of the file.
5710                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5711            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5712                if (scanFileTime != pkgSetting.timeStamp) {
5713                    // A package on the system image has changed; consider this
5714                    // to be an update.
5715                    pkgSetting.lastUpdateTime = scanFileTime;
5716                }
5717            }
5718
5719            // Add the package's KeySets to the global KeySetManagerService
5720            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5721            try {
5722                // Old KeySetData no longer valid.
5723                ksms.removeAppKeySetDataLPw(pkg.packageName);
5724                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5725                if (pkg.mKeySetMapping != null) {
5726                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5727                            pkg.mKeySetMapping.entrySet()) {
5728                        if (entry.getValue() != null) {
5729                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5730                                                          entry.getValue(), entry.getKey());
5731                        }
5732                    }
5733                    if (pkg.mUpgradeKeySets != null) {
5734                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5735                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5736                        }
5737                    }
5738                }
5739            } catch (NullPointerException e) {
5740                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5741            } catch (IllegalArgumentException e) {
5742                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5743            }
5744
5745            int N = pkg.providers.size();
5746            StringBuilder r = null;
5747            int i;
5748            for (i=0; i<N; i++) {
5749                PackageParser.Provider p = pkg.providers.get(i);
5750                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5751                        p.info.processName, pkg.applicationInfo.uid);
5752                mProviders.addProvider(p);
5753                p.syncable = p.info.isSyncable;
5754                if (p.info.authority != null) {
5755                    String names[] = p.info.authority.split(";");
5756                    p.info.authority = null;
5757                    for (int j = 0; j < names.length; j++) {
5758                        if (j == 1 && p.syncable) {
5759                            // We only want the first authority for a provider to possibly be
5760                            // syncable, so if we already added this provider using a different
5761                            // authority clear the syncable flag. We copy the provider before
5762                            // changing it because the mProviders object contains a reference
5763                            // to a provider that we don't want to change.
5764                            // Only do this for the second authority since the resulting provider
5765                            // object can be the same for all future authorities for this provider.
5766                            p = new PackageParser.Provider(p);
5767                            p.syncable = false;
5768                        }
5769                        if (!mProvidersByAuthority.containsKey(names[j])) {
5770                            mProvidersByAuthority.put(names[j], p);
5771                            if (p.info.authority == null) {
5772                                p.info.authority = names[j];
5773                            } else {
5774                                p.info.authority = p.info.authority + ";" + names[j];
5775                            }
5776                            if (DEBUG_PACKAGE_SCANNING) {
5777                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5778                                    Log.d(TAG, "Registered content provider: " + names[j]
5779                                            + ", className = " + p.info.name + ", isSyncable = "
5780                                            + p.info.isSyncable);
5781                            }
5782                        } else {
5783                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5784                            Slog.w(TAG, "Skipping provider name " + names[j] +
5785                                    " (in package " + pkg.applicationInfo.packageName +
5786                                    "): name already used by "
5787                                    + ((other != null && other.getComponentName() != null)
5788                                            ? other.getComponentName().getPackageName() : "?"));
5789                        }
5790                    }
5791                }
5792                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5793                    if (r == null) {
5794                        r = new StringBuilder(256);
5795                    } else {
5796                        r.append(' ');
5797                    }
5798                    r.append(p.info.name);
5799                }
5800            }
5801            if (r != null) {
5802                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5803            }
5804
5805            N = pkg.services.size();
5806            r = null;
5807            for (i=0; i<N; i++) {
5808                PackageParser.Service s = pkg.services.get(i);
5809                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5810                        s.info.processName, pkg.applicationInfo.uid);
5811                mServices.addService(s);
5812                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5813                    if (r == null) {
5814                        r = new StringBuilder(256);
5815                    } else {
5816                        r.append(' ');
5817                    }
5818                    r.append(s.info.name);
5819                }
5820            }
5821            if (r != null) {
5822                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5823            }
5824
5825            N = pkg.receivers.size();
5826            r = null;
5827            for (i=0; i<N; i++) {
5828                PackageParser.Activity a = pkg.receivers.get(i);
5829                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5830                        a.info.processName, pkg.applicationInfo.uid);
5831                mReceivers.addActivity(a, "receiver");
5832                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5833                    if (r == null) {
5834                        r = new StringBuilder(256);
5835                    } else {
5836                        r.append(' ');
5837                    }
5838                    r.append(a.info.name);
5839                }
5840            }
5841            if (r != null) {
5842                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5843            }
5844
5845            N = pkg.activities.size();
5846            r = null;
5847            for (i=0; i<N; i++) {
5848                PackageParser.Activity a = pkg.activities.get(i);
5849                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5850                        a.info.processName, pkg.applicationInfo.uid);
5851                mActivities.addActivity(a, "activity");
5852                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5853                    if (r == null) {
5854                        r = new StringBuilder(256);
5855                    } else {
5856                        r.append(' ');
5857                    }
5858                    r.append(a.info.name);
5859                }
5860            }
5861            if (r != null) {
5862                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5863            }
5864
5865            N = pkg.permissionGroups.size();
5866            r = null;
5867            for (i=0; i<N; i++) {
5868                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5869                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5870                if (cur == null) {
5871                    mPermissionGroups.put(pg.info.name, pg);
5872                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5873                        if (r == null) {
5874                            r = new StringBuilder(256);
5875                        } else {
5876                            r.append(' ');
5877                        }
5878                        r.append(pg.info.name);
5879                    }
5880                } else {
5881                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5882                            + pg.info.packageName + " ignored: original from "
5883                            + cur.info.packageName);
5884                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5885                        if (r == null) {
5886                            r = new StringBuilder(256);
5887                        } else {
5888                            r.append(' ');
5889                        }
5890                        r.append("DUP:");
5891                        r.append(pg.info.name);
5892                    }
5893                }
5894            }
5895            if (r != null) {
5896                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5897            }
5898
5899            N = pkg.permissions.size();
5900            r = null;
5901            for (i=0; i<N; i++) {
5902                PackageParser.Permission p = pkg.permissions.get(i);
5903                HashMap<String, BasePermission> permissionMap =
5904                        p.tree ? mSettings.mPermissionTrees
5905                        : mSettings.mPermissions;
5906                p.group = mPermissionGroups.get(p.info.group);
5907                if (p.info.group == null || p.group != null) {
5908                    BasePermission bp = permissionMap.get(p.info.name);
5909                    if (bp == null) {
5910                        bp = new BasePermission(p.info.name, p.info.packageName,
5911                                BasePermission.TYPE_NORMAL);
5912                        permissionMap.put(p.info.name, bp);
5913                    }
5914                    if (bp.perm == null) {
5915                        if (bp.sourcePackage != null
5916                                && !bp.sourcePackage.equals(p.info.packageName)) {
5917                            // If this is a permission that was formerly defined by a non-system
5918                            // app, but is now defined by a system app (following an upgrade),
5919                            // discard the previous declaration and consider the system's to be
5920                            // canonical.
5921                            if (isSystemApp(p.owner)) {
5922                                String msg = "New decl " + p.owner + " of permission  "
5923                                        + p.info.name + " is system";
5924                                reportSettingsProblem(Log.WARN, msg);
5925                                bp.sourcePackage = null;
5926                            }
5927                        }
5928                        if (bp.sourcePackage == null
5929                                || bp.sourcePackage.equals(p.info.packageName)) {
5930                            BasePermission tree = findPermissionTreeLP(p.info.name);
5931                            if (tree == null
5932                                    || tree.sourcePackage.equals(p.info.packageName)) {
5933                                bp.packageSetting = pkgSetting;
5934                                bp.perm = p;
5935                                bp.uid = pkg.applicationInfo.uid;
5936                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5937                                    if (r == null) {
5938                                        r = new StringBuilder(256);
5939                                    } else {
5940                                        r.append(' ');
5941                                    }
5942                                    r.append(p.info.name);
5943                                }
5944                            } else {
5945                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5946                                        + p.info.packageName + " ignored: base tree "
5947                                        + tree.name + " is from package "
5948                                        + tree.sourcePackage);
5949                            }
5950                        } else {
5951                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5952                                    + p.info.packageName + " ignored: original from "
5953                                    + bp.sourcePackage);
5954                        }
5955                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5956                        if (r == null) {
5957                            r = new StringBuilder(256);
5958                        } else {
5959                            r.append(' ');
5960                        }
5961                        r.append("DUP:");
5962                        r.append(p.info.name);
5963                    }
5964                    if (bp.perm == p) {
5965                        bp.protectionLevel = p.info.protectionLevel;
5966                    }
5967                } else {
5968                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5969                            + p.info.packageName + " ignored: no group "
5970                            + p.group);
5971                }
5972            }
5973            if (r != null) {
5974                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5975            }
5976
5977            N = pkg.instrumentation.size();
5978            r = null;
5979            for (i=0; i<N; i++) {
5980                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5981                a.info.packageName = pkg.applicationInfo.packageName;
5982                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5983                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5984                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
5985                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
5986                a.info.dataDir = pkg.applicationInfo.dataDir;
5987
5988                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
5989                // need other information about the application, like the ABI and what not ?
5990                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5991                mInstrumentation.put(a.getComponentName(), a);
5992                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5993                    if (r == null) {
5994                        r = new StringBuilder(256);
5995                    } else {
5996                        r.append(' ');
5997                    }
5998                    r.append(a.info.name);
5999                }
6000            }
6001            if (r != null) {
6002                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6003            }
6004
6005            if (pkg.protectedBroadcasts != null) {
6006                N = pkg.protectedBroadcasts.size();
6007                for (i=0; i<N; i++) {
6008                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6009                }
6010            }
6011
6012            pkgSetting.setTimeStamp(scanFileTime);
6013
6014            // Create idmap files for pairs of (packages, overlay packages).
6015            // Note: "android", ie framework-res.apk, is handled by native layers.
6016            if (pkg.mOverlayTarget != null) {
6017                // This is an overlay package.
6018                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6019                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6020                        mOverlays.put(pkg.mOverlayTarget,
6021                                new HashMap<String, PackageParser.Package>());
6022                    }
6023                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6024                    map.put(pkg.packageName, pkg);
6025                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6026                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6027                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6028                                "scanPackageLI failed to createIdmap");
6029                    }
6030                }
6031            } else if (mOverlays.containsKey(pkg.packageName) &&
6032                    !pkg.packageName.equals("android")) {
6033                // This is a regular package, with one or more known overlay packages.
6034                createIdmapsForPackageLI(pkg);
6035            }
6036        }
6037
6038        return pkg;
6039    }
6040
6041    /**
6042     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6043     * i.e, so that all packages can be run inside a single process if required.
6044     *
6045     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6046     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6047     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6048     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6049     * updating a package that belongs to a shared user.
6050     *
6051     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6052     * adds unnecessary complexity.
6053     */
6054    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6055            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6056        String requiredInstructionSet = null;
6057        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6058            requiredInstructionSet = VMRuntime.getInstructionSet(
6059                     scannedPackage.applicationInfo.primaryCpuAbi);
6060        }
6061
6062        PackageSetting requirer = null;
6063        for (PackageSetting ps : packagesForUser) {
6064            // If packagesForUser contains scannedPackage, we skip it. This will happen
6065            // when scannedPackage is an update of an existing package. Without this check,
6066            // we will never be able to change the ABI of any package belonging to a shared
6067            // user, even if it's compatible with other packages.
6068            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6069                if (ps.primaryCpuAbiString == null) {
6070                    continue;
6071                }
6072
6073                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6074                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6075                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6076                    // this but there's not much we can do.
6077                    String errorMessage = "Instruction set mismatch, "
6078                            + ((requirer == null) ? "[caller]" : requirer)
6079                            + " requires " + requiredInstructionSet + " whereas " + ps
6080                            + " requires " + instructionSet;
6081                    Slog.w(TAG, errorMessage);
6082                }
6083
6084                if (requiredInstructionSet == null) {
6085                    requiredInstructionSet = instructionSet;
6086                    requirer = ps;
6087                }
6088            }
6089        }
6090
6091        if (requiredInstructionSet != null) {
6092            String adjustedAbi;
6093            if (requirer != null) {
6094                // requirer != null implies that either scannedPackage was null or that scannedPackage
6095                // did not require an ABI, in which case we have to adjust scannedPackage to match
6096                // the ABI of the set (which is the same as requirer's ABI)
6097                adjustedAbi = requirer.primaryCpuAbiString;
6098                if (scannedPackage != null) {
6099                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6100                }
6101            } else {
6102                // requirer == null implies that we're updating all ABIs in the set to
6103                // match scannedPackage.
6104                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6105            }
6106
6107            for (PackageSetting ps : packagesForUser) {
6108                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6109                    if (ps.primaryCpuAbiString != null) {
6110                        continue;
6111                    }
6112
6113                    ps.primaryCpuAbiString = adjustedAbi;
6114                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6115                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6116                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6117
6118                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6119                                deferDexOpt, true) == DEX_OPT_FAILED) {
6120                            ps.primaryCpuAbiString = null;
6121                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6122                            return;
6123                        } else {
6124                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6125                        }
6126                    }
6127                }
6128            }
6129        }
6130    }
6131
6132    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6133        synchronized (mPackages) {
6134            mResolverReplaced = true;
6135            // Set up information for custom user intent resolution activity.
6136            mResolveActivity.applicationInfo = pkg.applicationInfo;
6137            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6138            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6139            mResolveActivity.processName = null;
6140            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6141            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6142                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6143            mResolveActivity.theme = 0;
6144            mResolveActivity.exported = true;
6145            mResolveActivity.enabled = true;
6146            mResolveInfo.activityInfo = mResolveActivity;
6147            mResolveInfo.priority = 0;
6148            mResolveInfo.preferredOrder = 0;
6149            mResolveInfo.match = 0;
6150            mResolveComponentName = mCustomResolverComponentName;
6151            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6152                    mResolveComponentName);
6153        }
6154    }
6155
6156    private static String calculateApkRoot(final String codePathString) {
6157        final File codePath = new File(codePathString);
6158        final File codeRoot;
6159        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6160            codeRoot = Environment.getRootDirectory();
6161        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6162            codeRoot = Environment.getOemDirectory();
6163        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6164            codeRoot = Environment.getVendorDirectory();
6165        } else {
6166            // Unrecognized code path; take its top real segment as the apk root:
6167            // e.g. /something/app/blah.apk => /something
6168            try {
6169                File f = codePath.getCanonicalFile();
6170                File parent = f.getParentFile();    // non-null because codePath is a file
6171                File tmp;
6172                while ((tmp = parent.getParentFile()) != null) {
6173                    f = parent;
6174                    parent = tmp;
6175                }
6176                codeRoot = f;
6177                Slog.w(TAG, "Unrecognized code path "
6178                        + codePath + " - using " + codeRoot);
6179            } catch (IOException e) {
6180                // Can't canonicalize the code path -- shenanigans?
6181                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6182                return Environment.getRootDirectory().getPath();
6183            }
6184        }
6185        return codeRoot.getPath();
6186    }
6187
6188    /**
6189     * Derive and set the location of native libraries for the given package,
6190     * which varies depending on where and how the package was installed.
6191     */
6192    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6193        final ApplicationInfo info = pkg.applicationInfo;
6194        final String codePath = pkg.codePath;
6195        final File codeFile = new File(codePath);
6196        // If "/system/lib64/apkname" exists, assume that is the per-package
6197        // native library directory to use; otherwise use "/system/lib/apkname".
6198        final String apkRoot = calculateApkRoot(info.sourceDir);
6199
6200        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6201        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6202
6203
6204        info.nativeLibraryRootDir = null;
6205        info.nativeLibraryRootRequiresIsa = false;
6206        info.nativeLibraryDir = null;
6207        info.secondaryNativeLibraryDir = null;
6208
6209        if (isApkFile(codeFile)) {
6210            // Monolithic install
6211            if (bundledApp) {
6212                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6213                        getPrimaryInstructionSet(info));
6214
6215                // This is a bundled system app so choose the path based on the ABI.
6216                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6217                // is just the default path.
6218                final String apkName = deriveCodePathName(codePath);
6219                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6220                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6221                        apkName).getAbsolutePath();
6222
6223                if (info.secondaryCpuAbi != null) {
6224                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6225                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6226                            secondaryLibDir, apkName).getAbsolutePath();
6227                }
6228            } else if (asecApp) {
6229                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6230                        .getAbsolutePath();
6231            } else {
6232                final String apkName = deriveCodePathName(codePath);
6233                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6234                        .getAbsolutePath();
6235            }
6236
6237            info.nativeLibraryRootRequiresIsa = false;
6238            info.nativeLibraryDir = info.nativeLibraryRootDir;
6239        } else {
6240            // Cluster install
6241            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6242            info.nativeLibraryRootRequiresIsa = true;
6243
6244            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6245                    getPrimaryInstructionSet(info)).getAbsolutePath();
6246
6247            if (info.secondaryCpuAbi != null) {
6248                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6249                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6250            }
6251        }
6252    }
6253
6254    /**
6255     * Calculate the abis and roots for a bundled app. These can uniquely
6256     * be determined from the contents of the system partition, i.e whether
6257     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6258     * of this information, and instead assume that the system was built
6259     * sensibly.
6260     */
6261    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6262                                           PackageSetting pkgSetting) {
6263        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6264
6265        // If "/system/lib64/apkname" exists, assume that is the per-package
6266        // native library directory to use; otherwise use "/system/lib/apkname".
6267        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6268        setBundledAppAbi(pkg, apkRoot, apkName);
6269        // pkgSetting might be null during rescan following uninstall of updates
6270        // to a bundled app, so accommodate that possibility.  The settings in
6271        // that case will be established later from the parsed package.
6272        //
6273        // If the settings aren't null, sync them up with what we've just derived.
6274        // note that apkRoot isn't stored in the package settings.
6275        if (pkgSetting != null) {
6276            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6277            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6278        }
6279    }
6280
6281    /**
6282     * Deduces the ABI of a bundled app and sets the relevant fields on the
6283     * parsed pkg object.
6284     *
6285     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6286     *        under which system libraries are installed.
6287     * @param apkName the name of the installed package.
6288     */
6289    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6290        final File codeFile = new File(pkg.codePath);
6291
6292        final boolean has64BitLibs;
6293        final boolean has32BitLibs;
6294        if (isApkFile(codeFile)) {
6295            // Monolithic install
6296            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6297            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6298        } else {
6299            // Cluster install
6300            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6301            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6302                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6303                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6304                has64BitLibs = (new File(rootDir, isa)).exists();
6305            } else {
6306                has64BitLibs = false;
6307            }
6308            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6309                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6310                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6311                has32BitLibs = (new File(rootDir, isa)).exists();
6312            } else {
6313                has32BitLibs = false;
6314            }
6315        }
6316
6317        if (has64BitLibs && !has32BitLibs) {
6318            // The package has 64 bit libs, but not 32 bit libs. Its primary
6319            // ABI should be 64 bit. We can safely assume here that the bundled
6320            // native libraries correspond to the most preferred ABI in the list.
6321
6322            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6323            pkg.applicationInfo.secondaryCpuAbi = null;
6324        } else if (has32BitLibs && !has64BitLibs) {
6325            // The package has 32 bit libs but not 64 bit libs. Its primary
6326            // ABI should be 32 bit.
6327
6328            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6329            pkg.applicationInfo.secondaryCpuAbi = null;
6330        } else if (has32BitLibs && has64BitLibs) {
6331            // The application has both 64 and 32 bit bundled libraries. We check
6332            // here that the app declares multiArch support, and warn if it doesn't.
6333            //
6334            // We will be lenient here and record both ABIs. The primary will be the
6335            // ABI that's higher on the list, i.e, a device that's configured to prefer
6336            // 64 bit apps will see a 64 bit primary ABI,
6337
6338            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6339                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6340            }
6341
6342            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6343                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6344                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6345            } else {
6346                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6347                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6348            }
6349        } else {
6350            pkg.applicationInfo.primaryCpuAbi = null;
6351            pkg.applicationInfo.secondaryCpuAbi = null;
6352        }
6353    }
6354
6355    private static void createNativeLibrarySubdir(File path) throws IOException {
6356        if (!path.isDirectory()) {
6357            path.delete();
6358
6359            if (!path.mkdir()) {
6360                throw new IOException("Cannot create " + path.getPath());
6361            }
6362
6363            try {
6364                Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6365            } catch (ErrnoException e) {
6366                throw new IOException("Cannot chmod native library directory "
6367                        + path.getPath(), e);
6368            }
6369        } else if (!SELinux.restorecon(path)) {
6370            throw new IOException("Cannot set SELinux context for " + path.getPath());
6371        }
6372    }
6373
6374    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6375            final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException {
6376        createNativeLibrarySubdir(nativeLibraryRoot);
6377
6378        /*
6379         * If this is an internal application or our nativeLibraryPath points to
6380         * the app-lib directory, unpack the libraries if necessary.
6381         */
6382        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6383        if (abi >= 0) {
6384            /*
6385             * If we have a matching instruction set, construct a subdir under the native
6386             * library root that corresponds to this instruction set.
6387             */
6388            final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]);
6389            final File subDir;
6390            if (useIsaSubdir) {
6391                final File isaSubdir = new File(nativeLibraryRoot, instructionSet);
6392                createNativeLibrarySubdir(isaSubdir);
6393                subDir = isaSubdir;
6394            } else {
6395                subDir = nativeLibraryRoot;
6396            }
6397
6398            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]);
6399            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6400                return copyRet;
6401            }
6402        }
6403
6404        return abi;
6405    }
6406
6407    private void killApplication(String pkgName, int appId, String reason) {
6408        // Request the ActivityManager to kill the process(only for existing packages)
6409        // so that we do not end up in a confused state while the user is still using the older
6410        // version of the application while the new one gets installed.
6411        IActivityManager am = ActivityManagerNative.getDefault();
6412        if (am != null) {
6413            try {
6414                am.killApplicationWithAppId(pkgName, appId, reason);
6415            } catch (RemoteException e) {
6416            }
6417        }
6418    }
6419
6420    void removePackageLI(PackageSetting ps, boolean chatty) {
6421        if (DEBUG_INSTALL) {
6422            if (chatty)
6423                Log.d(TAG, "Removing package " + ps.name);
6424        }
6425
6426        // writer
6427        synchronized (mPackages) {
6428            mPackages.remove(ps.name);
6429            if (ps.codePathString != null) {
6430                mAppDirs.remove(ps.codePathString);
6431            }
6432
6433            final PackageParser.Package pkg = ps.pkg;
6434            if (pkg != null) {
6435                cleanPackageDataStructuresLILPw(pkg, chatty);
6436            }
6437        }
6438    }
6439
6440    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6441        if (DEBUG_INSTALL) {
6442            if (chatty)
6443                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6444        }
6445
6446        // writer
6447        synchronized (mPackages) {
6448            mPackages.remove(pkg.applicationInfo.packageName);
6449            if (pkg.codePath != null) {
6450                mAppDirs.remove(pkg.codePath);
6451            }
6452            cleanPackageDataStructuresLILPw(pkg, chatty);
6453        }
6454    }
6455
6456    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6457        int N = pkg.providers.size();
6458        StringBuilder r = null;
6459        int i;
6460        for (i=0; i<N; i++) {
6461            PackageParser.Provider p = pkg.providers.get(i);
6462            mProviders.removeProvider(p);
6463            if (p.info.authority == null) {
6464
6465                /* There was another ContentProvider with this authority when
6466                 * this app was installed so this authority is null,
6467                 * Ignore it as we don't have to unregister the provider.
6468                 */
6469                continue;
6470            }
6471            String names[] = p.info.authority.split(";");
6472            for (int j = 0; j < names.length; j++) {
6473                if (mProvidersByAuthority.get(names[j]) == p) {
6474                    mProvidersByAuthority.remove(names[j]);
6475                    if (DEBUG_REMOVE) {
6476                        if (chatty)
6477                            Log.d(TAG, "Unregistered content provider: " + names[j]
6478                                    + ", className = " + p.info.name + ", isSyncable = "
6479                                    + p.info.isSyncable);
6480                    }
6481                }
6482            }
6483            if (DEBUG_REMOVE && chatty) {
6484                if (r == null) {
6485                    r = new StringBuilder(256);
6486                } else {
6487                    r.append(' ');
6488                }
6489                r.append(p.info.name);
6490            }
6491        }
6492        if (r != null) {
6493            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6494        }
6495
6496        N = pkg.services.size();
6497        r = null;
6498        for (i=0; i<N; i++) {
6499            PackageParser.Service s = pkg.services.get(i);
6500            mServices.removeService(s);
6501            if (chatty) {
6502                if (r == null) {
6503                    r = new StringBuilder(256);
6504                } else {
6505                    r.append(' ');
6506                }
6507                r.append(s.info.name);
6508            }
6509        }
6510        if (r != null) {
6511            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6512        }
6513
6514        N = pkg.receivers.size();
6515        r = null;
6516        for (i=0; i<N; i++) {
6517            PackageParser.Activity a = pkg.receivers.get(i);
6518            mReceivers.removeActivity(a, "receiver");
6519            if (DEBUG_REMOVE && chatty) {
6520                if (r == null) {
6521                    r = new StringBuilder(256);
6522                } else {
6523                    r.append(' ');
6524                }
6525                r.append(a.info.name);
6526            }
6527        }
6528        if (r != null) {
6529            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6530        }
6531
6532        N = pkg.activities.size();
6533        r = null;
6534        for (i=0; i<N; i++) {
6535            PackageParser.Activity a = pkg.activities.get(i);
6536            mActivities.removeActivity(a, "activity");
6537            if (DEBUG_REMOVE && chatty) {
6538                if (r == null) {
6539                    r = new StringBuilder(256);
6540                } else {
6541                    r.append(' ');
6542                }
6543                r.append(a.info.name);
6544            }
6545        }
6546        if (r != null) {
6547            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6548        }
6549
6550        N = pkg.permissions.size();
6551        r = null;
6552        for (i=0; i<N; i++) {
6553            PackageParser.Permission p = pkg.permissions.get(i);
6554            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6555            if (bp == null) {
6556                bp = mSettings.mPermissionTrees.get(p.info.name);
6557            }
6558            if (bp != null && bp.perm == p) {
6559                bp.perm = null;
6560                if (DEBUG_REMOVE && chatty) {
6561                    if (r == null) {
6562                        r = new StringBuilder(256);
6563                    } else {
6564                        r.append(' ');
6565                    }
6566                    r.append(p.info.name);
6567                }
6568            }
6569            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6570                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6571                if (appOpPerms != null) {
6572                    appOpPerms.remove(pkg.packageName);
6573                }
6574            }
6575        }
6576        if (r != null) {
6577            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6578        }
6579
6580        N = pkg.requestedPermissions.size();
6581        r = null;
6582        for (i=0; i<N; i++) {
6583            String perm = pkg.requestedPermissions.get(i);
6584            BasePermission bp = mSettings.mPermissions.get(perm);
6585            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6586                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6587                if (appOpPerms != null) {
6588                    appOpPerms.remove(pkg.packageName);
6589                    if (appOpPerms.isEmpty()) {
6590                        mAppOpPermissionPackages.remove(perm);
6591                    }
6592                }
6593            }
6594        }
6595        if (r != null) {
6596            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6597        }
6598
6599        N = pkg.instrumentation.size();
6600        r = null;
6601        for (i=0; i<N; i++) {
6602            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6603            mInstrumentation.remove(a.getComponentName());
6604            if (DEBUG_REMOVE && chatty) {
6605                if (r == null) {
6606                    r = new StringBuilder(256);
6607                } else {
6608                    r.append(' ');
6609                }
6610                r.append(a.info.name);
6611            }
6612        }
6613        if (r != null) {
6614            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6615        }
6616
6617        r = null;
6618        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6619            // Only system apps can hold shared libraries.
6620            if (pkg.libraryNames != null) {
6621                for (i=0; i<pkg.libraryNames.size(); i++) {
6622                    String name = pkg.libraryNames.get(i);
6623                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6624                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6625                        mSharedLibraries.remove(name);
6626                        if (DEBUG_REMOVE && chatty) {
6627                            if (r == null) {
6628                                r = new StringBuilder(256);
6629                            } else {
6630                                r.append(' ');
6631                            }
6632                            r.append(name);
6633                        }
6634                    }
6635                }
6636            }
6637        }
6638        if (r != null) {
6639            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6640        }
6641    }
6642
6643    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6644        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6645            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6646                return true;
6647            }
6648        }
6649        return false;
6650    }
6651
6652    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6653    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6654    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6655
6656    private void updatePermissionsLPw(String changingPkg,
6657            PackageParser.Package pkgInfo, int flags) {
6658        // Make sure there are no dangling permission trees.
6659        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6660        while (it.hasNext()) {
6661            final BasePermission bp = it.next();
6662            if (bp.packageSetting == null) {
6663                // We may not yet have parsed the package, so just see if
6664                // we still know about its settings.
6665                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6666            }
6667            if (bp.packageSetting == null) {
6668                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6669                        + " from package " + bp.sourcePackage);
6670                it.remove();
6671            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6672                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6673                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6674                            + " from package " + bp.sourcePackage);
6675                    flags |= UPDATE_PERMISSIONS_ALL;
6676                    it.remove();
6677                }
6678            }
6679        }
6680
6681        // Make sure all dynamic permissions have been assigned to a package,
6682        // and make sure there are no dangling permissions.
6683        it = mSettings.mPermissions.values().iterator();
6684        while (it.hasNext()) {
6685            final BasePermission bp = it.next();
6686            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6687                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6688                        + bp.name + " pkg=" + bp.sourcePackage
6689                        + " info=" + bp.pendingInfo);
6690                if (bp.packageSetting == null && bp.pendingInfo != null) {
6691                    final BasePermission tree = findPermissionTreeLP(bp.name);
6692                    if (tree != null && tree.perm != null) {
6693                        bp.packageSetting = tree.packageSetting;
6694                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6695                                new PermissionInfo(bp.pendingInfo));
6696                        bp.perm.info.packageName = tree.perm.info.packageName;
6697                        bp.perm.info.name = bp.name;
6698                        bp.uid = tree.uid;
6699                    }
6700                }
6701            }
6702            if (bp.packageSetting == null) {
6703                // We may not yet have parsed the package, so just see if
6704                // we still know about its settings.
6705                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6706            }
6707            if (bp.packageSetting == null) {
6708                Slog.w(TAG, "Removing dangling permission: " + bp.name
6709                        + " from package " + bp.sourcePackage);
6710                it.remove();
6711            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6712                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6713                    Slog.i(TAG, "Removing old permission: " + bp.name
6714                            + " from package " + bp.sourcePackage);
6715                    flags |= UPDATE_PERMISSIONS_ALL;
6716                    it.remove();
6717                }
6718            }
6719        }
6720
6721        // Now update the permissions for all packages, in particular
6722        // replace the granted permissions of the system packages.
6723        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6724            for (PackageParser.Package pkg : mPackages.values()) {
6725                if (pkg != pkgInfo) {
6726                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6727                }
6728            }
6729        }
6730
6731        if (pkgInfo != null) {
6732            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6733        }
6734    }
6735
6736    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6737        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6738        if (ps == null) {
6739            return;
6740        }
6741        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6742        HashSet<String> origPermissions = gp.grantedPermissions;
6743        boolean changedPermission = false;
6744
6745        if (replace) {
6746            ps.permissionsFixed = false;
6747            if (gp == ps) {
6748                origPermissions = new HashSet<String>(gp.grantedPermissions);
6749                gp.grantedPermissions.clear();
6750                gp.gids = mGlobalGids;
6751            }
6752        }
6753
6754        if (gp.gids == null) {
6755            gp.gids = mGlobalGids;
6756        }
6757
6758        final int N = pkg.requestedPermissions.size();
6759        for (int i=0; i<N; i++) {
6760            final String name = pkg.requestedPermissions.get(i);
6761            final boolean required = pkg.requestedPermissionsRequired.get(i);
6762            final BasePermission bp = mSettings.mPermissions.get(name);
6763            if (DEBUG_INSTALL) {
6764                if (gp != ps) {
6765                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6766                }
6767            }
6768
6769            if (bp == null || bp.packageSetting == null) {
6770                Slog.w(TAG, "Unknown permission " + name
6771                        + " in package " + pkg.packageName);
6772                continue;
6773            }
6774
6775            final String perm = bp.name;
6776            boolean allowed;
6777            boolean allowedSig = false;
6778            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6779                // Keep track of app op permissions.
6780                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6781                if (pkgs == null) {
6782                    pkgs = new ArraySet<>();
6783                    mAppOpPermissionPackages.put(bp.name, pkgs);
6784                }
6785                pkgs.add(pkg.packageName);
6786            }
6787            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6788            if (level == PermissionInfo.PROTECTION_NORMAL
6789                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6790                // We grant a normal or dangerous permission if any of the following
6791                // are true:
6792                // 1) The permission is required
6793                // 2) The permission is optional, but was granted in the past
6794                // 3) The permission is optional, but was requested by an
6795                //    app in /system (not /data)
6796                //
6797                // Otherwise, reject the permission.
6798                allowed = (required || origPermissions.contains(perm)
6799                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6800            } else if (bp.packageSetting == null) {
6801                // This permission is invalid; skip it.
6802                allowed = false;
6803            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6804                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6805                if (allowed) {
6806                    allowedSig = true;
6807                }
6808            } else {
6809                allowed = false;
6810            }
6811            if (DEBUG_INSTALL) {
6812                if (gp != ps) {
6813                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6814                }
6815            }
6816            if (allowed) {
6817                if (!isSystemApp(ps) && ps.permissionsFixed) {
6818                    // If this is an existing, non-system package, then
6819                    // we can't add any new permissions to it.
6820                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6821                        // Except...  if this is a permission that was added
6822                        // to the platform (note: need to only do this when
6823                        // updating the platform).
6824                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6825                    }
6826                }
6827                if (allowed) {
6828                    if (!gp.grantedPermissions.contains(perm)) {
6829                        changedPermission = true;
6830                        gp.grantedPermissions.add(perm);
6831                        gp.gids = appendInts(gp.gids, bp.gids);
6832                    } else if (!ps.haveGids) {
6833                        gp.gids = appendInts(gp.gids, bp.gids);
6834                    }
6835                } else {
6836                    Slog.w(TAG, "Not granting permission " + perm
6837                            + " to package " + pkg.packageName
6838                            + " because it was previously installed without");
6839                }
6840            } else {
6841                if (gp.grantedPermissions.remove(perm)) {
6842                    changedPermission = true;
6843                    gp.gids = removeInts(gp.gids, bp.gids);
6844                    Slog.i(TAG, "Un-granting permission " + perm
6845                            + " from package " + pkg.packageName
6846                            + " (protectionLevel=" + bp.protectionLevel
6847                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6848                            + ")");
6849                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6850                    // Don't print warning for app op permissions, since it is fine for them
6851                    // not to be granted, there is a UI for the user to decide.
6852                    Slog.w(TAG, "Not granting permission " + perm
6853                            + " to package " + pkg.packageName
6854                            + " (protectionLevel=" + bp.protectionLevel
6855                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6856                            + ")");
6857                }
6858            }
6859        }
6860
6861        if ((changedPermission || replace) && !ps.permissionsFixed &&
6862                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6863            // This is the first that we have heard about this package, so the
6864            // permissions we have now selected are fixed until explicitly
6865            // changed.
6866            ps.permissionsFixed = true;
6867        }
6868        ps.haveGids = true;
6869    }
6870
6871    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6872        boolean allowed = false;
6873        final int NP = PackageParser.NEW_PERMISSIONS.length;
6874        for (int ip=0; ip<NP; ip++) {
6875            final PackageParser.NewPermissionInfo npi
6876                    = PackageParser.NEW_PERMISSIONS[ip];
6877            if (npi.name.equals(perm)
6878                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6879                allowed = true;
6880                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6881                        + pkg.packageName);
6882                break;
6883            }
6884        }
6885        return allowed;
6886    }
6887
6888    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6889                                          BasePermission bp, HashSet<String> origPermissions) {
6890        boolean allowed;
6891        allowed = (compareSignatures(
6892                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6893                        == PackageManager.SIGNATURE_MATCH)
6894                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6895                        == PackageManager.SIGNATURE_MATCH);
6896        if (!allowed && (bp.protectionLevel
6897                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6898            if (isSystemApp(pkg)) {
6899                // For updated system applications, a system permission
6900                // is granted only if it had been defined by the original application.
6901                if (isUpdatedSystemApp(pkg)) {
6902                    final PackageSetting sysPs = mSettings
6903                            .getDisabledSystemPkgLPr(pkg.packageName);
6904                    final GrantedPermissions origGp = sysPs.sharedUser != null
6905                            ? sysPs.sharedUser : sysPs;
6906
6907                    if (origGp.grantedPermissions.contains(perm)) {
6908                        // If the original was granted this permission, we take
6909                        // that grant decision as read and propagate it to the
6910                        // update.
6911                        allowed = true;
6912                    } else {
6913                        // The system apk may have been updated with an older
6914                        // version of the one on the data partition, but which
6915                        // granted a new system permission that it didn't have
6916                        // before.  In this case we do want to allow the app to
6917                        // now get the new permission if the ancestral apk is
6918                        // privileged to get it.
6919                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6920                            for (int j=0;
6921                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6922                                if (perm.equals(
6923                                        sysPs.pkg.requestedPermissions.get(j))) {
6924                                    allowed = true;
6925                                    break;
6926                                }
6927                            }
6928                        }
6929                    }
6930                } else {
6931                    allowed = isPrivilegedApp(pkg);
6932                }
6933            }
6934        }
6935        if (!allowed && (bp.protectionLevel
6936                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6937            // For development permissions, a development permission
6938            // is granted only if it was already granted.
6939            allowed = origPermissions.contains(perm);
6940        }
6941        return allowed;
6942    }
6943
6944    final class ActivityIntentResolver
6945            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6946        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6947                boolean defaultOnly, int userId) {
6948            if (!sUserManager.exists(userId)) return null;
6949            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6950            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6951        }
6952
6953        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6954                int userId) {
6955            if (!sUserManager.exists(userId)) return null;
6956            mFlags = flags;
6957            return super.queryIntent(intent, resolvedType,
6958                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6959        }
6960
6961        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6962                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6963            if (!sUserManager.exists(userId)) return null;
6964            if (packageActivities == null) {
6965                return null;
6966            }
6967            mFlags = flags;
6968            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6969            final int N = packageActivities.size();
6970            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6971                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6972
6973            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6974            for (int i = 0; i < N; ++i) {
6975                intentFilters = packageActivities.get(i).intents;
6976                if (intentFilters != null && intentFilters.size() > 0) {
6977                    PackageParser.ActivityIntentInfo[] array =
6978                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6979                    intentFilters.toArray(array);
6980                    listCut.add(array);
6981                }
6982            }
6983            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6984        }
6985
6986        public final void addActivity(PackageParser.Activity a, String type) {
6987            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6988            mActivities.put(a.getComponentName(), a);
6989            if (DEBUG_SHOW_INFO)
6990                Log.v(
6991                TAG, "  " + type + " " +
6992                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6993            if (DEBUG_SHOW_INFO)
6994                Log.v(TAG, "    Class=" + a.info.name);
6995            final int NI = a.intents.size();
6996            for (int j=0; j<NI; j++) {
6997                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6998                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6999                    intent.setPriority(0);
7000                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7001                            + a.className + " with priority > 0, forcing to 0");
7002                }
7003                if (DEBUG_SHOW_INFO) {
7004                    Log.v(TAG, "    IntentFilter:");
7005                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7006                }
7007                if (!intent.debugCheck()) {
7008                    Log.w(TAG, "==> For Activity " + a.info.name);
7009                }
7010                addFilter(intent);
7011            }
7012        }
7013
7014        public final void removeActivity(PackageParser.Activity a, String type) {
7015            mActivities.remove(a.getComponentName());
7016            if (DEBUG_SHOW_INFO) {
7017                Log.v(TAG, "  " + type + " "
7018                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7019                                : a.info.name) + ":");
7020                Log.v(TAG, "    Class=" + a.info.name);
7021            }
7022            final int NI = a.intents.size();
7023            for (int j=0; j<NI; j++) {
7024                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7025                if (DEBUG_SHOW_INFO) {
7026                    Log.v(TAG, "    IntentFilter:");
7027                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7028                }
7029                removeFilter(intent);
7030            }
7031        }
7032
7033        @Override
7034        protected boolean allowFilterResult(
7035                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7036            ActivityInfo filterAi = filter.activity.info;
7037            for (int i=dest.size()-1; i>=0; i--) {
7038                ActivityInfo destAi = dest.get(i).activityInfo;
7039                if (destAi.name == filterAi.name
7040                        && destAi.packageName == filterAi.packageName) {
7041                    return false;
7042                }
7043            }
7044            return true;
7045        }
7046
7047        @Override
7048        protected ActivityIntentInfo[] newArray(int size) {
7049            return new ActivityIntentInfo[size];
7050        }
7051
7052        @Override
7053        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7054            if (!sUserManager.exists(userId)) return true;
7055            PackageParser.Package p = filter.activity.owner;
7056            if (p != null) {
7057                PackageSetting ps = (PackageSetting)p.mExtras;
7058                if (ps != null) {
7059                    // System apps are never considered stopped for purposes of
7060                    // filtering, because there may be no way for the user to
7061                    // actually re-launch them.
7062                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7063                            && ps.getStopped(userId);
7064                }
7065            }
7066            return false;
7067        }
7068
7069        @Override
7070        protected boolean isPackageForFilter(String packageName,
7071                PackageParser.ActivityIntentInfo info) {
7072            return packageName.equals(info.activity.owner.packageName);
7073        }
7074
7075        @Override
7076        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7077                int match, int userId) {
7078            if (!sUserManager.exists(userId)) return null;
7079            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7080                return null;
7081            }
7082            final PackageParser.Activity activity = info.activity;
7083            if (mSafeMode && (activity.info.applicationInfo.flags
7084                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7085                return null;
7086            }
7087            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7088            if (ps == null) {
7089                return null;
7090            }
7091            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7092                    ps.readUserState(userId), userId);
7093            if (ai == null) {
7094                return null;
7095            }
7096            final ResolveInfo res = new ResolveInfo();
7097            res.activityInfo = ai;
7098            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7099                res.filter = info;
7100            }
7101            res.priority = info.getPriority();
7102            res.preferredOrder = activity.owner.mPreferredOrder;
7103            //System.out.println("Result: " + res.activityInfo.className +
7104            //                   " = " + res.priority);
7105            res.match = match;
7106            res.isDefault = info.hasDefault;
7107            res.labelRes = info.labelRes;
7108            res.nonLocalizedLabel = info.nonLocalizedLabel;
7109            if (userNeedsBadging(userId)) {
7110                res.noResourceId = true;
7111            } else {
7112                res.icon = info.icon;
7113            }
7114            res.system = isSystemApp(res.activityInfo.applicationInfo);
7115            return res;
7116        }
7117
7118        @Override
7119        protected void sortResults(List<ResolveInfo> results) {
7120            Collections.sort(results, mResolvePrioritySorter);
7121        }
7122
7123        @Override
7124        protected void dumpFilter(PrintWriter out, String prefix,
7125                PackageParser.ActivityIntentInfo filter) {
7126            out.print(prefix); out.print(
7127                    Integer.toHexString(System.identityHashCode(filter.activity)));
7128                    out.print(' ');
7129                    filter.activity.printComponentShortName(out);
7130                    out.print(" filter ");
7131                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7132        }
7133
7134//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7135//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7136//            final List<ResolveInfo> retList = Lists.newArrayList();
7137//            while (i.hasNext()) {
7138//                final ResolveInfo resolveInfo = i.next();
7139//                if (isEnabledLP(resolveInfo.activityInfo)) {
7140//                    retList.add(resolveInfo);
7141//                }
7142//            }
7143//            return retList;
7144//        }
7145
7146        // Keys are String (activity class name), values are Activity.
7147        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7148                = new HashMap<ComponentName, PackageParser.Activity>();
7149        private int mFlags;
7150    }
7151
7152    private final class ServiceIntentResolver
7153            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7154        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7155                boolean defaultOnly, int userId) {
7156            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7157            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7158        }
7159
7160        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7161                int userId) {
7162            if (!sUserManager.exists(userId)) return null;
7163            mFlags = flags;
7164            return super.queryIntent(intent, resolvedType,
7165                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7166        }
7167
7168        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7169                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7170            if (!sUserManager.exists(userId)) return null;
7171            if (packageServices == null) {
7172                return null;
7173            }
7174            mFlags = flags;
7175            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7176            final int N = packageServices.size();
7177            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7178                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7179
7180            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7181            for (int i = 0; i < N; ++i) {
7182                intentFilters = packageServices.get(i).intents;
7183                if (intentFilters != null && intentFilters.size() > 0) {
7184                    PackageParser.ServiceIntentInfo[] array =
7185                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7186                    intentFilters.toArray(array);
7187                    listCut.add(array);
7188                }
7189            }
7190            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7191        }
7192
7193        public final void addService(PackageParser.Service s) {
7194            mServices.put(s.getComponentName(), s);
7195            if (DEBUG_SHOW_INFO) {
7196                Log.v(TAG, "  "
7197                        + (s.info.nonLocalizedLabel != null
7198                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7199                Log.v(TAG, "    Class=" + s.info.name);
7200            }
7201            final int NI = s.intents.size();
7202            int j;
7203            for (j=0; j<NI; j++) {
7204                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7205                if (DEBUG_SHOW_INFO) {
7206                    Log.v(TAG, "    IntentFilter:");
7207                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7208                }
7209                if (!intent.debugCheck()) {
7210                    Log.w(TAG, "==> For Service " + s.info.name);
7211                }
7212                addFilter(intent);
7213            }
7214        }
7215
7216        public final void removeService(PackageParser.Service s) {
7217            mServices.remove(s.getComponentName());
7218            if (DEBUG_SHOW_INFO) {
7219                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7220                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7221                Log.v(TAG, "    Class=" + s.info.name);
7222            }
7223            final int NI = s.intents.size();
7224            int j;
7225            for (j=0; j<NI; j++) {
7226                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7227                if (DEBUG_SHOW_INFO) {
7228                    Log.v(TAG, "    IntentFilter:");
7229                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7230                }
7231                removeFilter(intent);
7232            }
7233        }
7234
7235        @Override
7236        protected boolean allowFilterResult(
7237                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7238            ServiceInfo filterSi = filter.service.info;
7239            for (int i=dest.size()-1; i>=0; i--) {
7240                ServiceInfo destAi = dest.get(i).serviceInfo;
7241                if (destAi.name == filterSi.name
7242                        && destAi.packageName == filterSi.packageName) {
7243                    return false;
7244                }
7245            }
7246            return true;
7247        }
7248
7249        @Override
7250        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7251            return new PackageParser.ServiceIntentInfo[size];
7252        }
7253
7254        @Override
7255        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7256            if (!sUserManager.exists(userId)) return true;
7257            PackageParser.Package p = filter.service.owner;
7258            if (p != null) {
7259                PackageSetting ps = (PackageSetting)p.mExtras;
7260                if (ps != null) {
7261                    // System apps are never considered stopped for purposes of
7262                    // filtering, because there may be no way for the user to
7263                    // actually re-launch them.
7264                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7265                            && ps.getStopped(userId);
7266                }
7267            }
7268            return false;
7269        }
7270
7271        @Override
7272        protected boolean isPackageForFilter(String packageName,
7273                PackageParser.ServiceIntentInfo info) {
7274            return packageName.equals(info.service.owner.packageName);
7275        }
7276
7277        @Override
7278        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7279                int match, int userId) {
7280            if (!sUserManager.exists(userId)) return null;
7281            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7282            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7283                return null;
7284            }
7285            final PackageParser.Service service = info.service;
7286            if (mSafeMode && (service.info.applicationInfo.flags
7287                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7288                return null;
7289            }
7290            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7291            if (ps == null) {
7292                return null;
7293            }
7294            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7295                    ps.readUserState(userId), userId);
7296            if (si == null) {
7297                return null;
7298            }
7299            final ResolveInfo res = new ResolveInfo();
7300            res.serviceInfo = si;
7301            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7302                res.filter = filter;
7303            }
7304            res.priority = info.getPriority();
7305            res.preferredOrder = service.owner.mPreferredOrder;
7306            //System.out.println("Result: " + res.activityInfo.className +
7307            //                   " = " + res.priority);
7308            res.match = match;
7309            res.isDefault = info.hasDefault;
7310            res.labelRes = info.labelRes;
7311            res.nonLocalizedLabel = info.nonLocalizedLabel;
7312            res.icon = info.icon;
7313            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7314            return res;
7315        }
7316
7317        @Override
7318        protected void sortResults(List<ResolveInfo> results) {
7319            Collections.sort(results, mResolvePrioritySorter);
7320        }
7321
7322        @Override
7323        protected void dumpFilter(PrintWriter out, String prefix,
7324                PackageParser.ServiceIntentInfo filter) {
7325            out.print(prefix); out.print(
7326                    Integer.toHexString(System.identityHashCode(filter.service)));
7327                    out.print(' ');
7328                    filter.service.printComponentShortName(out);
7329                    out.print(" filter ");
7330                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7331        }
7332
7333//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7334//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7335//            final List<ResolveInfo> retList = Lists.newArrayList();
7336//            while (i.hasNext()) {
7337//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7338//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7339//                    retList.add(resolveInfo);
7340//                }
7341//            }
7342//            return retList;
7343//        }
7344
7345        // Keys are String (activity class name), values are Activity.
7346        private final HashMap<ComponentName, PackageParser.Service> mServices
7347                = new HashMap<ComponentName, PackageParser.Service>();
7348        private int mFlags;
7349    };
7350
7351    private final class ProviderIntentResolver
7352            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7353        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7354                boolean defaultOnly, int userId) {
7355            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7356            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7357        }
7358
7359        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7360                int userId) {
7361            if (!sUserManager.exists(userId))
7362                return null;
7363            mFlags = flags;
7364            return super.queryIntent(intent, resolvedType,
7365                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7366        }
7367
7368        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7369                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7370            if (!sUserManager.exists(userId))
7371                return null;
7372            if (packageProviders == null) {
7373                return null;
7374            }
7375            mFlags = flags;
7376            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7377            final int N = packageProviders.size();
7378            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7379                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7380
7381            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7382            for (int i = 0; i < N; ++i) {
7383                intentFilters = packageProviders.get(i).intents;
7384                if (intentFilters != null && intentFilters.size() > 0) {
7385                    PackageParser.ProviderIntentInfo[] array =
7386                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7387                    intentFilters.toArray(array);
7388                    listCut.add(array);
7389                }
7390            }
7391            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7392        }
7393
7394        public final void addProvider(PackageParser.Provider p) {
7395            if (mProviders.containsKey(p.getComponentName())) {
7396                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7397                return;
7398            }
7399
7400            mProviders.put(p.getComponentName(), p);
7401            if (DEBUG_SHOW_INFO) {
7402                Log.v(TAG, "  "
7403                        + (p.info.nonLocalizedLabel != null
7404                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7405                Log.v(TAG, "    Class=" + p.info.name);
7406            }
7407            final int NI = p.intents.size();
7408            int j;
7409            for (j = 0; j < NI; j++) {
7410                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7411                if (DEBUG_SHOW_INFO) {
7412                    Log.v(TAG, "    IntentFilter:");
7413                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7414                }
7415                if (!intent.debugCheck()) {
7416                    Log.w(TAG, "==> For Provider " + p.info.name);
7417                }
7418                addFilter(intent);
7419            }
7420        }
7421
7422        public final void removeProvider(PackageParser.Provider p) {
7423            mProviders.remove(p.getComponentName());
7424            if (DEBUG_SHOW_INFO) {
7425                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7426                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7427                Log.v(TAG, "    Class=" + p.info.name);
7428            }
7429            final int NI = p.intents.size();
7430            int j;
7431            for (j = 0; j < NI; j++) {
7432                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7433                if (DEBUG_SHOW_INFO) {
7434                    Log.v(TAG, "    IntentFilter:");
7435                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7436                }
7437                removeFilter(intent);
7438            }
7439        }
7440
7441        @Override
7442        protected boolean allowFilterResult(
7443                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7444            ProviderInfo filterPi = filter.provider.info;
7445            for (int i = dest.size() - 1; i >= 0; i--) {
7446                ProviderInfo destPi = dest.get(i).providerInfo;
7447                if (destPi.name == filterPi.name
7448                        && destPi.packageName == filterPi.packageName) {
7449                    return false;
7450                }
7451            }
7452            return true;
7453        }
7454
7455        @Override
7456        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7457            return new PackageParser.ProviderIntentInfo[size];
7458        }
7459
7460        @Override
7461        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7462            if (!sUserManager.exists(userId))
7463                return true;
7464            PackageParser.Package p = filter.provider.owner;
7465            if (p != null) {
7466                PackageSetting ps = (PackageSetting) p.mExtras;
7467                if (ps != null) {
7468                    // System apps are never considered stopped for purposes of
7469                    // filtering, because there may be no way for the user to
7470                    // actually re-launch them.
7471                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7472                            && ps.getStopped(userId);
7473                }
7474            }
7475            return false;
7476        }
7477
7478        @Override
7479        protected boolean isPackageForFilter(String packageName,
7480                PackageParser.ProviderIntentInfo info) {
7481            return packageName.equals(info.provider.owner.packageName);
7482        }
7483
7484        @Override
7485        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7486                int match, int userId) {
7487            if (!sUserManager.exists(userId))
7488                return null;
7489            final PackageParser.ProviderIntentInfo info = filter;
7490            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7491                return null;
7492            }
7493            final PackageParser.Provider provider = info.provider;
7494            if (mSafeMode && (provider.info.applicationInfo.flags
7495                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7496                return null;
7497            }
7498            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7499            if (ps == null) {
7500                return null;
7501            }
7502            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7503                    ps.readUserState(userId), userId);
7504            if (pi == null) {
7505                return null;
7506            }
7507            final ResolveInfo res = new ResolveInfo();
7508            res.providerInfo = pi;
7509            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7510                res.filter = filter;
7511            }
7512            res.priority = info.getPriority();
7513            res.preferredOrder = provider.owner.mPreferredOrder;
7514            res.match = match;
7515            res.isDefault = info.hasDefault;
7516            res.labelRes = info.labelRes;
7517            res.nonLocalizedLabel = info.nonLocalizedLabel;
7518            res.icon = info.icon;
7519            res.system = isSystemApp(res.providerInfo.applicationInfo);
7520            return res;
7521        }
7522
7523        @Override
7524        protected void sortResults(List<ResolveInfo> results) {
7525            Collections.sort(results, mResolvePrioritySorter);
7526        }
7527
7528        @Override
7529        protected void dumpFilter(PrintWriter out, String prefix,
7530                PackageParser.ProviderIntentInfo filter) {
7531            out.print(prefix);
7532            out.print(
7533                    Integer.toHexString(System.identityHashCode(filter.provider)));
7534            out.print(' ');
7535            filter.provider.printComponentShortName(out);
7536            out.print(" filter ");
7537            out.println(Integer.toHexString(System.identityHashCode(filter)));
7538        }
7539
7540        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7541                = new HashMap<ComponentName, PackageParser.Provider>();
7542        private int mFlags;
7543    };
7544
7545    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7546            new Comparator<ResolveInfo>() {
7547        public int compare(ResolveInfo r1, ResolveInfo r2) {
7548            int v1 = r1.priority;
7549            int v2 = r2.priority;
7550            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7551            if (v1 != v2) {
7552                return (v1 > v2) ? -1 : 1;
7553            }
7554            v1 = r1.preferredOrder;
7555            v2 = r2.preferredOrder;
7556            if (v1 != v2) {
7557                return (v1 > v2) ? -1 : 1;
7558            }
7559            if (r1.isDefault != r2.isDefault) {
7560                return r1.isDefault ? -1 : 1;
7561            }
7562            v1 = r1.match;
7563            v2 = r2.match;
7564            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7565            if (v1 != v2) {
7566                return (v1 > v2) ? -1 : 1;
7567            }
7568            if (r1.system != r2.system) {
7569                return r1.system ? -1 : 1;
7570            }
7571            return 0;
7572        }
7573    };
7574
7575    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7576            new Comparator<ProviderInfo>() {
7577        public int compare(ProviderInfo p1, ProviderInfo p2) {
7578            final int v1 = p1.initOrder;
7579            final int v2 = p2.initOrder;
7580            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7581        }
7582    };
7583
7584    static final void sendPackageBroadcast(String action, String pkg,
7585            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7586            int[] userIds) {
7587        IActivityManager am = ActivityManagerNative.getDefault();
7588        if (am != null) {
7589            try {
7590                if (userIds == null) {
7591                    userIds = am.getRunningUserIds();
7592                }
7593                for (int id : userIds) {
7594                    final Intent intent = new Intent(action,
7595                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7596                    if (extras != null) {
7597                        intent.putExtras(extras);
7598                    }
7599                    if (targetPkg != null) {
7600                        intent.setPackage(targetPkg);
7601                    }
7602                    // Modify the UID when posting to other users
7603                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7604                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7605                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7606                        intent.putExtra(Intent.EXTRA_UID, uid);
7607                    }
7608                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7609                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7610                    if (DEBUG_BROADCASTS) {
7611                        RuntimeException here = new RuntimeException("here");
7612                        here.fillInStackTrace();
7613                        Slog.d(TAG, "Sending to user " + id + ": "
7614                                + intent.toShortString(false, true, false, false)
7615                                + " " + intent.getExtras(), here);
7616                    }
7617                    am.broadcastIntent(null, intent, null, finishedReceiver,
7618                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7619                            finishedReceiver != null, false, id);
7620                }
7621            } catch (RemoteException ex) {
7622            }
7623        }
7624    }
7625
7626    /**
7627     * Check if the external storage media is available. This is true if there
7628     * is a mounted external storage medium or if the external storage is
7629     * emulated.
7630     */
7631    private boolean isExternalMediaAvailable() {
7632        return mMediaMounted || Environment.isExternalStorageEmulated();
7633    }
7634
7635    @Override
7636    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7637        // writer
7638        synchronized (mPackages) {
7639            if (!isExternalMediaAvailable()) {
7640                // If the external storage is no longer mounted at this point,
7641                // the caller may not have been able to delete all of this
7642                // packages files and can not delete any more.  Bail.
7643                return null;
7644            }
7645            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7646            if (lastPackage != null) {
7647                pkgs.remove(lastPackage);
7648            }
7649            if (pkgs.size() > 0) {
7650                return pkgs.get(0);
7651            }
7652        }
7653        return null;
7654    }
7655
7656    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7657        if (false) {
7658            RuntimeException here = new RuntimeException("here");
7659            here.fillInStackTrace();
7660            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7661                    + " andCode=" + andCode, here);
7662        }
7663        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7664                userId, andCode ? 1 : 0, packageName));
7665    }
7666
7667    void startCleaningPackages() {
7668        // reader
7669        synchronized (mPackages) {
7670            if (!isExternalMediaAvailable()) {
7671                return;
7672            }
7673            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7674                return;
7675            }
7676        }
7677        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7678        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7679        IActivityManager am = ActivityManagerNative.getDefault();
7680        if (am != null) {
7681            try {
7682                am.startService(null, intent, null, UserHandle.USER_OWNER);
7683            } catch (RemoteException e) {
7684            }
7685        }
7686    }
7687
7688    @Override
7689    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7690            String installerPackageName, VerificationParams verificationParams,
7691            String packageAbiOverride) {
7692        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7693                null);
7694
7695        final File originFile = new File(originPath);
7696        final int uid = Binder.getCallingUid();
7697        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7698            try {
7699                if (observer != null) {
7700                    observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null);
7701                }
7702            } catch (RemoteException re) {
7703            }
7704            return;
7705        }
7706
7707        UserHandle user;
7708        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7709            user = UserHandle.ALL;
7710        } else {
7711            user = new UserHandle(UserHandle.getUserId(uid));
7712        }
7713
7714        final int filteredFlags;
7715        if (uid == Process.SHELL_UID || uid == 0) {
7716            if (DEBUG_INSTALL) {
7717                Slog.v(TAG, "Install from ADB");
7718            }
7719            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7720        } else {
7721            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7722        }
7723
7724        verificationParams.setInstallerUid(uid);
7725
7726        final Message msg = mHandler.obtainMessage(INIT_COPY);
7727        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7728                installerPackageName, verificationParams, user, packageAbiOverride);
7729        mHandler.sendMessage(msg);
7730    }
7731
7732    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7733            InstallSessionParams params, String installerPackageName, int installerUid,
7734            UserHandle user) {
7735        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7736                params.referrerUri, installerUid, null);
7737
7738        final Message msg = mHandler.obtainMessage(INIT_COPY);
7739        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7740                installerPackageName, verifParams, user, params.abiOverride);
7741        mHandler.sendMessage(msg);
7742    }
7743
7744    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7745        Bundle extras = new Bundle(1);
7746        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7747
7748        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7749                packageName, extras, null, null, new int[] {userId});
7750        try {
7751            IActivityManager am = ActivityManagerNative.getDefault();
7752            final boolean isSystem =
7753                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7754            if (isSystem && am.isUserRunning(userId, false)) {
7755                // The just-installed/enabled app is bundled on the system, so presumed
7756                // to be able to run automatically without needing an explicit launch.
7757                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7758                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7759                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7760                        .setPackage(packageName);
7761                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7762                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7763            }
7764        } catch (RemoteException e) {
7765            // shouldn't happen
7766            Slog.w(TAG, "Unable to bootstrap installed package", e);
7767        }
7768    }
7769
7770    @Override
7771    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7772            int userId) {
7773        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7774        PackageSetting pkgSetting;
7775        final int uid = Binder.getCallingUid();
7776        if (UserHandle.getUserId(uid) != userId) {
7777            mContext.enforceCallingOrSelfPermission(
7778                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7779                    "setApplicationHiddenSetting for user " + userId);
7780        }
7781
7782        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7783            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7784            return false;
7785        }
7786
7787        long callingId = Binder.clearCallingIdentity();
7788        try {
7789            boolean sendAdded = false;
7790            boolean sendRemoved = false;
7791            // writer
7792            synchronized (mPackages) {
7793                pkgSetting = mSettings.mPackages.get(packageName);
7794                if (pkgSetting == null) {
7795                    return false;
7796                }
7797                if (pkgSetting.getHidden(userId) != hidden) {
7798                    pkgSetting.setHidden(hidden, userId);
7799                    mSettings.writePackageRestrictionsLPr(userId);
7800                    if (hidden) {
7801                        sendRemoved = true;
7802                    } else {
7803                        sendAdded = true;
7804                    }
7805                }
7806            }
7807            if (sendAdded) {
7808                sendPackageAddedForUser(packageName, pkgSetting, userId);
7809                return true;
7810            }
7811            if (sendRemoved) {
7812                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7813                        "hiding pkg");
7814                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7815            }
7816        } finally {
7817            Binder.restoreCallingIdentity(callingId);
7818        }
7819        return false;
7820    }
7821
7822    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7823            int userId) {
7824        final PackageRemovedInfo info = new PackageRemovedInfo();
7825        info.removedPackage = packageName;
7826        info.removedUsers = new int[] {userId};
7827        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7828        info.sendBroadcast(false, false, false);
7829    }
7830
7831    /**
7832     * Returns true if application is not found or there was an error. Otherwise it returns
7833     * the hidden state of the package for the given user.
7834     */
7835    @Override
7836    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7837        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7838        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7839                "getApplicationHidden for user " + userId);
7840        PackageSetting pkgSetting;
7841        long callingId = Binder.clearCallingIdentity();
7842        try {
7843            // writer
7844            synchronized (mPackages) {
7845                pkgSetting = mSettings.mPackages.get(packageName);
7846                if (pkgSetting == null) {
7847                    return true;
7848                }
7849                return pkgSetting.getHidden(userId);
7850            }
7851        } finally {
7852            Binder.restoreCallingIdentity(callingId);
7853        }
7854    }
7855
7856    /**
7857     * @hide
7858     */
7859    @Override
7860    public int installExistingPackageAsUser(String packageName, int userId) {
7861        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7862                null);
7863        PackageSetting pkgSetting;
7864        final int uid = Binder.getCallingUid();
7865        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7866        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7867            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7868        }
7869
7870        long callingId = Binder.clearCallingIdentity();
7871        try {
7872            boolean sendAdded = false;
7873            Bundle extras = new Bundle(1);
7874
7875            // writer
7876            synchronized (mPackages) {
7877                pkgSetting = mSettings.mPackages.get(packageName);
7878                if (pkgSetting == null) {
7879                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7880                }
7881                if (!pkgSetting.getInstalled(userId)) {
7882                    pkgSetting.setInstalled(true, userId);
7883                    pkgSetting.setHidden(false, userId);
7884                    mSettings.writePackageRestrictionsLPr(userId);
7885                    sendAdded = true;
7886                }
7887            }
7888
7889            if (sendAdded) {
7890                sendPackageAddedForUser(packageName, pkgSetting, userId);
7891            }
7892        } finally {
7893            Binder.restoreCallingIdentity(callingId);
7894        }
7895
7896        return PackageManager.INSTALL_SUCCEEDED;
7897    }
7898
7899    boolean isUserRestricted(int userId, String restrictionKey) {
7900        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7901        if (restrictions.getBoolean(restrictionKey, false)) {
7902            Log.w(TAG, "User is restricted: " + restrictionKey);
7903            return true;
7904        }
7905        return false;
7906    }
7907
7908    @Override
7909    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7910        mContext.enforceCallingOrSelfPermission(
7911                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7912                "Only package verification agents can verify applications");
7913
7914        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7915        final PackageVerificationResponse response = new PackageVerificationResponse(
7916                verificationCode, Binder.getCallingUid());
7917        msg.arg1 = id;
7918        msg.obj = response;
7919        mHandler.sendMessage(msg);
7920    }
7921
7922    @Override
7923    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7924            long millisecondsToDelay) {
7925        mContext.enforceCallingOrSelfPermission(
7926                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7927                "Only package verification agents can extend verification timeouts");
7928
7929        final PackageVerificationState state = mPendingVerification.get(id);
7930        final PackageVerificationResponse response = new PackageVerificationResponse(
7931                verificationCodeAtTimeout, Binder.getCallingUid());
7932
7933        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7934            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7935        }
7936        if (millisecondsToDelay < 0) {
7937            millisecondsToDelay = 0;
7938        }
7939        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7940                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7941            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7942        }
7943
7944        if ((state != null) && !state.timeoutExtended()) {
7945            state.extendTimeout();
7946
7947            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7948            msg.arg1 = id;
7949            msg.obj = response;
7950            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7951        }
7952    }
7953
7954    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7955            int verificationCode, UserHandle user) {
7956        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7957        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7958        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7959        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7960        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7961
7962        mContext.sendBroadcastAsUser(intent, user,
7963                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7964    }
7965
7966    private ComponentName matchComponentForVerifier(String packageName,
7967            List<ResolveInfo> receivers) {
7968        ActivityInfo targetReceiver = null;
7969
7970        final int NR = receivers.size();
7971        for (int i = 0; i < NR; i++) {
7972            final ResolveInfo info = receivers.get(i);
7973            if (info.activityInfo == null) {
7974                continue;
7975            }
7976
7977            if (packageName.equals(info.activityInfo.packageName)) {
7978                targetReceiver = info.activityInfo;
7979                break;
7980            }
7981        }
7982
7983        if (targetReceiver == null) {
7984            return null;
7985        }
7986
7987        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7988    }
7989
7990    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7991            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7992        if (pkgInfo.verifiers.length == 0) {
7993            return null;
7994        }
7995
7996        final int N = pkgInfo.verifiers.length;
7997        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7998        for (int i = 0; i < N; i++) {
7999            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8000
8001            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8002                    receivers);
8003            if (comp == null) {
8004                continue;
8005            }
8006
8007            final int verifierUid = getUidForVerifier(verifierInfo);
8008            if (verifierUid == -1) {
8009                continue;
8010            }
8011
8012            if (DEBUG_VERIFY) {
8013                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8014                        + " with the correct signature");
8015            }
8016            sufficientVerifiers.add(comp);
8017            verificationState.addSufficientVerifier(verifierUid);
8018        }
8019
8020        return sufficientVerifiers;
8021    }
8022
8023    private int getUidForVerifier(VerifierInfo verifierInfo) {
8024        synchronized (mPackages) {
8025            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8026            if (pkg == null) {
8027                return -1;
8028            } else if (pkg.mSignatures.length != 1) {
8029                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8030                        + " has more than one signature; ignoring");
8031                return -1;
8032            }
8033
8034            /*
8035             * If the public key of the package's signature does not match
8036             * our expected public key, then this is a different package and
8037             * we should skip.
8038             */
8039
8040            final byte[] expectedPublicKey;
8041            try {
8042                final Signature verifierSig = pkg.mSignatures[0];
8043                final PublicKey publicKey = verifierSig.getPublicKey();
8044                expectedPublicKey = publicKey.getEncoded();
8045            } catch (CertificateException e) {
8046                return -1;
8047            }
8048
8049            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8050
8051            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8052                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8053                        + " does not have the expected public key; ignoring");
8054                return -1;
8055            }
8056
8057            return pkg.applicationInfo.uid;
8058        }
8059    }
8060
8061    @Override
8062    public void finishPackageInstall(int token) {
8063        enforceSystemOrRoot("Only the system is allowed to finish installs");
8064
8065        if (DEBUG_INSTALL) {
8066            Slog.v(TAG, "BM finishing package install for " + token);
8067        }
8068
8069        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8070        mHandler.sendMessage(msg);
8071    }
8072
8073    /**
8074     * Get the verification agent timeout.
8075     *
8076     * @return verification timeout in milliseconds
8077     */
8078    private long getVerificationTimeout() {
8079        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8080                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8081                DEFAULT_VERIFICATION_TIMEOUT);
8082    }
8083
8084    /**
8085     * Get the default verification agent response code.
8086     *
8087     * @return default verification response code
8088     */
8089    private int getDefaultVerificationResponse() {
8090        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8091                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8092                DEFAULT_VERIFICATION_RESPONSE);
8093    }
8094
8095    /**
8096     * Check whether or not package verification has been enabled.
8097     *
8098     * @return true if verification should be performed
8099     */
8100    private boolean isVerificationEnabled(int userId, int flags) {
8101        if (!DEFAULT_VERIFY_ENABLE) {
8102            return false;
8103        }
8104
8105        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8106
8107        // Check if installing from ADB
8108        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8109            // Do not run verification in a test harness environment
8110            if (ActivityManager.isRunningInTestHarness()) {
8111                return false;
8112            }
8113            if (ensureVerifyAppsEnabled) {
8114                return true;
8115            }
8116            // Check if the developer does not want package verification for ADB installs
8117            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8118                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8119                return false;
8120            }
8121        }
8122
8123        if (ensureVerifyAppsEnabled) {
8124            return true;
8125        }
8126
8127        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8128                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8129    }
8130
8131    /**
8132     * Get the "allow unknown sources" setting.
8133     *
8134     * @return the current "allow unknown sources" setting
8135     */
8136    private int getUnknownSourcesSettings() {
8137        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8138                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8139                -1);
8140    }
8141
8142    @Override
8143    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8144        final int uid = Binder.getCallingUid();
8145        // writer
8146        synchronized (mPackages) {
8147            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8148            if (targetPackageSetting == null) {
8149                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8150            }
8151
8152            PackageSetting installerPackageSetting;
8153            if (installerPackageName != null) {
8154                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8155                if (installerPackageSetting == null) {
8156                    throw new IllegalArgumentException("Unknown installer package: "
8157                            + installerPackageName);
8158                }
8159            } else {
8160                installerPackageSetting = null;
8161            }
8162
8163            Signature[] callerSignature;
8164            Object obj = mSettings.getUserIdLPr(uid);
8165            if (obj != null) {
8166                if (obj instanceof SharedUserSetting) {
8167                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8168                } else if (obj instanceof PackageSetting) {
8169                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8170                } else {
8171                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8172                }
8173            } else {
8174                throw new SecurityException("Unknown calling uid " + uid);
8175            }
8176
8177            // Verify: can't set installerPackageName to a package that is
8178            // not signed with the same cert as the caller.
8179            if (installerPackageSetting != null) {
8180                if (compareSignatures(callerSignature,
8181                        installerPackageSetting.signatures.mSignatures)
8182                        != PackageManager.SIGNATURE_MATCH) {
8183                    throw new SecurityException(
8184                            "Caller does not have same cert as new installer package "
8185                            + installerPackageName);
8186                }
8187            }
8188
8189            // Verify: if target already has an installer package, it must
8190            // be signed with the same cert as the caller.
8191            if (targetPackageSetting.installerPackageName != null) {
8192                PackageSetting setting = mSettings.mPackages.get(
8193                        targetPackageSetting.installerPackageName);
8194                // If the currently set package isn't valid, then it's always
8195                // okay to change it.
8196                if (setting != null) {
8197                    if (compareSignatures(callerSignature,
8198                            setting.signatures.mSignatures)
8199                            != PackageManager.SIGNATURE_MATCH) {
8200                        throw new SecurityException(
8201                                "Caller does not have same cert as old installer package "
8202                                + targetPackageSetting.installerPackageName);
8203                    }
8204                }
8205            }
8206
8207            // Okay!
8208            targetPackageSetting.installerPackageName = installerPackageName;
8209            scheduleWriteSettingsLocked();
8210        }
8211    }
8212
8213    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8214        // Queue up an async operation since the package installation may take a little while.
8215        mHandler.post(new Runnable() {
8216            public void run() {
8217                mHandler.removeCallbacks(this);
8218                 // Result object to be returned
8219                PackageInstalledInfo res = new PackageInstalledInfo();
8220                res.returnCode = currentStatus;
8221                res.uid = -1;
8222                res.pkg = null;
8223                res.removedInfo = new PackageRemovedInfo();
8224                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8225                    args.doPreInstall(res.returnCode);
8226                    synchronized (mInstallLock) {
8227                        installPackageLI(args, true, res);
8228                    }
8229                    args.doPostInstall(res.returnCode, res.uid);
8230                }
8231
8232                // A restore should be performed at this point if (a) the install
8233                // succeeded, (b) the operation is not an update, and (c) the new
8234                // package has a backupAgent defined.
8235                final boolean update = res.removedInfo.removedPackage != null;
8236                boolean doRestore = (!update
8237                        && res.pkg != null
8238                        && res.pkg.applicationInfo.backupAgentName != null);
8239
8240                // Set up the post-install work request bookkeeping.  This will be used
8241                // and cleaned up by the post-install event handling regardless of whether
8242                // there's a restore pass performed.  Token values are >= 1.
8243                int token;
8244                if (mNextInstallToken < 0) mNextInstallToken = 1;
8245                token = mNextInstallToken++;
8246
8247                PostInstallData data = new PostInstallData(args, res);
8248                mRunningInstalls.put(token, data);
8249                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8250
8251                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8252                    // Pass responsibility to the Backup Manager.  It will perform a
8253                    // restore if appropriate, then pass responsibility back to the
8254                    // Package Manager to run the post-install observer callbacks
8255                    // and broadcasts.
8256                    IBackupManager bm = IBackupManager.Stub.asInterface(
8257                            ServiceManager.getService(Context.BACKUP_SERVICE));
8258                    if (bm != null) {
8259                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8260                                + " to BM for possible restore");
8261                        try {
8262                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8263                        } catch (RemoteException e) {
8264                            // can't happen; the backup manager is local
8265                        } catch (Exception e) {
8266                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8267                            doRestore = false;
8268                        }
8269                    } else {
8270                        Slog.e(TAG, "Backup Manager not found!");
8271                        doRestore = false;
8272                    }
8273                }
8274
8275                if (!doRestore) {
8276                    // No restore possible, or the Backup Manager was mysteriously not
8277                    // available -- just fire the post-install work request directly.
8278                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8279                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8280                    mHandler.sendMessage(msg);
8281                }
8282            }
8283        });
8284    }
8285
8286    private abstract class HandlerParams {
8287        private static final int MAX_RETRIES = 4;
8288
8289        /**
8290         * Number of times startCopy() has been attempted and had a non-fatal
8291         * error.
8292         */
8293        private int mRetries = 0;
8294
8295        /** User handle for the user requesting the information or installation. */
8296        private final UserHandle mUser;
8297
8298        HandlerParams(UserHandle user) {
8299            mUser = user;
8300        }
8301
8302        UserHandle getUser() {
8303            return mUser;
8304        }
8305
8306        final boolean startCopy() {
8307            boolean res;
8308            try {
8309                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8310
8311                if (++mRetries > MAX_RETRIES) {
8312                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8313                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8314                    handleServiceError();
8315                    return false;
8316                } else {
8317                    handleStartCopy();
8318                    res = true;
8319                }
8320            } catch (RemoteException e) {
8321                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8322                mHandler.sendEmptyMessage(MCS_RECONNECT);
8323                res = false;
8324            }
8325            handleReturnCode();
8326            return res;
8327        }
8328
8329        final void serviceError() {
8330            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8331            handleServiceError();
8332            handleReturnCode();
8333        }
8334
8335        abstract void handleStartCopy() throws RemoteException;
8336        abstract void handleServiceError();
8337        abstract void handleReturnCode();
8338    }
8339
8340    class MeasureParams extends HandlerParams {
8341        private final PackageStats mStats;
8342        private boolean mSuccess;
8343
8344        private final IPackageStatsObserver mObserver;
8345
8346        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8347            super(new UserHandle(stats.userHandle));
8348            mObserver = observer;
8349            mStats = stats;
8350        }
8351
8352        @Override
8353        public String toString() {
8354            return "MeasureParams{"
8355                + Integer.toHexString(System.identityHashCode(this))
8356                + " " + mStats.packageName + "}";
8357        }
8358
8359        @Override
8360        void handleStartCopy() throws RemoteException {
8361            synchronized (mInstallLock) {
8362                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8363            }
8364
8365            if (mSuccess) {
8366                final boolean mounted;
8367                if (Environment.isExternalStorageEmulated()) {
8368                    mounted = true;
8369                } else {
8370                    final String status = Environment.getExternalStorageState();
8371                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8372                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8373                }
8374
8375                if (mounted) {
8376                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8377
8378                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8379                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8380
8381                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8382                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8383
8384                    // Always subtract cache size, since it's a subdirectory
8385                    mStats.externalDataSize -= mStats.externalCacheSize;
8386
8387                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8388                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8389
8390                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8391                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8392                }
8393            }
8394        }
8395
8396        @Override
8397        void handleReturnCode() {
8398            if (mObserver != null) {
8399                try {
8400                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8401                } catch (RemoteException e) {
8402                    Slog.i(TAG, "Observer no longer exists.");
8403                }
8404            }
8405        }
8406
8407        @Override
8408        void handleServiceError() {
8409            Slog.e(TAG, "Could not measure application " + mStats.packageName
8410                            + " external storage");
8411        }
8412    }
8413
8414    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8415            throws RemoteException {
8416        long result = 0;
8417        for (File path : paths) {
8418            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8419        }
8420        return result;
8421    }
8422
8423    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8424        for (File path : paths) {
8425            try {
8426                mcs.clearDirectory(path.getAbsolutePath());
8427            } catch (RemoteException e) {
8428            }
8429        }
8430    }
8431
8432    class InstallParams extends HandlerParams {
8433        /**
8434         * Location where install is coming from, before it has been
8435         * copied/renamed into place. This could be a single monolithic APK
8436         * file, or a cluster directory. This location may be untrusted.
8437         */
8438        final File originFile;
8439
8440        /**
8441         * Flag indicating that {@link #originFile} has already been staged,
8442         * meaning downstream users don't need to defensively copy the contents.
8443         */
8444        boolean originStaged;
8445
8446        final IPackageInstallObserver2 observer;
8447        int flags;
8448        final String installerPackageName;
8449        final VerificationParams verificationParams;
8450        private InstallArgs mArgs;
8451        private int mRet;
8452        final String packageAbiOverride;
8453        boolean multiArch;
8454
8455        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8456                int flags, String installerPackageName, VerificationParams verificationParams,
8457                UserHandle user, String packageAbiOverride) {
8458            super(user);
8459            this.originFile = Preconditions.checkNotNull(originFile);
8460            this.originStaged = originStaged;
8461            this.observer = observer;
8462            this.flags = flags;
8463            this.installerPackageName = installerPackageName;
8464            this.verificationParams = verificationParams;
8465            this.packageAbiOverride = packageAbiOverride;
8466        }
8467
8468        @Override
8469        public String toString() {
8470            return "InstallParams{"
8471                + Integer.toHexString(System.identityHashCode(this))
8472                + " " + originFile + "}";
8473        }
8474
8475        public ManifestDigest getManifestDigest() {
8476            if (verificationParams == null) {
8477                return null;
8478            }
8479            return verificationParams.getManifestDigest();
8480        }
8481
8482        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8483            String packageName = pkgLite.packageName;
8484            int installLocation = pkgLite.installLocation;
8485            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8486            // reader
8487            synchronized (mPackages) {
8488                PackageParser.Package pkg = mPackages.get(packageName);
8489                if (pkg != null) {
8490                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8491                        // Check for downgrading.
8492                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8493                            if (pkgLite.versionCode < pkg.mVersionCode) {
8494                                Slog.w(TAG, "Can't install update of " + packageName
8495                                        + " update version " + pkgLite.versionCode
8496                                        + " is older than installed version "
8497                                        + pkg.mVersionCode);
8498                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8499                            }
8500                        }
8501                        // Check for updated system application.
8502                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8503                            if (onSd) {
8504                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8505                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8506                            }
8507                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8508                        } else {
8509                            if (onSd) {
8510                                // Install flag overrides everything.
8511                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8512                            }
8513                            // If current upgrade specifies particular preference
8514                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8515                                // Application explicitly specified internal.
8516                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8517                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8518                                // App explictly prefers external. Let policy decide
8519                            } else {
8520                                // Prefer previous location
8521                                if (isExternal(pkg)) {
8522                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8523                                }
8524                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8525                            }
8526                        }
8527                    } else {
8528                        // Invalid install. Return error code
8529                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8530                    }
8531                }
8532            }
8533            // All the special cases have been taken care of.
8534            // Return result based on recommended install location.
8535            if (onSd) {
8536                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8537            }
8538            return pkgLite.recommendedInstallLocation;
8539        }
8540
8541        private long getMemoryLowThreshold() {
8542            final DeviceStorageMonitorInternal
8543                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8544            if (dsm == null) {
8545                return 0L;
8546            }
8547            return dsm.getMemoryLowThreshold();
8548        }
8549
8550        /*
8551         * Invoke remote method to get package information and install
8552         * location values. Override install location based on default
8553         * policy if needed and then create install arguments based
8554         * on the install location.
8555         */
8556        public void handleStartCopy() throws RemoteException {
8557            int ret = PackageManager.INSTALL_SUCCEEDED;
8558            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8559            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8560            PackageInfoLite pkgLite = null;
8561
8562            if (onInt && onSd) {
8563                // Check if both bits are set.
8564                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8565                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8566            } else {
8567                final long lowThreshold = getMemoryLowThreshold();
8568                if (lowThreshold == 0L) {
8569                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8570                }
8571
8572                // Remote call to find out default install location
8573                final String originPath = originFile.getAbsolutePath();
8574                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8575                        packageAbiOverride);
8576                // Keep track of whether this package is a multiArch package until
8577                // we perform a full scan of it. We need to do this because we might
8578                // end up extracting the package shared libraries before we perform
8579                // a full scan.
8580                multiArch = pkgLite.multiArch;
8581
8582                /*
8583                 * If we have too little free space, try to free cache
8584                 * before giving up.
8585                 */
8586                if (pkgLite.recommendedInstallLocation
8587                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8588                    final long size = mContainerService.calculateInstalledSize(
8589                            originPath, isForwardLocked(), packageAbiOverride);
8590                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8591                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8592                                lowThreshold, packageAbiOverride);
8593                    }
8594                    /*
8595                     * The cache free must have deleted the file we
8596                     * downloaded to install.
8597                     *
8598                     * TODO: fix the "freeCache" call to not delete
8599                     *       the file we care about.
8600                     */
8601                    if (pkgLite.recommendedInstallLocation
8602                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8603                        pkgLite.recommendedInstallLocation
8604                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8605                    }
8606                }
8607            }
8608
8609            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8610                int loc = pkgLite.recommendedInstallLocation;
8611                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8612                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8613                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8614                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8615                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8616                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8617                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8618                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8619                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8620                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8621                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8622                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8623                } else {
8624                    // Override with defaults if needed.
8625                    loc = installLocationPolicy(pkgLite, flags);
8626                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8627                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8628                    } else if (!onSd && !onInt) {
8629                        // Override install location with flags
8630                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8631                            // Set the flag to install on external media.
8632                            flags |= PackageManager.INSTALL_EXTERNAL;
8633                            flags &= ~PackageManager.INSTALL_INTERNAL;
8634                        } else {
8635                            // Make sure the flag for installing on external
8636                            // media is unset
8637                            flags |= PackageManager.INSTALL_INTERNAL;
8638                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8639                        }
8640                    }
8641                }
8642            }
8643
8644            final InstallArgs args = createInstallArgs(this);
8645            mArgs = args;
8646
8647            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8648                 /*
8649                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8650                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8651                 */
8652                int userIdentifier = getUser().getIdentifier();
8653                if (userIdentifier == UserHandle.USER_ALL
8654                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8655                    userIdentifier = UserHandle.USER_OWNER;
8656                }
8657
8658                /*
8659                 * Determine if we have any installed package verifiers. If we
8660                 * do, then we'll defer to them to verify the packages.
8661                 */
8662                final int requiredUid = mRequiredVerifierPackage == null ? -1
8663                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8664                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8665                    // TODO: send verifier the install session instead of uri
8666                    final Intent verification = new Intent(
8667                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8668                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8669                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8670
8671                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8672                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8673                            0 /* TODO: Which userId? */);
8674
8675                    if (DEBUG_VERIFY) {
8676                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8677                                + verification.toString() + " with " + pkgLite.verifiers.length
8678                                + " optional verifiers");
8679                    }
8680
8681                    final int verificationId = mPendingVerificationToken++;
8682
8683                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8684
8685                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8686                            installerPackageName);
8687
8688                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8689
8690                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8691                            pkgLite.packageName);
8692
8693                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8694                            pkgLite.versionCode);
8695
8696                    if (verificationParams != null) {
8697                        if (verificationParams.getVerificationURI() != null) {
8698                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8699                                 verificationParams.getVerificationURI());
8700                        }
8701                        if (verificationParams.getOriginatingURI() != null) {
8702                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8703                                  verificationParams.getOriginatingURI());
8704                        }
8705                        if (verificationParams.getReferrer() != null) {
8706                            verification.putExtra(Intent.EXTRA_REFERRER,
8707                                  verificationParams.getReferrer());
8708                        }
8709                        if (verificationParams.getOriginatingUid() >= 0) {
8710                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8711                                  verificationParams.getOriginatingUid());
8712                        }
8713                        if (verificationParams.getInstallerUid() >= 0) {
8714                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8715                                  verificationParams.getInstallerUid());
8716                        }
8717                    }
8718
8719                    final PackageVerificationState verificationState = new PackageVerificationState(
8720                            requiredUid, args);
8721
8722                    mPendingVerification.append(verificationId, verificationState);
8723
8724                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8725                            receivers, verificationState);
8726
8727                    /*
8728                     * If any sufficient verifiers were listed in the package
8729                     * manifest, attempt to ask them.
8730                     */
8731                    if (sufficientVerifiers != null) {
8732                        final int N = sufficientVerifiers.size();
8733                        if (N == 0) {
8734                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8735                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8736                        } else {
8737                            for (int i = 0; i < N; i++) {
8738                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8739
8740                                final Intent sufficientIntent = new Intent(verification);
8741                                sufficientIntent.setComponent(verifierComponent);
8742
8743                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8744                            }
8745                        }
8746                    }
8747
8748                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8749                            mRequiredVerifierPackage, receivers);
8750                    if (ret == PackageManager.INSTALL_SUCCEEDED
8751                            && mRequiredVerifierPackage != null) {
8752                        /*
8753                         * Send the intent to the required verification agent,
8754                         * but only start the verification timeout after the
8755                         * target BroadcastReceivers have run.
8756                         */
8757                        verification.setComponent(requiredVerifierComponent);
8758                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8759                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8760                                new BroadcastReceiver() {
8761                                    @Override
8762                                    public void onReceive(Context context, Intent intent) {
8763                                        final Message msg = mHandler
8764                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8765                                        msg.arg1 = verificationId;
8766                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8767                                    }
8768                                }, null, 0, null, null);
8769
8770                        /*
8771                         * We don't want the copy to proceed until verification
8772                         * succeeds, so null out this field.
8773                         */
8774                        mArgs = null;
8775                    }
8776                } else {
8777                    /*
8778                     * No package verification is enabled, so immediately start
8779                     * the remote call to initiate copy using temporary file.
8780                     */
8781                    ret = args.copyApk(mContainerService, true);
8782                }
8783            }
8784
8785            mRet = ret;
8786        }
8787
8788        @Override
8789        void handleReturnCode() {
8790            // If mArgs is null, then MCS couldn't be reached. When it
8791            // reconnects, it will try again to install. At that point, this
8792            // will succeed.
8793            if (mArgs != null) {
8794                processPendingInstall(mArgs, mRet);
8795            }
8796        }
8797
8798        @Override
8799        void handleServiceError() {
8800            mArgs = createInstallArgs(this);
8801            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8802        }
8803
8804        public boolean isForwardLocked() {
8805            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8806        }
8807    }
8808
8809    /*
8810     * Utility class used in movePackage api.
8811     * srcArgs and targetArgs are not set for invalid flags and make
8812     * sure to do null checks when invoking methods on them.
8813     * We probably want to return ErrorPrams for both failed installs
8814     * and moves.
8815     */
8816    class MoveParams extends HandlerParams {
8817        final IPackageMoveObserver observer;
8818        final int flags;
8819        final String packageName;
8820        final InstallArgs srcArgs;
8821        final InstallArgs targetArgs;
8822        int uid;
8823        int mRet;
8824
8825        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8826                String packageName, String[] instructionSets, int uid, UserHandle user,
8827                boolean isMultiArch) {
8828            super(user);
8829            this.srcArgs = srcArgs;
8830            this.observer = observer;
8831            this.flags = flags;
8832            this.packageName = packageName;
8833            this.uid = uid;
8834            if (srcArgs != null) {
8835                final String codePath = srcArgs.getCodePath();
8836                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8837                        instructionSets, isMultiArch);
8838            } else {
8839                targetArgs = null;
8840            }
8841        }
8842
8843        @Override
8844        public String toString() {
8845            return "MoveParams{"
8846                + Integer.toHexString(System.identityHashCode(this))
8847                + " " + packageName + "}";
8848        }
8849
8850        public void handleStartCopy() throws RemoteException {
8851            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8852            // Check for storage space on target medium
8853            if (!targetArgs.checkFreeStorage(mContainerService)) {
8854                Log.w(TAG, "Insufficient storage to install");
8855                return;
8856            }
8857
8858            mRet = srcArgs.doPreCopy();
8859            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8860                return;
8861            }
8862
8863            mRet = targetArgs.copyApk(mContainerService, false);
8864            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8865                srcArgs.doPostCopy(uid);
8866                return;
8867            }
8868
8869            mRet = srcArgs.doPostCopy(uid);
8870            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8871                return;
8872            }
8873
8874            mRet = targetArgs.doPreInstall(mRet);
8875            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8876                return;
8877            }
8878
8879            if (DEBUG_SD_INSTALL) {
8880                StringBuilder builder = new StringBuilder();
8881                if (srcArgs != null) {
8882                    builder.append("src: ");
8883                    builder.append(srcArgs.getCodePath());
8884                }
8885                if (targetArgs != null) {
8886                    builder.append(" target : ");
8887                    builder.append(targetArgs.getCodePath());
8888                }
8889                Log.i(TAG, builder.toString());
8890            }
8891        }
8892
8893        @Override
8894        void handleReturnCode() {
8895            targetArgs.doPostInstall(mRet, uid);
8896            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8897            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8898                currentStatus = PackageManager.MOVE_SUCCEEDED;
8899            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8900                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8901            }
8902            processPendingMove(this, currentStatus);
8903        }
8904
8905        @Override
8906        void handleServiceError() {
8907            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8908        }
8909    }
8910
8911    /**
8912     * Used during creation of InstallArgs
8913     *
8914     * @param flags package installation flags
8915     * @return true if should be installed on external storage
8916     */
8917    private static boolean installOnSd(int flags) {
8918        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8919            return false;
8920        }
8921        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8922            return true;
8923        }
8924        return false;
8925    }
8926
8927    /**
8928     * Used during creation of InstallArgs
8929     *
8930     * @param flags package installation flags
8931     * @return true if should be installed as forward locked
8932     */
8933    private static boolean installForwardLocked(int flags) {
8934        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8935    }
8936
8937    private InstallArgs createInstallArgs(InstallParams params) {
8938        // TODO: extend to support incoming zero-copy locations
8939
8940        if (installOnSd(params.flags) || params.isForwardLocked()) {
8941            return new AsecInstallArgs(params);
8942        } else {
8943            return new FileInstallArgs(params);
8944        }
8945    }
8946
8947    /**
8948     * Create args that describe an existing installed package. Typically used
8949     * when cleaning up old installs, or used as a move source.
8950     */
8951    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
8952            String resourcePath, String nativeLibraryRoot, String[] instructionSets,
8953            boolean isMultiArch) {
8954        final boolean isInAsec;
8955        if (installOnSd(flags)) {
8956            /* Apps on SD card are always in ASEC containers. */
8957            isInAsec = true;
8958        } else if (installForwardLocked(flags)
8959                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8960            /*
8961             * Forward-locked apps are only in ASEC containers if they're the
8962             * new style
8963             */
8964            isInAsec = true;
8965        } else {
8966            isInAsec = false;
8967        }
8968
8969        if (isInAsec) {
8970            return new AsecInstallArgs(codePath, instructionSets,
8971                    installOnSd(flags), installForwardLocked(flags), isMultiArch);
8972        } else {
8973            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8974                    instructionSets, isMultiArch);
8975        }
8976    }
8977
8978    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
8979            String[] instructionSets, boolean isMultiArch) {
8980        final File codeFile = new File(codePath);
8981        if (installOnSd(flags) || installForwardLocked(flags)) {
8982            String cid = getNextCodePath(codePath, pkgName, "/"
8983                    + AsecInstallArgs.RES_FILE_NAME);
8984            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
8985                    installForwardLocked(flags), isMultiArch);
8986        } else {
8987            return new FileInstallArgs(codeFile, instructionSets, isMultiArch);
8988        }
8989    }
8990
8991    static abstract class InstallArgs {
8992        /** @see InstallParams#originFile */
8993        final File originFile;
8994        /** @see InstallParams#originStaged */
8995        final boolean originStaged;
8996
8997        // TODO: define inherit location
8998
8999        final IPackageInstallObserver2 observer;
9000        // Always refers to PackageManager flags only
9001        final int flags;
9002        final String installerPackageName;
9003        final ManifestDigest manifestDigest;
9004        final UserHandle user;
9005        final String abiOverride;
9006        final boolean multiArch;
9007
9008        // The list of instruction sets supported by this app. This is currently
9009        // only used during the rmdex() phase to clean up resources. We can get rid of this
9010        // if we move dex files under the common app path.
9011        /* nullable */ String[] instructionSets;
9012
9013        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
9014                    int flags, String installerPackageName, ManifestDigest manifestDigest,
9015                    UserHandle user, String[] instructionSets,
9016                    String abiOverride, boolean multiArch) {
9017            this.originFile = originFile;
9018            this.originStaged = originStaged;
9019            this.flags = flags;
9020            this.observer = observer;
9021            this.installerPackageName = installerPackageName;
9022            this.manifestDigest = manifestDigest;
9023            this.user = user;
9024            this.instructionSets = instructionSets;
9025            this.abiOverride = abiOverride;
9026            this.multiArch = multiArch;
9027        }
9028
9029        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9030        abstract int doPreInstall(int status);
9031
9032        /**
9033         * Rename package into final resting place. All paths on the given
9034         * scanned package should be updated to reflect the rename.
9035         */
9036        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9037        abstract int doPostInstall(int status, int uid);
9038
9039        /** @see PackageSettingBase#codePathString */
9040        abstract String getCodePath();
9041        /** @see PackageSettingBase#resourcePathString */
9042        abstract String getResourcePath();
9043        abstract String getLegacyNativeLibraryPath();
9044
9045        // Need installer lock especially for dex file removal.
9046        abstract void cleanUpResourcesLI();
9047        abstract boolean doPostDeleteLI(boolean delete);
9048        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9049
9050        /**
9051         * Called before the source arguments are copied. This is used mostly
9052         * for MoveParams when it needs to read the source file to put it in the
9053         * destination.
9054         */
9055        int doPreCopy() {
9056            return PackageManager.INSTALL_SUCCEEDED;
9057        }
9058
9059        /**
9060         * Called after the source arguments are copied. This is used mostly for
9061         * MoveParams when it needs to read the source file to put it in the
9062         * destination.
9063         *
9064         * @return
9065         */
9066        int doPostCopy(int uid) {
9067            return PackageManager.INSTALL_SUCCEEDED;
9068        }
9069
9070        protected boolean isFwdLocked() {
9071            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9072        }
9073
9074        UserHandle getUser() {
9075            return user;
9076        }
9077    }
9078
9079    /**
9080     * Logic to handle installation of non-ASEC applications, including copying
9081     * and renaming logic.
9082     */
9083    class FileInstallArgs extends InstallArgs {
9084        private File codeFile;
9085        private File resourceFile;
9086        private File legacyNativeLibraryPath;
9087
9088        // Example topology:
9089        // /data/app/com.example/base.apk
9090        // /data/app/com.example/split_foo.apk
9091        // /data/app/com.example/lib/arm/libfoo.so
9092        // /data/app/com.example/lib/arm64/libfoo.so
9093        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9094
9095        /** New install */
9096        FileInstallArgs(InstallParams params) {
9097            super(params.originFile, params.originStaged, params.observer, params.flags,
9098                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9099                    null /* instruction sets */, params.packageAbiOverride,
9100                    params.multiArch);
9101            if (isFwdLocked()) {
9102                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9103            }
9104        }
9105
9106        /** Existing install */
9107        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9108                String[] instructionSets, boolean isMultiArch) {
9109            super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch);
9110            this.codeFile = (codePath != null) ? new File(codePath) : null;
9111            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9112            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9113                    new File(legacyNativeLibraryPath) : null;
9114        }
9115
9116        /** New install from existing */
9117        FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) {
9118            super(originFile, false, null, 0, null, null, null, instructionSets, null,
9119                    isMultiArch);
9120        }
9121
9122        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9123            final long lowThreshold;
9124
9125            final DeviceStorageMonitorInternal
9126                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9127            if (dsm == null) {
9128                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9129                lowThreshold = 0L;
9130            } else {
9131                if (dsm.isMemoryLow()) {
9132                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9133                    return false;
9134                }
9135
9136                lowThreshold = dsm.getMemoryLowThreshold();
9137            }
9138
9139            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9140                    lowThreshold);
9141        }
9142
9143        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9144            int ret = PackageManager.INSTALL_SUCCEEDED;
9145
9146            if (originStaged) {
9147                Slog.d(TAG, originFile + " already staged; skipping copy");
9148                codeFile = originFile;
9149                resourceFile = originFile;
9150            } else {
9151                try {
9152                    final File tempDir = mInstallerService.allocateSessionDir();
9153                    codeFile = tempDir;
9154                    resourceFile = tempDir;
9155                } catch (IOException e) {
9156                    Slog.w(TAG, "Failed to create copy file: " + e);
9157                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9158                }
9159
9160                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9161                    @Override
9162                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9163                        if (!FileUtils.isValidExtFilename(name)) {
9164                            throw new IllegalArgumentException("Invalid filename: " + name);
9165                        }
9166                        try {
9167                            final File file = new File(codeFile, name);
9168                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9169                                    O_RDWR | O_CREAT, 0644);
9170                            Os.chmod(file.getAbsolutePath(), 0644);
9171                            return new ParcelFileDescriptor(fd);
9172                        } catch (ErrnoException e) {
9173                            throw new RemoteException("Failed to open: " + e.getMessage());
9174                        }
9175                    }
9176                };
9177
9178                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9179                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9180                    Slog.e(TAG, "Failed to copy package");
9181                    return ret;
9182                }
9183            }
9184
9185            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9186            NativeLibraryHelper.Handle handle = null;
9187            try {
9188                handle = NativeLibraryHelper.Handle.create(codeFile);
9189                if (multiArch) {
9190                    // Warn if we've set an abiOverride for multi-lib packages..
9191                    // By definition, we need to copy both 32 and 64 bit libraries for
9192                    // such packages.
9193                    if (abiOverride != null) {
9194                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9195                    }
9196
9197                    int copyRet = PackageManager.NO_NATIVE_LIBRARIES;
9198                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9199                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9200                                Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */);
9201                        maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet);
9202                    }
9203
9204                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9205                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9206                                Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */);
9207                        maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet);
9208                    }
9209                } else {
9210                    String[] abiList = (abiOverride != null) ?
9211                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9212
9213                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
9214                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9215                        abiList = Build.SUPPORTED_32_BIT_ABIS;
9216                    }
9217
9218                    int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList,
9219                            true /* use isa specific subdirs */);
9220                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9221                        Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]");
9222                        return copyRet;
9223                    }
9224                }
9225            } catch (IOException e) {
9226                Slog.e(TAG, "Copying native libraries failed", e);
9227                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9228            } catch (PackageManagerException pme) {
9229                Slog.e(TAG, "Copying native libraries failed", pme);
9230                ret = pme.error;
9231            } finally {
9232                IoUtils.closeQuietly(handle);
9233            }
9234
9235            return ret;
9236        }
9237
9238        int doPreInstall(int status) {
9239            if (status != PackageManager.INSTALL_SUCCEEDED) {
9240                cleanUp();
9241            }
9242            return status;
9243        }
9244
9245        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9246            if (status != PackageManager.INSTALL_SUCCEEDED) {
9247                cleanUp();
9248                return false;
9249            } else {
9250                final File beforeCodeFile = codeFile;
9251                final File afterCodeFile = getNextCodePath(pkg.packageName);
9252
9253                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9254                try {
9255                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9256                } catch (ErrnoException e) {
9257                    Slog.d(TAG, "Failed to rename", e);
9258                    return false;
9259                }
9260
9261                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9262                    Slog.d(TAG, "Failed to restorecon");
9263                    return false;
9264                }
9265
9266                // Reflect the rename internally
9267                codeFile = afterCodeFile;
9268                resourceFile = afterCodeFile;
9269
9270                // Reflect the rename in scanned details
9271                pkg.codePath = afterCodeFile.getAbsolutePath();
9272                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9273                        pkg.baseCodePath);
9274                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9275                        pkg.splitCodePaths);
9276
9277                // Reflect the rename in app info
9278                pkg.applicationInfo.setCodePath(pkg.codePath);
9279                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9280                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9281                pkg.applicationInfo.setResourcePath(pkg.codePath);
9282                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9283                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9284
9285                return true;
9286            }
9287        }
9288
9289        int doPostInstall(int status, int uid) {
9290            if (status != PackageManager.INSTALL_SUCCEEDED) {
9291                cleanUp();
9292            }
9293            return status;
9294        }
9295
9296        @Override
9297        String getCodePath() {
9298            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9299        }
9300
9301        @Override
9302        String getResourcePath() {
9303            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9304        }
9305
9306        @Override
9307        String getLegacyNativeLibraryPath() {
9308            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9309        }
9310
9311        private boolean cleanUp() {
9312            if (codeFile == null || !codeFile.exists()) {
9313                return false;
9314            }
9315
9316            if (codeFile.isDirectory()) {
9317                FileUtils.deleteContents(codeFile);
9318            }
9319            codeFile.delete();
9320
9321            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9322                resourceFile.delete();
9323            }
9324
9325            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9326                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9327                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9328                }
9329                legacyNativeLibraryPath.delete();
9330            }
9331
9332            return true;
9333        }
9334
9335        void cleanUpResourcesLI() {
9336            // Try enumerating all code paths before deleting
9337            List<String> allCodePaths = Collections.EMPTY_LIST;
9338            if (codeFile != null && codeFile.exists()) {
9339                try {
9340                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9341                    allCodePaths = pkg.getAllCodePaths();
9342                } catch (PackageParserException e) {
9343                    // Ignored; we tried our best
9344                }
9345            }
9346
9347            cleanUp();
9348
9349            if (!allCodePaths.isEmpty()) {
9350                if (instructionSets == null) {
9351                    throw new IllegalStateException("instructionSet == null");
9352                }
9353
9354                for (String codePath : allCodePaths) {
9355                    for (String instructionSet : instructionSets) {
9356                        int retCode = mInstaller.rmdex(codePath, instructionSet);
9357                        if (retCode < 0) {
9358                            Slog.w(TAG, "Couldn't remove dex file for package: "
9359                                    + " at location " + codePath + ", retcode=" + retCode);
9360                            // we don't consider this to be a failure of the core package deletion
9361                        }
9362                    }
9363                }
9364            }
9365        }
9366
9367        boolean doPostDeleteLI(boolean delete) {
9368            // XXX err, shouldn't we respect the delete flag?
9369            cleanUpResourcesLI();
9370            return true;
9371        }
9372    }
9373
9374    private boolean isAsecExternal(String cid) {
9375        final String asecPath = PackageHelper.getSdFilesystem(cid);
9376        return !asecPath.startsWith(mAsecInternalPath);
9377    }
9378
9379    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9380            PackageManagerException {
9381        if (copyRet < 0) {
9382            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9383                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9384                throw new PackageManagerException(copyRet, message);
9385            }
9386        }
9387    }
9388
9389    /**
9390     * Extract the MountService "container ID" from the full code path of an
9391     * .apk.
9392     */
9393    static String cidFromCodePath(String fullCodePath) {
9394        int eidx = fullCodePath.lastIndexOf("/");
9395        String subStr1 = fullCodePath.substring(0, eidx);
9396        int sidx = subStr1.lastIndexOf("/");
9397        return subStr1.substring(sidx+1, eidx);
9398    }
9399
9400    /**
9401     * Logic to handle installation of ASEC applications, including copying and
9402     * renaming logic.
9403     */
9404    class AsecInstallArgs extends InstallArgs {
9405        // TODO: teach about handling cluster directories
9406
9407        static final String RES_FILE_NAME = "pkg.apk";
9408        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9409
9410        String cid;
9411        String packagePath;
9412        String resourcePath;
9413        String legacyNativeLibraryDir;
9414
9415        /** New install */
9416        AsecInstallArgs(InstallParams params) {
9417            super(params.originFile, params.originStaged, params.observer, params.flags,
9418                    params.installerPackageName, params.getManifestDigest(),
9419                    params.getUser(), null /* instruction sets */,
9420                    params.packageAbiOverride, params.multiArch);
9421        }
9422
9423        /** Existing install */
9424        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9425                        boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9426            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9427                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9428                    instructionSets, null, isMultiArch);
9429            // Extract cid from fullCodePath
9430            int eidx = fullCodePath.lastIndexOf("/");
9431            String subStr1 = fullCodePath.substring(0, eidx);
9432            int sidx = subStr1.lastIndexOf("/");
9433            cid = subStr1.substring(sidx+1, eidx);
9434            setCachePath(subStr1);
9435        }
9436
9437        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked,
9438                        boolean isMultiArch) {
9439            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9440                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9441                    instructionSets, null, isMultiArch);
9442            this.cid = cid;
9443            setCachePath(PackageHelper.getSdDir(cid));
9444        }
9445
9446        /** New install from existing */
9447        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9448                boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9449            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9450                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9451                    instructionSets, null, isMultiArch);
9452            this.cid = cid;
9453        }
9454
9455        void createCopyFile() {
9456            cid = getTempContainerId();
9457        }
9458
9459        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9460            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9461                    abiOverride);
9462        }
9463
9464        private final boolean isExternal() {
9465            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9466        }
9467
9468        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9469            if (temp) {
9470                createCopyFile();
9471            } else {
9472                /*
9473                 * Pre-emptively destroy the container since it's destroyed if
9474                 * copying fails due to it existing anyway.
9475                 */
9476                PackageHelper.destroySdDir(cid);
9477            }
9478
9479            final String newCachePath = imcs.copyPackageToContainer(
9480                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9481                    isFwdLocked(), abiOverride);
9482
9483            if (newCachePath != null) {
9484                setCachePath(newCachePath);
9485                return PackageManager.INSTALL_SUCCEEDED;
9486            } else {
9487                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9488            }
9489        }
9490
9491        @Override
9492        String getCodePath() {
9493            return packagePath;
9494        }
9495
9496        @Override
9497        String getResourcePath() {
9498            return resourcePath;
9499        }
9500
9501        @Override
9502        String getLegacyNativeLibraryPath() {
9503            return legacyNativeLibraryDir;
9504        }
9505
9506        int doPreInstall(int status) {
9507            if (status != PackageManager.INSTALL_SUCCEEDED) {
9508                // Destroy container
9509                PackageHelper.destroySdDir(cid);
9510            } else {
9511                boolean mounted = PackageHelper.isContainerMounted(cid);
9512                if (!mounted) {
9513                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9514                            Process.SYSTEM_UID);
9515                    if (newCachePath != null) {
9516                        setCachePath(newCachePath);
9517                    } else {
9518                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9519                    }
9520                }
9521            }
9522            return status;
9523        }
9524
9525        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9526            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9527            String newCachePath = null;
9528            if (PackageHelper.isContainerMounted(cid)) {
9529                // Unmount the container
9530                if (!PackageHelper.unMountSdDir(cid)) {
9531                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9532                    return false;
9533                }
9534            }
9535            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9536                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9537                        " which might be stale. Will try to clean up.");
9538                // Clean up the stale container and proceed to recreate.
9539                if (!PackageHelper.destroySdDir(newCacheId)) {
9540                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9541                    return false;
9542                }
9543                // Successfully cleaned up stale container. Try to rename again.
9544                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9545                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9546                            + " inspite of cleaning it up.");
9547                    return false;
9548                }
9549            }
9550            if (!PackageHelper.isContainerMounted(newCacheId)) {
9551                Slog.w(TAG, "Mounting container " + newCacheId);
9552                newCachePath = PackageHelper.mountSdDir(newCacheId,
9553                        getEncryptKey(), Process.SYSTEM_UID);
9554            } else {
9555                newCachePath = PackageHelper.getSdDir(newCacheId);
9556            }
9557            if (newCachePath == null) {
9558                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9559                return false;
9560            }
9561            Log.i(TAG, "Succesfully renamed " + cid +
9562                    " to " + newCacheId +
9563                    " at new path: " + newCachePath);
9564            cid = newCacheId;
9565            setCachePath(newCachePath);
9566
9567            // TODO: extend to support split APKs
9568            pkg.codePath = getCodePath();
9569            pkg.baseCodePath = getCodePath();
9570            pkg.splitCodePaths = null;
9571
9572            pkg.applicationInfo.setCodePath(getCodePath());
9573            pkg.applicationInfo.setBaseCodePath(getCodePath());
9574            pkg.applicationInfo.setSplitCodePaths(null);
9575            pkg.applicationInfo.setResourcePath(getResourcePath());
9576            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9577            pkg.applicationInfo.setSplitResourcePaths(null);
9578
9579            return true;
9580        }
9581
9582        private void setCachePath(String newCachePath) {
9583            File cachePath = new File(newCachePath);
9584            legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath();
9585            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9586
9587            if (isFwdLocked()) {
9588                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9589            } else {
9590                resourcePath = packagePath;
9591            }
9592        }
9593
9594        int doPostInstall(int status, int uid) {
9595            if (status != PackageManager.INSTALL_SUCCEEDED) {
9596                cleanUp();
9597            } else {
9598                final int groupOwner;
9599                final String protectedFile;
9600                if (isFwdLocked()) {
9601                    groupOwner = UserHandle.getSharedAppGid(uid);
9602                    protectedFile = RES_FILE_NAME;
9603                } else {
9604                    groupOwner = -1;
9605                    protectedFile = null;
9606                }
9607
9608                if (uid < Process.FIRST_APPLICATION_UID
9609                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9610                    Slog.e(TAG, "Failed to finalize " + cid);
9611                    PackageHelper.destroySdDir(cid);
9612                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9613                }
9614
9615                boolean mounted = PackageHelper.isContainerMounted(cid);
9616                if (!mounted) {
9617                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9618                }
9619            }
9620            return status;
9621        }
9622
9623        private void cleanUp() {
9624            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9625
9626            // Destroy secure container
9627            PackageHelper.destroySdDir(cid);
9628        }
9629
9630        void cleanUpResourcesLI() {
9631            String sourceFile = getCodePath();
9632            // Remove dex file
9633            if (instructionSets == null) {
9634                throw new IllegalStateException("instructionSet == null");
9635            }
9636            for (String instructionSet : instructionSets) {
9637                int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9638                if (retCode < 0) {
9639                    Slog.w(TAG, "Couldn't remove dex file for package: "
9640                            + " at location "
9641                            + sourceFile.toString() + ", retcode=" + retCode);
9642                    // we don't consider this to be a failure of the core package deletion
9643                }
9644            }
9645            cleanUp();
9646        }
9647
9648        boolean matchContainer(String app) {
9649            if (cid.startsWith(app)) {
9650                return true;
9651            }
9652            return false;
9653        }
9654
9655        String getPackageName() {
9656            return getAsecPackageName(cid);
9657        }
9658
9659        boolean doPostDeleteLI(boolean delete) {
9660            boolean ret = false;
9661            boolean mounted = PackageHelper.isContainerMounted(cid);
9662            if (mounted) {
9663                // Unmount first
9664                ret = PackageHelper.unMountSdDir(cid);
9665            }
9666            if (ret && delete) {
9667                cleanUpResourcesLI();
9668            }
9669            return ret;
9670        }
9671
9672        @Override
9673        int doPreCopy() {
9674            if (isFwdLocked()) {
9675                if (!PackageHelper.fixSdPermissions(cid,
9676                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9677                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9678                }
9679            }
9680
9681            return PackageManager.INSTALL_SUCCEEDED;
9682        }
9683
9684        @Override
9685        int doPostCopy(int uid) {
9686            if (isFwdLocked()) {
9687                if (uid < Process.FIRST_APPLICATION_UID
9688                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9689                                RES_FILE_NAME)) {
9690                    Slog.e(TAG, "Failed to finalize " + cid);
9691                    PackageHelper.destroySdDir(cid);
9692                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9693                }
9694            }
9695
9696            return PackageManager.INSTALL_SUCCEEDED;
9697        }
9698    }
9699
9700    static String getAsecPackageName(String packageCid) {
9701        int idx = packageCid.lastIndexOf("-");
9702        if (idx == -1) {
9703            return packageCid;
9704        }
9705        return packageCid.substring(0, idx);
9706    }
9707
9708    // Utility method used to create code paths based on package name and available index.
9709    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9710        String idxStr = "";
9711        int idx = 1;
9712        // Fall back to default value of idx=1 if prefix is not
9713        // part of oldCodePath
9714        if (oldCodePath != null) {
9715            String subStr = oldCodePath;
9716            // Drop the suffix right away
9717            if (suffix != null && subStr.endsWith(suffix)) {
9718                subStr = subStr.substring(0, subStr.length() - suffix.length());
9719            }
9720            // If oldCodePath already contains prefix find out the
9721            // ending index to either increment or decrement.
9722            int sidx = subStr.lastIndexOf(prefix);
9723            if (sidx != -1) {
9724                subStr = subStr.substring(sidx + prefix.length());
9725                if (subStr != null) {
9726                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9727                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9728                    }
9729                    try {
9730                        idx = Integer.parseInt(subStr);
9731                        if (idx <= 1) {
9732                            idx++;
9733                        } else {
9734                            idx--;
9735                        }
9736                    } catch(NumberFormatException e) {
9737                    }
9738                }
9739            }
9740        }
9741        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9742        return prefix + idxStr;
9743    }
9744
9745    private File getNextCodePath(String packageName) {
9746        int suffix = 1;
9747        File result;
9748        do {
9749            result = new File(mAppInstallDir, packageName + "-" + suffix);
9750            suffix++;
9751        } while (result.exists());
9752        return result;
9753    }
9754
9755    // Utility method used to ignore ADD/REMOVE events
9756    // by directory observer.
9757    private static boolean ignoreCodePath(String fullPathStr) {
9758        String apkName = deriveCodePathName(fullPathStr);
9759        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9760        if (idx != -1 && ((idx+1) < apkName.length())) {
9761            // Make sure the package ends with a numeral
9762            String version = apkName.substring(idx+1);
9763            try {
9764                Integer.parseInt(version);
9765                return true;
9766            } catch (NumberFormatException e) {}
9767        }
9768        return false;
9769    }
9770
9771    // Utility method that returns the relative package path with respect
9772    // to the installation directory. Like say for /data/data/com.test-1.apk
9773    // string com.test-1 is returned.
9774    static String deriveCodePathName(String codePath) {
9775        if (codePath == null) {
9776            return null;
9777        }
9778        final File codeFile = new File(codePath);
9779        final String name = codeFile.getName();
9780        if (codeFile.isDirectory()) {
9781            return name;
9782        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9783            final int lastDot = name.lastIndexOf('.');
9784            return name.substring(0, lastDot);
9785        } else {
9786            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9787            return null;
9788        }
9789    }
9790
9791    class PackageInstalledInfo {
9792        String name;
9793        int uid;
9794        // The set of users that originally had this package installed.
9795        int[] origUsers;
9796        // The set of users that now have this package installed.
9797        int[] newUsers;
9798        PackageParser.Package pkg;
9799        int returnCode;
9800        String returnMsg;
9801        PackageRemovedInfo removedInfo;
9802
9803        public void setError(int code, String msg) {
9804            returnCode = code;
9805            returnMsg = msg;
9806            Slog.w(TAG, msg);
9807        }
9808
9809        public void setError(String msg, PackageParserException e) {
9810            returnCode = e.error;
9811            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9812            Slog.w(TAG, msg, e);
9813        }
9814
9815        public void setError(String msg, PackageManagerException e) {
9816            returnCode = e.error;
9817            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9818            Slog.w(TAG, msg, e);
9819        }
9820
9821        // In some error cases we want to convey more info back to the observer
9822        String origPackage;
9823        String origPermission;
9824    }
9825
9826    /*
9827     * Install a non-existing package.
9828     */
9829    private void installNewPackageLI(PackageParser.Package pkg,
9830            int parseFlags, int scanMode, UserHandle user,
9831            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9832        // Remember this for later, in case we need to rollback this install
9833        String pkgName = pkg.packageName;
9834
9835        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9836        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9837        synchronized(mPackages) {
9838            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9839                // A package with the same name is already installed, though
9840                // it has been renamed to an older name.  The package we
9841                // are trying to install should be installed as an update to
9842                // the existing one, but that has not been requested, so bail.
9843                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9844                        + " without first uninstalling package running as "
9845                        + mSettings.mRenamedPackages.get(pkgName));
9846                return;
9847            }
9848            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9849                // Don't allow installation over an existing package with the same name.
9850                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9851                        + " without first uninstalling.");
9852                return;
9853            }
9854        }
9855
9856        try {
9857            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9858                    System.currentTimeMillis(), user, abiOverride);
9859
9860            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9861            // delete the partially installed application. the data directory will have to be
9862            // restored if it was already existing
9863            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9864                // remove package from internal structures.  Note that we want deletePackageX to
9865                // delete the package data and cache directories that it created in
9866                // scanPackageLocked, unless those directories existed before we even tried to
9867                // install.
9868                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9869                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9870                                res.removedInfo, true);
9871            }
9872
9873        } catch (PackageManagerException e) {
9874            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9875        }
9876    }
9877
9878    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9879        // Upgrade keysets are being used.  Determine if new package has a superset of the
9880        // required keys.
9881        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9882        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9883        for (int i = 0; i < upgradeKeySets.length; i++) {
9884            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9885            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9886                return true;
9887            }
9888        }
9889        return false;
9890    }
9891
9892    private void replacePackageLI(PackageParser.Package pkg,
9893            int parseFlags, int scanMode, UserHandle user,
9894            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9895        PackageParser.Package oldPackage;
9896        String pkgName = pkg.packageName;
9897        int[] allUsers;
9898        boolean[] perUserInstalled;
9899
9900        // First find the old package info and check signatures
9901        synchronized(mPackages) {
9902            oldPackage = mPackages.get(pkgName);
9903            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9904            PackageSetting ps = mSettings.mPackages.get(pkgName);
9905            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9906                // default to original signature matching
9907                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9908                    != PackageManager.SIGNATURE_MATCH) {
9909                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9910                            "New package has a different signature: " + pkgName);
9911                    return;
9912                }
9913            } else {
9914                if(!checkUpgradeKeySetLP(ps, pkg)) {
9915                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9916                            "New package not signed by keys specified by upgrade-keysets: "
9917                            + pkgName);
9918                    return;
9919                }
9920            }
9921
9922            // In case of rollback, remember per-user/profile install state
9923            allUsers = sUserManager.getUserIds();
9924            perUserInstalled = new boolean[allUsers.length];
9925            for (int i = 0; i < allUsers.length; i++) {
9926                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9927            }
9928        }
9929
9930        boolean sysPkg = (isSystemApp(oldPackage));
9931        if (sysPkg) {
9932            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9933                    user, allUsers, perUserInstalled, installerPackageName, res,
9934                    abiOverride);
9935        } else {
9936            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9937                    user, allUsers, perUserInstalled, installerPackageName, res,
9938                    abiOverride);
9939        }
9940    }
9941
9942    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9943            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9944            int[] allUsers, boolean[] perUserInstalled,
9945            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9946        String pkgName = deletedPackage.packageName;
9947        boolean deletedPkg = true;
9948        boolean updatedSettings = false;
9949
9950        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9951                + deletedPackage);
9952        long origUpdateTime;
9953        if (pkg.mExtras != null) {
9954            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9955        } else {
9956            origUpdateTime = 0;
9957        }
9958
9959        // First delete the existing package while retaining the data directory
9960        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9961                res.removedInfo, true)) {
9962            // If the existing package wasn't successfully deleted
9963            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9964            deletedPkg = false;
9965        } else {
9966            // Successfully deleted the old package. Now proceed with re-installation
9967            deleteCodeCacheDirsLI(pkgName);
9968            try {
9969                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9970                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride);
9971                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9972                updatedSettings = true;
9973            } catch (PackageManagerException e) {
9974                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9975            }
9976        }
9977
9978        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9979            // remove package from internal structures.  Note that we want deletePackageX to
9980            // delete the package data and cache directories that it created in
9981            // scanPackageLocked, unless those directories existed before we even tried to
9982            // install.
9983            if(updatedSettings) {
9984                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9985                deletePackageLI(
9986                        pkgName, null, true, allUsers, perUserInstalled,
9987                        PackageManager.DELETE_KEEP_DATA,
9988                                res.removedInfo, true);
9989            }
9990            // Since we failed to install the new package we need to restore the old
9991            // package that we deleted.
9992            if (deletedPkg) {
9993                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9994                File restoreFile = new File(deletedPackage.codePath);
9995                // Parse old package
9996                boolean oldOnSd = isExternal(deletedPackage);
9997                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9998                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9999                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10000                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10001                        | SCAN_UPDATE_TIME;
10002                try {
10003                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null,
10004                            null);
10005                } catch (PackageManagerException e) {
10006                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10007                            + e.getMessage());
10008                    return;
10009                }
10010                // Restore of old package succeeded. Update permissions.
10011                // writer
10012                synchronized (mPackages) {
10013                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10014                            UPDATE_PERMISSIONS_ALL);
10015                    // can downgrade to reader
10016                    mSettings.writeLPr();
10017                }
10018                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10019            }
10020        }
10021    }
10022
10023    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10024            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10025            int[] allUsers, boolean[] perUserInstalled,
10026            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10027        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10028                + ", old=" + deletedPackage);
10029        boolean updatedSettings = false;
10030        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10031                PackageParser.PARSE_IS_SYSTEM;
10032        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10033            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10034        }
10035        String packageName = deletedPackage.packageName;
10036        if (packageName == null) {
10037            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10038                    "Attempt to delete null packageName.");
10039            return;
10040        }
10041        PackageParser.Package oldPkg;
10042        PackageSetting oldPkgSetting;
10043        // reader
10044        synchronized (mPackages) {
10045            oldPkg = mPackages.get(packageName);
10046            oldPkgSetting = mSettings.mPackages.get(packageName);
10047            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10048                    (oldPkgSetting == null)) {
10049                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10050                        "Couldn't find package:" + packageName + " information");
10051                return;
10052            }
10053        }
10054
10055        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10056
10057        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10058        res.removedInfo.removedPackage = packageName;
10059        // Remove existing system package
10060        removePackageLI(oldPkgSetting, true);
10061        // writer
10062        synchronized (mPackages) {
10063            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10064                // We didn't need to disable the .apk as a current system package,
10065                // which means we are replacing another update that is already
10066                // installed.  We need to make sure to delete the older one's .apk.
10067                res.removedInfo.args = createInstallArgsForExisting(0,
10068                        deletedPackage.applicationInfo.getCodePath(),
10069                        deletedPackage.applicationInfo.getResourcePath(),
10070                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10071                        getAppDexInstructionSets(deletedPackage.applicationInfo),
10072                        isMultiArch(deletedPackage.applicationInfo));
10073            } else {
10074                res.removedInfo.args = null;
10075            }
10076        }
10077
10078        // Successfully disabled the old package. Now proceed with re-installation
10079        deleteCodeCacheDirsLI(packageName);
10080
10081        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10082        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10083
10084        PackageParser.Package newPackage = null;
10085        try {
10086            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10087            if (newPackage.mExtras != null) {
10088                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10089                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10090                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10091
10092                // is the update attempting to change shared user? that isn't going to work...
10093                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10094                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10095                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10096                            + " to " + newPkgSetting.sharedUser);
10097                    updatedSettings = true;
10098                }
10099            }
10100
10101            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10102                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10103                updatedSettings = true;
10104            }
10105
10106        } catch (PackageManagerException e) {
10107            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10108        }
10109
10110        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10111            // Re installation failed. Restore old information
10112            // Remove new pkg information
10113            if (newPackage != null) {
10114                removeInstalledPackageLI(newPackage, true);
10115            }
10116            // Add back the old system package
10117            try {
10118                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user,
10119                        null);
10120            } catch (PackageManagerException e) {
10121                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10122            }
10123            // Restore the old system information in Settings
10124            synchronized(mPackages) {
10125                if (updatedSettings) {
10126                    mSettings.enableSystemPackageLPw(packageName);
10127                    mSettings.setInstallerPackageName(packageName,
10128                            oldPkgSetting.installerPackageName);
10129                }
10130                mSettings.writeLPr();
10131            }
10132        }
10133    }
10134
10135    // Utility method used to move dex files during install.
10136    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10137        // TODO: extend to move split APK dex files
10138        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10139            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10140            for (String instructionSet : instructionSets) {
10141                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10142                        instructionSet);
10143                if (retCode != 0) {
10144                /*
10145                 * Programs may be lazily run through dexopt, so the
10146                 * source may not exist. However, something seems to
10147                 * have gone wrong, so note that dexopt needs to be
10148                 * run again and remove the source file. In addition,
10149                 * remove the target to make sure there isn't a stale
10150                 * file from a previous version of the package.
10151                 */
10152                    newPackage.mDexOptPerformed.clear();
10153                    mInstaller.rmdex(oldCodePath, instructionSet);
10154                    mInstaller.rmdex(newPackage.baseCodePath, instructionSet);
10155                }
10156            }
10157        }
10158        return PackageManager.INSTALL_SUCCEEDED;
10159    }
10160
10161    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10162            int[] allUsers, boolean[] perUserInstalled,
10163            PackageInstalledInfo res) {
10164        String pkgName = newPackage.packageName;
10165        synchronized (mPackages) {
10166            //write settings. the installStatus will be incomplete at this stage.
10167            //note that the new package setting would have already been
10168            //added to mPackages. It hasn't been persisted yet.
10169            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10170            mSettings.writeLPr();
10171        }
10172
10173        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10174
10175        synchronized (mPackages) {
10176            updatePermissionsLPw(newPackage.packageName, newPackage,
10177                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10178                            ? UPDATE_PERMISSIONS_ALL : 0));
10179            // For system-bundled packages, we assume that installing an upgraded version
10180            // of the package implies that the user actually wants to run that new code,
10181            // so we enable the package.
10182            if (isSystemApp(newPackage)) {
10183                // NB: implicit assumption that system package upgrades apply to all users
10184                if (DEBUG_INSTALL) {
10185                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10186                }
10187                PackageSetting ps = mSettings.mPackages.get(pkgName);
10188                if (ps != null) {
10189                    if (res.origUsers != null) {
10190                        for (int userHandle : res.origUsers) {
10191                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10192                                    userHandle, installerPackageName);
10193                        }
10194                    }
10195                    // Also convey the prior install/uninstall state
10196                    if (allUsers != null && perUserInstalled != null) {
10197                        for (int i = 0; i < allUsers.length; i++) {
10198                            if (DEBUG_INSTALL) {
10199                                Slog.d(TAG, "    user " + allUsers[i]
10200                                        + " => " + perUserInstalled[i]);
10201                            }
10202                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10203                        }
10204                        // these install state changes will be persisted in the
10205                        // upcoming call to mSettings.writeLPr().
10206                    }
10207                }
10208            }
10209            res.name = pkgName;
10210            res.uid = newPackage.applicationInfo.uid;
10211            res.pkg = newPackage;
10212            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10213            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10214            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10215            //to update install status
10216            mSettings.writeLPr();
10217        }
10218    }
10219
10220    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10221        int pFlags = args.flags;
10222        String installerPackageName = args.installerPackageName;
10223        File tmpPackageFile = new File(args.getCodePath());
10224        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10225        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10226        boolean replace = false;
10227        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10228                | (newInstall ? SCAN_NEW_INSTALL : 0);
10229        // Result object to be returned
10230        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10231
10232        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10233        // Retrieve PackageSettings and parse package
10234        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10235                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10236                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10237        PackageParser pp = new PackageParser();
10238        pp.setSeparateProcesses(mSeparateProcesses);
10239        pp.setDisplayMetrics(mMetrics);
10240
10241        final PackageParser.Package pkg;
10242        try {
10243            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10244        } catch (PackageParserException e) {
10245            res.setError("Failed parse during installPackageLI", e);
10246            return;
10247        }
10248
10249        String pkgName = res.name = pkg.packageName;
10250        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10251            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10252                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10253                return;
10254            }
10255        }
10256
10257        try {
10258            pp.collectCertificates(pkg, parseFlags);
10259            pp.collectManifestDigest(pkg);
10260        } catch (PackageParserException e) {
10261            res.setError("Failed collect during installPackageLI", e);
10262            return;
10263        }
10264
10265        /* If the installer passed in a manifest digest, compare it now. */
10266        if (args.manifestDigest != null) {
10267            if (DEBUG_INSTALL) {
10268                final String parsedManifest = pkg.manifestDigest == null ? "null"
10269                        : pkg.manifestDigest.toString();
10270                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10271                        + parsedManifest);
10272            }
10273
10274            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10275                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10276                return;
10277            }
10278        } else if (DEBUG_INSTALL) {
10279            final String parsedManifest = pkg.manifestDigest == null
10280                    ? "null" : pkg.manifestDigest.toString();
10281            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10282        }
10283
10284        // Get rid of all references to package scan path via parser.
10285        pp = null;
10286        String oldCodePath = null;
10287        boolean systemApp = false;
10288        synchronized (mPackages) {
10289            // Check whether the newly-scanned package wants to define an already-defined perm
10290            int N = pkg.permissions.size();
10291            for (int i = N-1; i >= 0; i--) {
10292                PackageParser.Permission perm = pkg.permissions.get(i);
10293                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10294                if (bp != null) {
10295                    // If the defining package is signed with our cert, it's okay.  This
10296                    // also includes the "updating the same package" case, of course.
10297                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10298                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10299                        // If the owning package is the system itself, we log but allow
10300                        // install to proceed; we fail the install on all other permission
10301                        // redefinitions.
10302                        if (!bp.sourcePackage.equals("android")) {
10303                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10304                                    + pkg.packageName + " attempting to redeclare permission "
10305                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10306                            res.origPermission = perm.info.name;
10307                            res.origPackage = bp.sourcePackage;
10308                            return;
10309                        } else {
10310                            Slog.w(TAG, "Package " + pkg.packageName
10311                                    + " attempting to redeclare system permission "
10312                                    + perm.info.name + "; ignoring new declaration");
10313                            pkg.permissions.remove(i);
10314                        }
10315                    }
10316                }
10317            }
10318
10319            // Check if installing already existing package
10320            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10321                String oldName = mSettings.mRenamedPackages.get(pkgName);
10322                if (pkg.mOriginalPackages != null
10323                        && pkg.mOriginalPackages.contains(oldName)
10324                        && mPackages.containsKey(oldName)) {
10325                    // This package is derived from an original package,
10326                    // and this device has been updating from that original
10327                    // name.  We must continue using the original name, so
10328                    // rename the new package here.
10329                    pkg.setPackageName(oldName);
10330                    pkgName = pkg.packageName;
10331                    replace = true;
10332                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10333                            + oldName + " pkgName=" + pkgName);
10334                } else if (mPackages.containsKey(pkgName)) {
10335                    // This package, under its official name, already exists
10336                    // on the device; we should replace it.
10337                    replace = true;
10338                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10339                }
10340            }
10341            PackageSetting ps = mSettings.mPackages.get(pkgName);
10342            if (ps != null) {
10343                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10344                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10345                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10346                    systemApp = (ps.pkg.applicationInfo.flags &
10347                            ApplicationInfo.FLAG_SYSTEM) != 0;
10348                }
10349                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10350            }
10351        }
10352
10353        if (systemApp && onSd) {
10354            // Disable updates to system apps on sdcard
10355            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10356                    "Cannot install updates to system apps on sdcard");
10357            return;
10358        }
10359
10360        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10361            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10362            return;
10363        }
10364
10365        if (replace) {
10366            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10367                    installerPackageName, res, args.abiOverride);
10368        } else {
10369            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10370                    installerPackageName, res, args.abiOverride);
10371        }
10372        synchronized (mPackages) {
10373            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10374            if (ps != null) {
10375                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10376            }
10377        }
10378    }
10379
10380    private static boolean isForwardLocked(PackageParser.Package pkg) {
10381        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10382    }
10383
10384    private static boolean isForwardLocked(ApplicationInfo info) {
10385        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10386    }
10387
10388    private boolean isForwardLocked(PackageSetting ps) {
10389        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10390    }
10391
10392    private static boolean isMultiArch(PackageSetting ps) {
10393        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10394    }
10395
10396    private static boolean isMultiArch(ApplicationInfo info) {
10397        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10398    }
10399
10400    private static boolean isExternal(PackageParser.Package pkg) {
10401        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10402    }
10403
10404    private static boolean isExternal(PackageSetting ps) {
10405        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10406    }
10407
10408    private static boolean isExternal(ApplicationInfo info) {
10409        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10410    }
10411
10412    private static boolean isSystemApp(PackageParser.Package pkg) {
10413        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10414    }
10415
10416    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10417        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10418    }
10419
10420    private static boolean isSystemApp(ApplicationInfo info) {
10421        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10422    }
10423
10424    private static boolean isSystemApp(PackageSetting ps) {
10425        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10426    }
10427
10428    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10429        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10430    }
10431
10432    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10433        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10434    }
10435
10436    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10437        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10438    }
10439
10440    private int packageFlagsToInstallFlags(PackageSetting ps) {
10441        int installFlags = 0;
10442        if (isExternal(ps)) {
10443            installFlags |= PackageManager.INSTALL_EXTERNAL;
10444        }
10445        if (isForwardLocked(ps)) {
10446            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10447        }
10448        return installFlags;
10449    }
10450
10451    private void deleteTempPackageFiles() {
10452        final FilenameFilter filter = new FilenameFilter() {
10453            public boolean accept(File dir, String name) {
10454                return name.startsWith("vmdl") && name.endsWith(".tmp");
10455            }
10456        };
10457        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10458            file.delete();
10459        }
10460    }
10461
10462    @Override
10463    public void deletePackageAsUser(final String packageName,
10464                                    final IPackageDeleteObserver observer,
10465                                    final int userId, final int flags) {
10466        mContext.enforceCallingOrSelfPermission(
10467                android.Manifest.permission.DELETE_PACKAGES, null);
10468        final int uid = Binder.getCallingUid();
10469        if (UserHandle.getUserId(uid) != userId) {
10470            mContext.enforceCallingPermission(
10471                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10472                    "deletePackage for user " + userId);
10473        }
10474        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10475            try {
10476                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10477            } catch (RemoteException re) {
10478            }
10479            return;
10480        }
10481
10482        boolean uninstallBlocked = false;
10483        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10484            int[] users = sUserManager.getUserIds();
10485            for (int i = 0; i < users.length; ++i) {
10486                if (getBlockUninstallForUser(packageName, users[i])) {
10487                    uninstallBlocked = true;
10488                    break;
10489                }
10490            }
10491        } else {
10492            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10493        }
10494        if (uninstallBlocked) {
10495            try {
10496                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED);
10497            } catch (RemoteException re) {
10498            }
10499            return;
10500        }
10501
10502        if (DEBUG_REMOVE) {
10503            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10504        }
10505        // Queue up an async operation since the package deletion may take a little while.
10506        mHandler.post(new Runnable() {
10507            public void run() {
10508                mHandler.removeCallbacks(this);
10509                final int returnCode = deletePackageX(packageName, userId, flags);
10510                if (observer != null) {
10511                    try {
10512                        observer.packageDeleted(packageName, returnCode);
10513                    } catch (RemoteException e) {
10514                        Log.i(TAG, "Observer no longer exists.");
10515                    } //end catch
10516                } //end if
10517            } //end run
10518        });
10519    }
10520
10521    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10522        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10523                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10524        try {
10525            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10526                    || dpm.isDeviceOwner(packageName))) {
10527                return true;
10528            }
10529        } catch (RemoteException e) {
10530        }
10531        return false;
10532    }
10533
10534    /**
10535     *  This method is an internal method that could be get invoked either
10536     *  to delete an installed package or to clean up a failed installation.
10537     *  After deleting an installed package, a broadcast is sent to notify any
10538     *  listeners that the package has been installed. For cleaning up a failed
10539     *  installation, the broadcast is not necessary since the package's
10540     *  installation wouldn't have sent the initial broadcast either
10541     *  The key steps in deleting a package are
10542     *  deleting the package information in internal structures like mPackages,
10543     *  deleting the packages base directories through installd
10544     *  updating mSettings to reflect current status
10545     *  persisting settings for later use
10546     *  sending a broadcast if necessary
10547     */
10548    private int deletePackageX(String packageName, int userId, int flags) {
10549        final PackageRemovedInfo info = new PackageRemovedInfo();
10550        final boolean res;
10551
10552        if (isPackageDeviceAdmin(packageName, userId)) {
10553            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10554            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10555        }
10556
10557        boolean removedForAllUsers = false;
10558        boolean systemUpdate = false;
10559
10560        // for the uninstall-updates case and restricted profiles, remember the per-
10561        // userhandle installed state
10562        int[] allUsers;
10563        boolean[] perUserInstalled;
10564        synchronized (mPackages) {
10565            PackageSetting ps = mSettings.mPackages.get(packageName);
10566            allUsers = sUserManager.getUserIds();
10567            perUserInstalled = new boolean[allUsers.length];
10568            for (int i = 0; i < allUsers.length; i++) {
10569                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10570            }
10571        }
10572
10573        synchronized (mInstallLock) {
10574            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10575            res = deletePackageLI(packageName,
10576                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10577                            ? UserHandle.ALL : new UserHandle(userId),
10578                    true, allUsers, perUserInstalled,
10579                    flags | REMOVE_CHATTY, info, true);
10580            systemUpdate = info.isRemovedPackageSystemUpdate;
10581            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10582                removedForAllUsers = true;
10583            }
10584            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10585                    + " removedForAllUsers=" + removedForAllUsers);
10586        }
10587
10588        if (res) {
10589            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10590
10591            // If the removed package was a system update, the old system package
10592            // was re-enabled; we need to broadcast this information
10593            if (systemUpdate) {
10594                Bundle extras = new Bundle(1);
10595                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10596                        ? info.removedAppId : info.uid);
10597                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10598
10599                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10600                        extras, null, null, null);
10601                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10602                        extras, null, null, null);
10603                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10604                        null, packageName, null, null);
10605            }
10606        }
10607        // Force a gc here.
10608        Runtime.getRuntime().gc();
10609        // Delete the resources here after sending the broadcast to let
10610        // other processes clean up before deleting resources.
10611        if (info.args != null) {
10612            synchronized (mInstallLock) {
10613                info.args.doPostDeleteLI(true);
10614            }
10615        }
10616
10617        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10618    }
10619
10620    static class PackageRemovedInfo {
10621        String removedPackage;
10622        int uid = -1;
10623        int removedAppId = -1;
10624        int[] removedUsers = null;
10625        boolean isRemovedPackageSystemUpdate = false;
10626        // Clean up resources deleted packages.
10627        InstallArgs args = null;
10628
10629        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10630            Bundle extras = new Bundle(1);
10631            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10632            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10633            if (replacing) {
10634                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10635            }
10636            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10637            if (removedPackage != null) {
10638                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10639                        extras, null, null, removedUsers);
10640                if (fullRemove && !replacing) {
10641                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10642                            extras, null, null, removedUsers);
10643                }
10644            }
10645            if (removedAppId >= 0) {
10646                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10647                        removedUsers);
10648            }
10649        }
10650    }
10651
10652    /*
10653     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10654     * flag is not set, the data directory is removed as well.
10655     * make sure this flag is set for partially installed apps. If not its meaningless to
10656     * delete a partially installed application.
10657     */
10658    private void removePackageDataLI(PackageSetting ps,
10659            int[] allUserHandles, boolean[] perUserInstalled,
10660            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10661        String packageName = ps.name;
10662        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10663        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10664        // Retrieve object to delete permissions for shared user later on
10665        final PackageSetting deletedPs;
10666        // reader
10667        synchronized (mPackages) {
10668            deletedPs = mSettings.mPackages.get(packageName);
10669            if (outInfo != null) {
10670                outInfo.removedPackage = packageName;
10671                outInfo.removedUsers = deletedPs != null
10672                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10673                        : null;
10674            }
10675        }
10676        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10677            removeDataDirsLI(packageName);
10678            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10679        }
10680        // writer
10681        synchronized (mPackages) {
10682            if (deletedPs != null) {
10683                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10684                    if (outInfo != null) {
10685                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10686                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10687                    }
10688                    if (deletedPs != null) {
10689                        updatePermissionsLPw(deletedPs.name, null, 0);
10690                        if (deletedPs.sharedUser != null) {
10691                            // remove permissions associated with package
10692                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10693                        }
10694                    }
10695                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10696                }
10697                // make sure to preserve per-user disabled state if this removal was just
10698                // a downgrade of a system app to the factory package
10699                if (allUserHandles != null && perUserInstalled != null) {
10700                    if (DEBUG_REMOVE) {
10701                        Slog.d(TAG, "Propagating install state across downgrade");
10702                    }
10703                    for (int i = 0; i < allUserHandles.length; i++) {
10704                        if (DEBUG_REMOVE) {
10705                            Slog.d(TAG, "    user " + allUserHandles[i]
10706                                    + " => " + perUserInstalled[i]);
10707                        }
10708                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10709                    }
10710                }
10711            }
10712            // can downgrade to reader
10713            if (writeSettings) {
10714                // Save settings now
10715                mSettings.writeLPr();
10716            }
10717        }
10718        if (outInfo != null) {
10719            // A user ID was deleted here. Go through all users and remove it
10720            // from KeyStore.
10721            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10722        }
10723    }
10724
10725    static boolean locationIsPrivileged(File path) {
10726        try {
10727            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10728                    .getCanonicalPath();
10729            return path.getCanonicalPath().startsWith(privilegedAppDir);
10730        } catch (IOException e) {
10731            Slog.e(TAG, "Unable to access code path " + path);
10732        }
10733        return false;
10734    }
10735
10736    /*
10737     * Tries to delete system package.
10738     */
10739    private boolean deleteSystemPackageLI(PackageSetting newPs,
10740            int[] allUserHandles, boolean[] perUserInstalled,
10741            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10742        final boolean applyUserRestrictions
10743                = (allUserHandles != null) && (perUserInstalled != null);
10744        PackageSetting disabledPs = null;
10745        // Confirm if the system package has been updated
10746        // An updated system app can be deleted. This will also have to restore
10747        // the system pkg from system partition
10748        // reader
10749        synchronized (mPackages) {
10750            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10751        }
10752        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10753                + " disabledPs=" + disabledPs);
10754        if (disabledPs == null) {
10755            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10756            return false;
10757        } else if (DEBUG_REMOVE) {
10758            Slog.d(TAG, "Deleting system pkg from data partition");
10759        }
10760        if (DEBUG_REMOVE) {
10761            if (applyUserRestrictions) {
10762                Slog.d(TAG, "Remembering install states:");
10763                for (int i = 0; i < allUserHandles.length; i++) {
10764                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10765                }
10766            }
10767        }
10768        // Delete the updated package
10769        outInfo.isRemovedPackageSystemUpdate = true;
10770        if (disabledPs.versionCode < newPs.versionCode) {
10771            // Delete data for downgrades
10772            flags &= ~PackageManager.DELETE_KEEP_DATA;
10773        } else {
10774            // Preserve data by setting flag
10775            flags |= PackageManager.DELETE_KEEP_DATA;
10776        }
10777        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10778                allUserHandles, perUserInstalled, outInfo, writeSettings);
10779        if (!ret) {
10780            return false;
10781        }
10782        // writer
10783        synchronized (mPackages) {
10784            // Reinstate the old system package
10785            mSettings.enableSystemPackageLPw(newPs.name);
10786            // Remove any native libraries from the upgraded package.
10787            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10788        }
10789        // Install the system package
10790        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10791        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10792        if (locationIsPrivileged(disabledPs.codePath)) {
10793            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10794        }
10795
10796        final PackageParser.Package newPkg;
10797        try {
10798            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0,
10799                    null, null);
10800        } catch (PackageManagerException e) {
10801            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10802            return false;
10803        }
10804
10805        // writer
10806        synchronized (mPackages) {
10807            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10808            updatePermissionsLPw(newPkg.packageName, newPkg,
10809                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10810            if (applyUserRestrictions) {
10811                if (DEBUG_REMOVE) {
10812                    Slog.d(TAG, "Propagating install state across reinstall");
10813                }
10814                for (int i = 0; i < allUserHandles.length; i++) {
10815                    if (DEBUG_REMOVE) {
10816                        Slog.d(TAG, "    user " + allUserHandles[i]
10817                                + " => " + perUserInstalled[i]);
10818                    }
10819                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10820                }
10821                // Regardless of writeSettings we need to ensure that this restriction
10822                // state propagation is persisted
10823                mSettings.writeAllUsersPackageRestrictionsLPr();
10824            }
10825            // can downgrade to reader here
10826            if (writeSettings) {
10827                mSettings.writeLPr();
10828            }
10829        }
10830        return true;
10831    }
10832
10833    private boolean deleteInstalledPackageLI(PackageSetting ps,
10834            boolean deleteCodeAndResources, int flags,
10835            int[] allUserHandles, boolean[] perUserInstalled,
10836            PackageRemovedInfo outInfo, boolean writeSettings) {
10837        if (outInfo != null) {
10838            outInfo.uid = ps.appId;
10839        }
10840
10841        // Delete package data from internal structures and also remove data if flag is set
10842        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10843
10844        // Delete application code and resources
10845        if (deleteCodeAndResources && (outInfo != null)) {
10846            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10847                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10848                    getAppDexInstructionSets(ps), isMultiArch(ps));
10849        }
10850        return true;
10851    }
10852
10853    @Override
10854    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10855            int userId) {
10856        mContext.enforceCallingOrSelfPermission(
10857                android.Manifest.permission.DELETE_PACKAGES, null);
10858        synchronized (mPackages) {
10859            PackageSetting ps = mSettings.mPackages.get(packageName);
10860            if (ps == null) {
10861                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10862                return false;
10863            }
10864            if (!ps.getInstalled(userId)) {
10865                // Can't block uninstall for an app that is not installed or enabled.
10866                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10867                return false;
10868            }
10869            ps.setBlockUninstall(blockUninstall, userId);
10870            mSettings.writePackageRestrictionsLPr(userId);
10871        }
10872        return true;
10873    }
10874
10875    @Override
10876    public boolean getBlockUninstallForUser(String packageName, int userId) {
10877        synchronized (mPackages) {
10878            PackageSetting ps = mSettings.mPackages.get(packageName);
10879            if (ps == null) {
10880                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10881                return false;
10882            }
10883            return ps.getBlockUninstall(userId);
10884        }
10885    }
10886
10887    /*
10888     * This method handles package deletion in general
10889     */
10890    private boolean deletePackageLI(String packageName, UserHandle user,
10891            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10892            int flags, PackageRemovedInfo outInfo,
10893            boolean writeSettings) {
10894        if (packageName == null) {
10895            Slog.w(TAG, "Attempt to delete null packageName.");
10896            return false;
10897        }
10898        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10899        PackageSetting ps;
10900        boolean dataOnly = false;
10901        int removeUser = -1;
10902        int appId = -1;
10903        synchronized (mPackages) {
10904            ps = mSettings.mPackages.get(packageName);
10905            if (ps == null) {
10906                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10907                return false;
10908            }
10909            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10910                    && user.getIdentifier() != UserHandle.USER_ALL) {
10911                // The caller is asking that the package only be deleted for a single
10912                // user.  To do this, we just mark its uninstalled state and delete
10913                // its data.  If this is a system app, we only allow this to happen if
10914                // they have set the special DELETE_SYSTEM_APP which requests different
10915                // semantics than normal for uninstalling system apps.
10916                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10917                ps.setUserState(user.getIdentifier(),
10918                        COMPONENT_ENABLED_STATE_DEFAULT,
10919                        false, //installed
10920                        true,  //stopped
10921                        true,  //notLaunched
10922                        false, //hidden
10923                        null, null, null,
10924                        false // blockUninstall
10925                        );
10926                if (!isSystemApp(ps)) {
10927                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10928                        // Other user still have this package installed, so all
10929                        // we need to do is clear this user's data and save that
10930                        // it is uninstalled.
10931                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10932                        removeUser = user.getIdentifier();
10933                        appId = ps.appId;
10934                        mSettings.writePackageRestrictionsLPr(removeUser);
10935                    } else {
10936                        // We need to set it back to 'installed' so the uninstall
10937                        // broadcasts will be sent correctly.
10938                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10939                        ps.setInstalled(true, user.getIdentifier());
10940                    }
10941                } else {
10942                    // This is a system app, so we assume that the
10943                    // other users still have this package installed, so all
10944                    // we need to do is clear this user's data and save that
10945                    // it is uninstalled.
10946                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10947                    removeUser = user.getIdentifier();
10948                    appId = ps.appId;
10949                    mSettings.writePackageRestrictionsLPr(removeUser);
10950                }
10951            }
10952        }
10953
10954        if (removeUser >= 0) {
10955            // From above, we determined that we are deleting this only
10956            // for a single user.  Continue the work here.
10957            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10958            if (outInfo != null) {
10959                outInfo.removedPackage = packageName;
10960                outInfo.removedAppId = appId;
10961                outInfo.removedUsers = new int[] {removeUser};
10962            }
10963            mInstaller.clearUserData(packageName, removeUser);
10964            removeKeystoreDataIfNeeded(removeUser, appId);
10965            schedulePackageCleaning(packageName, removeUser, false);
10966            return true;
10967        }
10968
10969        if (dataOnly) {
10970            // Delete application data first
10971            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10972            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10973            return true;
10974        }
10975
10976        boolean ret = false;
10977        if (isSystemApp(ps)) {
10978            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10979            // When an updated system application is deleted we delete the existing resources as well and
10980            // fall back to existing code in system partition
10981            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10982                    flags, outInfo, writeSettings);
10983        } else {
10984            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10985            // Kill application pre-emptively especially for apps on sd.
10986            killApplication(packageName, ps.appId, "uninstall pkg");
10987            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10988                    allUserHandles, perUserInstalled,
10989                    outInfo, writeSettings);
10990        }
10991
10992        return ret;
10993    }
10994
10995    private final class ClearStorageConnection implements ServiceConnection {
10996        IMediaContainerService mContainerService;
10997
10998        @Override
10999        public void onServiceConnected(ComponentName name, IBinder service) {
11000            synchronized (this) {
11001                mContainerService = IMediaContainerService.Stub.asInterface(service);
11002                notifyAll();
11003            }
11004        }
11005
11006        @Override
11007        public void onServiceDisconnected(ComponentName name) {
11008        }
11009    }
11010
11011    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11012        final boolean mounted;
11013        if (Environment.isExternalStorageEmulated()) {
11014            mounted = true;
11015        } else {
11016            final String status = Environment.getExternalStorageState();
11017
11018            mounted = status.equals(Environment.MEDIA_MOUNTED)
11019                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11020        }
11021
11022        if (!mounted) {
11023            return;
11024        }
11025
11026        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11027        int[] users;
11028        if (userId == UserHandle.USER_ALL) {
11029            users = sUserManager.getUserIds();
11030        } else {
11031            users = new int[] { userId };
11032        }
11033        final ClearStorageConnection conn = new ClearStorageConnection();
11034        if (mContext.bindServiceAsUser(
11035                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11036            try {
11037                for (int curUser : users) {
11038                    long timeout = SystemClock.uptimeMillis() + 5000;
11039                    synchronized (conn) {
11040                        long now = SystemClock.uptimeMillis();
11041                        while (conn.mContainerService == null && now < timeout) {
11042                            try {
11043                                conn.wait(timeout - now);
11044                            } catch (InterruptedException e) {
11045                            }
11046                        }
11047                    }
11048                    if (conn.mContainerService == null) {
11049                        return;
11050                    }
11051
11052                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11053                    clearDirectory(conn.mContainerService,
11054                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11055                    if (allData) {
11056                        clearDirectory(conn.mContainerService,
11057                                userEnv.buildExternalStorageAppDataDirs(packageName));
11058                        clearDirectory(conn.mContainerService,
11059                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11060                    }
11061                }
11062            } finally {
11063                mContext.unbindService(conn);
11064            }
11065        }
11066    }
11067
11068    @Override
11069    public void clearApplicationUserData(final String packageName,
11070            final IPackageDataObserver observer, final int userId) {
11071        mContext.enforceCallingOrSelfPermission(
11072                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11073        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11074        // Queue up an async operation since the package deletion may take a little while.
11075        mHandler.post(new Runnable() {
11076            public void run() {
11077                mHandler.removeCallbacks(this);
11078                final boolean succeeded;
11079                synchronized (mInstallLock) {
11080                    succeeded = clearApplicationUserDataLI(packageName, userId);
11081                }
11082                clearExternalStorageDataSync(packageName, userId, true);
11083                if (succeeded) {
11084                    // invoke DeviceStorageMonitor's update method to clear any notifications
11085                    DeviceStorageMonitorInternal
11086                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11087                    if (dsm != null) {
11088                        dsm.checkMemory();
11089                    }
11090                }
11091                if(observer != null) {
11092                    try {
11093                        observer.onRemoveCompleted(packageName, succeeded);
11094                    } catch (RemoteException e) {
11095                        Log.i(TAG, "Observer no longer exists.");
11096                    }
11097                } //end if observer
11098            } //end run
11099        });
11100    }
11101
11102    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11103        if (packageName == null) {
11104            Slog.w(TAG, "Attempt to delete null packageName.");
11105            return false;
11106        }
11107        PackageParser.Package p;
11108        boolean dataOnly = false;
11109        final int appId;
11110        synchronized (mPackages) {
11111            p = mPackages.get(packageName);
11112            if (p == null) {
11113                dataOnly = true;
11114                PackageSetting ps = mSettings.mPackages.get(packageName);
11115                if ((ps == null) || (ps.pkg == null)) {
11116                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11117                    return false;
11118                }
11119                p = ps.pkg;
11120            }
11121            if (!dataOnly) {
11122                // need to check this only for fully installed applications
11123                if (p == null) {
11124                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11125                    return false;
11126                }
11127                final ApplicationInfo applicationInfo = p.applicationInfo;
11128                if (applicationInfo == null) {
11129                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11130                    return false;
11131                }
11132            }
11133            if (p != null && p.applicationInfo != null) {
11134                appId = p.applicationInfo.uid;
11135            } else {
11136                appId = -1;
11137            }
11138        }
11139        int retCode = mInstaller.clearUserData(packageName, userId);
11140        if (retCode < 0) {
11141            Slog.w(TAG, "Couldn't remove cache files for package: "
11142                    + packageName);
11143            return false;
11144        }
11145        removeKeystoreDataIfNeeded(userId, appId);
11146        return true;
11147    }
11148
11149    /**
11150     * Remove entries from the keystore daemon. Will only remove it if the
11151     * {@code appId} is valid.
11152     */
11153    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11154        if (appId < 0) {
11155            return;
11156        }
11157
11158        final KeyStore keyStore = KeyStore.getInstance();
11159        if (keyStore != null) {
11160            if (userId == UserHandle.USER_ALL) {
11161                for (final int individual : sUserManager.getUserIds()) {
11162                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11163                }
11164            } else {
11165                keyStore.clearUid(UserHandle.getUid(userId, appId));
11166            }
11167        } else {
11168            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11169        }
11170    }
11171
11172    @Override
11173    public void deleteApplicationCacheFiles(final String packageName,
11174            final IPackageDataObserver observer) {
11175        mContext.enforceCallingOrSelfPermission(
11176                android.Manifest.permission.DELETE_CACHE_FILES, null);
11177        // Queue up an async operation since the package deletion may take a little while.
11178        final int userId = UserHandle.getCallingUserId();
11179        mHandler.post(new Runnable() {
11180            public void run() {
11181                mHandler.removeCallbacks(this);
11182                final boolean succeded;
11183                synchronized (mInstallLock) {
11184                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11185                }
11186                clearExternalStorageDataSync(packageName, userId, false);
11187                if(observer != null) {
11188                    try {
11189                        observer.onRemoveCompleted(packageName, succeded);
11190                    } catch (RemoteException e) {
11191                        Log.i(TAG, "Observer no longer exists.");
11192                    }
11193                } //end if observer
11194            } //end run
11195        });
11196    }
11197
11198    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11199        if (packageName == null) {
11200            Slog.w(TAG, "Attempt to delete null packageName.");
11201            return false;
11202        }
11203        PackageParser.Package p;
11204        synchronized (mPackages) {
11205            p = mPackages.get(packageName);
11206        }
11207        if (p == null) {
11208            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11209            return false;
11210        }
11211        final ApplicationInfo applicationInfo = p.applicationInfo;
11212        if (applicationInfo == null) {
11213            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11214            return false;
11215        }
11216        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11217        if (retCode < 0) {
11218            Slog.w(TAG, "Couldn't remove cache files for package: "
11219                       + packageName + " u" + userId);
11220            return false;
11221        }
11222        return true;
11223    }
11224
11225    @Override
11226    public void getPackageSizeInfo(final String packageName, int userHandle,
11227            final IPackageStatsObserver observer) {
11228        mContext.enforceCallingOrSelfPermission(
11229                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11230        if (packageName == null) {
11231            throw new IllegalArgumentException("Attempt to get size of null packageName");
11232        }
11233
11234        PackageStats stats = new PackageStats(packageName, userHandle);
11235
11236        /*
11237         * Queue up an async operation since the package measurement may take a
11238         * little while.
11239         */
11240        Message msg = mHandler.obtainMessage(INIT_COPY);
11241        msg.obj = new MeasureParams(stats, observer);
11242        mHandler.sendMessage(msg);
11243    }
11244
11245    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11246            PackageStats pStats) {
11247        if (packageName == null) {
11248            Slog.w(TAG, "Attempt to get size of null packageName.");
11249            return false;
11250        }
11251        PackageParser.Package p;
11252        boolean dataOnly = false;
11253        String libDirRoot = null;
11254        String asecPath = null;
11255        PackageSetting ps = null;
11256        synchronized (mPackages) {
11257            p = mPackages.get(packageName);
11258            ps = mSettings.mPackages.get(packageName);
11259            if(p == null) {
11260                dataOnly = true;
11261                if((ps == null) || (ps.pkg == null)) {
11262                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11263                    return false;
11264                }
11265                p = ps.pkg;
11266            }
11267            if (ps != null) {
11268                libDirRoot = ps.legacyNativeLibraryPathString;
11269            }
11270            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11271                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11272                if (secureContainerId != null) {
11273                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11274                }
11275            }
11276        }
11277        String publicSrcDir = null;
11278        if(!dataOnly) {
11279            final ApplicationInfo applicationInfo = p.applicationInfo;
11280            if (applicationInfo == null) {
11281                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11282                return false;
11283            }
11284            if (isForwardLocked(p)) {
11285                publicSrcDir = applicationInfo.getBaseResourcePath();
11286            }
11287        }
11288        // TODO: extend to measure size of split APKs
11289        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11290        // not just the first level.
11291        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11292        // just the primary.
11293        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11294                publicSrcDir, asecPath, getAppDexInstructionSets(ps),
11295                pStats);
11296        if (res < 0) {
11297            return false;
11298        }
11299
11300        // Fix-up for forward-locked applications in ASEC containers.
11301        if (!isExternal(p)) {
11302            pStats.codeSize += pStats.externalCodeSize;
11303            pStats.externalCodeSize = 0L;
11304        }
11305
11306        return true;
11307    }
11308
11309
11310    @Override
11311    public void addPackageToPreferred(String packageName) {
11312        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11313    }
11314
11315    @Override
11316    public void removePackageFromPreferred(String packageName) {
11317        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11318    }
11319
11320    @Override
11321    public List<PackageInfo> getPreferredPackages(int flags) {
11322        return new ArrayList<PackageInfo>();
11323    }
11324
11325    private int getUidTargetSdkVersionLockedLPr(int uid) {
11326        Object obj = mSettings.getUserIdLPr(uid);
11327        if (obj instanceof SharedUserSetting) {
11328            final SharedUserSetting sus = (SharedUserSetting) obj;
11329            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11330            final Iterator<PackageSetting> it = sus.packages.iterator();
11331            while (it.hasNext()) {
11332                final PackageSetting ps = it.next();
11333                if (ps.pkg != null) {
11334                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11335                    if (v < vers) vers = v;
11336                }
11337            }
11338            return vers;
11339        } else if (obj instanceof PackageSetting) {
11340            final PackageSetting ps = (PackageSetting) obj;
11341            if (ps.pkg != null) {
11342                return ps.pkg.applicationInfo.targetSdkVersion;
11343            }
11344        }
11345        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11346    }
11347
11348    @Override
11349    public void addPreferredActivity(IntentFilter filter, int match,
11350            ComponentName[] set, ComponentName activity, int userId) {
11351        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11352    }
11353
11354    private void addPreferredActivityInternal(IntentFilter filter, int match,
11355            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11356        // writer
11357        int callingUid = Binder.getCallingUid();
11358        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11359        if (filter.countActions() == 0) {
11360            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11361            return;
11362        }
11363        synchronized (mPackages) {
11364            if (mContext.checkCallingOrSelfPermission(
11365                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11366                    != PackageManager.PERMISSION_GRANTED) {
11367                if (getUidTargetSdkVersionLockedLPr(callingUid)
11368                        < Build.VERSION_CODES.FROYO) {
11369                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11370                            + callingUid);
11371                    return;
11372                }
11373                mContext.enforceCallingOrSelfPermission(
11374                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11375            }
11376
11377            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11378            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11379            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11380                    new PreferredActivity(filter, match, set, activity, always));
11381            mSettings.writePackageRestrictionsLPr(userId);
11382        }
11383    }
11384
11385    @Override
11386    public void replacePreferredActivity(IntentFilter filter, int match,
11387            ComponentName[] set, ComponentName activity) {
11388        if (filter.countActions() != 1) {
11389            throw new IllegalArgumentException(
11390                    "replacePreferredActivity expects filter to have only 1 action.");
11391        }
11392        if (filter.countDataAuthorities() != 0
11393                || filter.countDataPaths() != 0
11394                || filter.countDataSchemes() > 1
11395                || filter.countDataTypes() != 0) {
11396            throw new IllegalArgumentException(
11397                    "replacePreferredActivity expects filter to have no data authorities, " +
11398                    "paths, or types; and at most one scheme.");
11399        }
11400        synchronized (mPackages) {
11401            if (mContext.checkCallingOrSelfPermission(
11402                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11403                    != PackageManager.PERMISSION_GRANTED) {
11404                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11405                        < Build.VERSION_CODES.FROYO) {
11406                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11407                            + Binder.getCallingUid());
11408                    return;
11409                }
11410                mContext.enforceCallingOrSelfPermission(
11411                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11412            }
11413
11414            final int callingUserId = UserHandle.getCallingUserId();
11415            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11416            if (pir != null) {
11417                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11418                if (filter.countDataSchemes() == 1) {
11419                    Uri.Builder builder = new Uri.Builder();
11420                    builder.scheme(filter.getDataScheme(0));
11421                    intent.setData(builder.build());
11422                }
11423                List<PreferredActivity> matches = pir.queryIntent(
11424                        intent, null, true, callingUserId);
11425                if (DEBUG_PREFERRED) {
11426                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11427                }
11428                for (int i = 0; i < matches.size(); i++) {
11429                    PreferredActivity pa = matches.get(i);
11430                    if (DEBUG_PREFERRED) {
11431                        Slog.i(TAG, "Removing preferred activity "
11432                                + pa.mPref.mComponent + ":");
11433                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11434                    }
11435                    pir.removeFilter(pa);
11436                }
11437            }
11438            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11439        }
11440    }
11441
11442    @Override
11443    public void clearPackagePreferredActivities(String packageName) {
11444        final int uid = Binder.getCallingUid();
11445        // writer
11446        synchronized (mPackages) {
11447            PackageParser.Package pkg = mPackages.get(packageName);
11448            if (pkg == null || pkg.applicationInfo.uid != uid) {
11449                if (mContext.checkCallingOrSelfPermission(
11450                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11451                        != PackageManager.PERMISSION_GRANTED) {
11452                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11453                            < Build.VERSION_CODES.FROYO) {
11454                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11455                                + Binder.getCallingUid());
11456                        return;
11457                    }
11458                    mContext.enforceCallingOrSelfPermission(
11459                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11460                }
11461            }
11462
11463            int user = UserHandle.getCallingUserId();
11464            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11465                mSettings.writePackageRestrictionsLPr(user);
11466                scheduleWriteSettingsLocked();
11467            }
11468        }
11469    }
11470
11471    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11472    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11473        ArrayList<PreferredActivity> removed = null;
11474        boolean changed = false;
11475        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11476            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11477            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11478            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11479                continue;
11480            }
11481            Iterator<PreferredActivity> it = pir.filterIterator();
11482            while (it.hasNext()) {
11483                PreferredActivity pa = it.next();
11484                // Mark entry for removal only if it matches the package name
11485                // and the entry is of type "always".
11486                if (packageName == null ||
11487                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11488                                && pa.mPref.mAlways)) {
11489                    if (removed == null) {
11490                        removed = new ArrayList<PreferredActivity>();
11491                    }
11492                    removed.add(pa);
11493                }
11494            }
11495            if (removed != null) {
11496                for (int j=0; j<removed.size(); j++) {
11497                    PreferredActivity pa = removed.get(j);
11498                    pir.removeFilter(pa);
11499                }
11500                changed = true;
11501            }
11502        }
11503        return changed;
11504    }
11505
11506    @Override
11507    public void resetPreferredActivities(int userId) {
11508        mContext.enforceCallingOrSelfPermission(
11509                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11510        // writer
11511        synchronized (mPackages) {
11512            int user = UserHandle.getCallingUserId();
11513            clearPackagePreferredActivitiesLPw(null, user);
11514            mSettings.readDefaultPreferredAppsLPw(this, user);
11515            mSettings.writePackageRestrictionsLPr(user);
11516            scheduleWriteSettingsLocked();
11517        }
11518    }
11519
11520    @Override
11521    public int getPreferredActivities(List<IntentFilter> outFilters,
11522            List<ComponentName> outActivities, String packageName) {
11523
11524        int num = 0;
11525        final int userId = UserHandle.getCallingUserId();
11526        // reader
11527        synchronized (mPackages) {
11528            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11529            if (pir != null) {
11530                final Iterator<PreferredActivity> it = pir.filterIterator();
11531                while (it.hasNext()) {
11532                    final PreferredActivity pa = it.next();
11533                    if (packageName == null
11534                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11535                                    && pa.mPref.mAlways)) {
11536                        if (outFilters != null) {
11537                            outFilters.add(new IntentFilter(pa));
11538                        }
11539                        if (outActivities != null) {
11540                            outActivities.add(pa.mPref.mComponent);
11541                        }
11542                    }
11543                }
11544            }
11545        }
11546
11547        return num;
11548    }
11549
11550    @Override
11551    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11552            int userId) {
11553        int callingUid = Binder.getCallingUid();
11554        if (callingUid != Process.SYSTEM_UID) {
11555            throw new SecurityException(
11556                    "addPersistentPreferredActivity can only be run by the system");
11557        }
11558        if (filter.countActions() == 0) {
11559            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11560            return;
11561        }
11562        synchronized (mPackages) {
11563            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11564                    " :");
11565            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11566            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11567                    new PersistentPreferredActivity(filter, activity));
11568            mSettings.writePackageRestrictionsLPr(userId);
11569        }
11570    }
11571
11572    @Override
11573    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11574        int callingUid = Binder.getCallingUid();
11575        if (callingUid != Process.SYSTEM_UID) {
11576            throw new SecurityException(
11577                    "clearPackagePersistentPreferredActivities can only be run by the system");
11578        }
11579        ArrayList<PersistentPreferredActivity> removed = null;
11580        boolean changed = false;
11581        synchronized (mPackages) {
11582            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11583                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11584                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11585                        .valueAt(i);
11586                if (userId != thisUserId) {
11587                    continue;
11588                }
11589                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11590                while (it.hasNext()) {
11591                    PersistentPreferredActivity ppa = it.next();
11592                    // Mark entry for removal only if it matches the package name.
11593                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11594                        if (removed == null) {
11595                            removed = new ArrayList<PersistentPreferredActivity>();
11596                        }
11597                        removed.add(ppa);
11598                    }
11599                }
11600                if (removed != null) {
11601                    for (int j=0; j<removed.size(); j++) {
11602                        PersistentPreferredActivity ppa = removed.get(j);
11603                        ppir.removeFilter(ppa);
11604                    }
11605                    changed = true;
11606                }
11607            }
11608
11609            if (changed) {
11610                mSettings.writePackageRestrictionsLPr(userId);
11611            }
11612        }
11613    }
11614
11615    @Override
11616    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11617            int targetUserId, int flags) {
11618        mContext.enforceCallingOrSelfPermission(
11619                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11620        if (intentFilter.countActions() == 0) {
11621            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11622            return;
11623        }
11624        synchronized (mPackages) {
11625            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11626                    targetUserId, flags);
11627            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11628            mSettings.writePackageRestrictionsLPr(sourceUserId);
11629        }
11630    }
11631
11632    public void addCrossProfileIntentsForPackage(String packageName,
11633            int sourceUserId, int targetUserId) {
11634        mContext.enforceCallingOrSelfPermission(
11635                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11636        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11637        mSettings.writePackageRestrictionsLPr(sourceUserId);
11638    }
11639
11640    public void removeCrossProfileIntentsForPackage(String packageName,
11641            int sourceUserId, int targetUserId) {
11642        mContext.enforceCallingOrSelfPermission(
11643                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11644        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11645        mSettings.writePackageRestrictionsLPr(sourceUserId);
11646    }
11647
11648    @Override
11649    public void clearCrossProfileIntentFilters(int sourceUserId) {
11650        mContext.enforceCallingOrSelfPermission(
11651                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11652        synchronized (mPackages) {
11653            CrossProfileIntentResolver resolver =
11654                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11655            HashSet<CrossProfileIntentFilter> set =
11656                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11657            for (CrossProfileIntentFilter filter : set) {
11658                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11659                    resolver.removeFilter(filter);
11660                }
11661            }
11662            mSettings.writePackageRestrictionsLPr(sourceUserId);
11663        }
11664    }
11665
11666    @Override
11667    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11668        Intent intent = new Intent(Intent.ACTION_MAIN);
11669        intent.addCategory(Intent.CATEGORY_HOME);
11670
11671        final int callingUserId = UserHandle.getCallingUserId();
11672        List<ResolveInfo> list = queryIntentActivities(intent, null,
11673                PackageManager.GET_META_DATA, callingUserId);
11674        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11675                true, false, false, callingUserId);
11676
11677        allHomeCandidates.clear();
11678        if (list != null) {
11679            for (ResolveInfo ri : list) {
11680                allHomeCandidates.add(ri);
11681            }
11682        }
11683        return (preferred == null || preferred.activityInfo == null)
11684                ? null
11685                : new ComponentName(preferred.activityInfo.packageName,
11686                        preferred.activityInfo.name);
11687    }
11688
11689    @Override
11690    public void setApplicationEnabledSetting(String appPackageName,
11691            int newState, int flags, int userId, String callingPackage) {
11692        if (!sUserManager.exists(userId)) return;
11693        if (callingPackage == null) {
11694            callingPackage = Integer.toString(Binder.getCallingUid());
11695        }
11696        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11697    }
11698
11699    @Override
11700    public void setComponentEnabledSetting(ComponentName componentName,
11701            int newState, int flags, int userId) {
11702        if (!sUserManager.exists(userId)) return;
11703        setEnabledSetting(componentName.getPackageName(),
11704                componentName.getClassName(), newState, flags, userId, null);
11705    }
11706
11707    private void setEnabledSetting(final String packageName, String className, int newState,
11708            final int flags, int userId, String callingPackage) {
11709        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11710              || newState == COMPONENT_ENABLED_STATE_ENABLED
11711              || newState == COMPONENT_ENABLED_STATE_DISABLED
11712              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11713              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11714            throw new IllegalArgumentException("Invalid new component state: "
11715                    + newState);
11716        }
11717        PackageSetting pkgSetting;
11718        final int uid = Binder.getCallingUid();
11719        final int permission = mContext.checkCallingOrSelfPermission(
11720                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11721        enforceCrossUserPermission(uid, userId, false, "set enabled");
11722        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11723        boolean sendNow = false;
11724        boolean isApp = (className == null);
11725        String componentName = isApp ? packageName : className;
11726        int packageUid = -1;
11727        ArrayList<String> components;
11728
11729        // writer
11730        synchronized (mPackages) {
11731            pkgSetting = mSettings.mPackages.get(packageName);
11732            if (pkgSetting == null) {
11733                if (className == null) {
11734                    throw new IllegalArgumentException(
11735                            "Unknown package: " + packageName);
11736                }
11737                throw new IllegalArgumentException(
11738                        "Unknown component: " + packageName
11739                        + "/" + className);
11740            }
11741            // Allow root and verify that userId is not being specified by a different user
11742            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11743                throw new SecurityException(
11744                        "Permission Denial: attempt to change component state from pid="
11745                        + Binder.getCallingPid()
11746                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11747            }
11748            if (className == null) {
11749                // We're dealing with an application/package level state change
11750                if (pkgSetting.getEnabled(userId) == newState) {
11751                    // Nothing to do
11752                    return;
11753                }
11754                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11755                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11756                    // Don't care about who enables an app.
11757                    callingPackage = null;
11758                }
11759                pkgSetting.setEnabled(newState, userId, callingPackage);
11760                // pkgSetting.pkg.mSetEnabled = newState;
11761            } else {
11762                // We're dealing with a component level state change
11763                // First, verify that this is a valid class name.
11764                PackageParser.Package pkg = pkgSetting.pkg;
11765                if (pkg == null || !pkg.hasComponentClassName(className)) {
11766                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11767                        throw new IllegalArgumentException("Component class " + className
11768                                + " does not exist in " + packageName);
11769                    } else {
11770                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11771                                + className + " does not exist in " + packageName);
11772                    }
11773                }
11774                switch (newState) {
11775                case COMPONENT_ENABLED_STATE_ENABLED:
11776                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11777                        return;
11778                    }
11779                    break;
11780                case COMPONENT_ENABLED_STATE_DISABLED:
11781                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11782                        return;
11783                    }
11784                    break;
11785                case COMPONENT_ENABLED_STATE_DEFAULT:
11786                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11787                        return;
11788                    }
11789                    break;
11790                default:
11791                    Slog.e(TAG, "Invalid new component state: " + newState);
11792                    return;
11793                }
11794            }
11795            mSettings.writePackageRestrictionsLPr(userId);
11796            components = mPendingBroadcasts.get(userId, packageName);
11797            final boolean newPackage = components == null;
11798            if (newPackage) {
11799                components = new ArrayList<String>();
11800            }
11801            if (!components.contains(componentName)) {
11802                components.add(componentName);
11803            }
11804            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11805                sendNow = true;
11806                // Purge entry from pending broadcast list if another one exists already
11807                // since we are sending one right away.
11808                mPendingBroadcasts.remove(userId, packageName);
11809            } else {
11810                if (newPackage) {
11811                    mPendingBroadcasts.put(userId, packageName, components);
11812                }
11813                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11814                    // Schedule a message
11815                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11816                }
11817            }
11818        }
11819
11820        long callingId = Binder.clearCallingIdentity();
11821        try {
11822            if (sendNow) {
11823                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11824                sendPackageChangedBroadcast(packageName,
11825                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11826            }
11827        } finally {
11828            Binder.restoreCallingIdentity(callingId);
11829        }
11830    }
11831
11832    private void sendPackageChangedBroadcast(String packageName,
11833            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11834        if (DEBUG_INSTALL)
11835            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11836                    + componentNames);
11837        Bundle extras = new Bundle(4);
11838        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11839        String nameList[] = new String[componentNames.size()];
11840        componentNames.toArray(nameList);
11841        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11842        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11843        extras.putInt(Intent.EXTRA_UID, packageUid);
11844        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11845                new int[] {UserHandle.getUserId(packageUid)});
11846    }
11847
11848    @Override
11849    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11850        if (!sUserManager.exists(userId)) return;
11851        final int uid = Binder.getCallingUid();
11852        final int permission = mContext.checkCallingOrSelfPermission(
11853                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11854        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11855        enforceCrossUserPermission(uid, userId, true, "stop package");
11856        // writer
11857        synchronized (mPackages) {
11858            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11859                    uid, userId)) {
11860                scheduleWritePackageRestrictionsLocked(userId);
11861            }
11862        }
11863    }
11864
11865    @Override
11866    public String getInstallerPackageName(String packageName) {
11867        // reader
11868        synchronized (mPackages) {
11869            return mSettings.getInstallerPackageNameLPr(packageName);
11870        }
11871    }
11872
11873    @Override
11874    public int getApplicationEnabledSetting(String packageName, int userId) {
11875        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11876        int uid = Binder.getCallingUid();
11877        enforceCrossUserPermission(uid, userId, false, "get enabled");
11878        // reader
11879        synchronized (mPackages) {
11880            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11881        }
11882    }
11883
11884    @Override
11885    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11886        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11887        int uid = Binder.getCallingUid();
11888        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11889        // reader
11890        synchronized (mPackages) {
11891            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11892        }
11893    }
11894
11895    @Override
11896    public void enterSafeMode() {
11897        enforceSystemOrRoot("Only the system can request entering safe mode");
11898
11899        if (!mSystemReady) {
11900            mSafeMode = true;
11901        }
11902    }
11903
11904    @Override
11905    public void systemReady() {
11906        mSystemReady = true;
11907
11908        // Read the compatibilty setting when the system is ready.
11909        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11910                mContext.getContentResolver(),
11911                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11912        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11913        if (DEBUG_SETTINGS) {
11914            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11915        }
11916
11917        synchronized (mPackages) {
11918            // Verify that all of the preferred activity components actually
11919            // exist.  It is possible for applications to be updated and at
11920            // that point remove a previously declared activity component that
11921            // had been set as a preferred activity.  We try to clean this up
11922            // the next time we encounter that preferred activity, but it is
11923            // possible for the user flow to never be able to return to that
11924            // situation so here we do a sanity check to make sure we haven't
11925            // left any junk around.
11926            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11927            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11928                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11929                removed.clear();
11930                for (PreferredActivity pa : pir.filterSet()) {
11931                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11932                        removed.add(pa);
11933                    }
11934                }
11935                if (removed.size() > 0) {
11936                    for (int r=0; r<removed.size(); r++) {
11937                        PreferredActivity pa = removed.get(r);
11938                        Slog.w(TAG, "Removing dangling preferred activity: "
11939                                + pa.mPref.mComponent);
11940                        pir.removeFilter(pa);
11941                    }
11942                    mSettings.writePackageRestrictionsLPr(
11943                            mSettings.mPreferredActivities.keyAt(i));
11944                }
11945            }
11946        }
11947        sUserManager.systemReady();
11948    }
11949
11950    @Override
11951    public boolean isSafeMode() {
11952        return mSafeMode;
11953    }
11954
11955    @Override
11956    public boolean hasSystemUidErrors() {
11957        return mHasSystemUidErrors;
11958    }
11959
11960    static String arrayToString(int[] array) {
11961        StringBuffer buf = new StringBuffer(128);
11962        buf.append('[');
11963        if (array != null) {
11964            for (int i=0; i<array.length; i++) {
11965                if (i > 0) buf.append(", ");
11966                buf.append(array[i]);
11967            }
11968        }
11969        buf.append(']');
11970        return buf.toString();
11971    }
11972
11973    static class DumpState {
11974        public static final int DUMP_LIBS = 1 << 0;
11975        public static final int DUMP_FEATURES = 1 << 1;
11976        public static final int DUMP_RESOLVERS = 1 << 2;
11977        public static final int DUMP_PERMISSIONS = 1 << 3;
11978        public static final int DUMP_PACKAGES = 1 << 4;
11979        public static final int DUMP_SHARED_USERS = 1 << 5;
11980        public static final int DUMP_MESSAGES = 1 << 6;
11981        public static final int DUMP_PROVIDERS = 1 << 7;
11982        public static final int DUMP_VERIFIERS = 1 << 8;
11983        public static final int DUMP_PREFERRED = 1 << 9;
11984        public static final int DUMP_PREFERRED_XML = 1 << 10;
11985        public static final int DUMP_KEYSETS = 1 << 11;
11986        public static final int DUMP_VERSION = 1 << 12;
11987        public static final int DUMP_INSTALLS = 1 << 13;
11988
11989        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11990
11991        private int mTypes;
11992
11993        private int mOptions;
11994
11995        private boolean mTitlePrinted;
11996
11997        private SharedUserSetting mSharedUser;
11998
11999        public boolean isDumping(int type) {
12000            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12001                return true;
12002            }
12003
12004            return (mTypes & type) != 0;
12005        }
12006
12007        public void setDump(int type) {
12008            mTypes |= type;
12009        }
12010
12011        public boolean isOptionEnabled(int option) {
12012            return (mOptions & option) != 0;
12013        }
12014
12015        public void setOptionEnabled(int option) {
12016            mOptions |= option;
12017        }
12018
12019        public boolean onTitlePrinted() {
12020            final boolean printed = mTitlePrinted;
12021            mTitlePrinted = true;
12022            return printed;
12023        }
12024
12025        public boolean getTitlePrinted() {
12026            return mTitlePrinted;
12027        }
12028
12029        public void setTitlePrinted(boolean enabled) {
12030            mTitlePrinted = enabled;
12031        }
12032
12033        public SharedUserSetting getSharedUser() {
12034            return mSharedUser;
12035        }
12036
12037        public void setSharedUser(SharedUserSetting user) {
12038            mSharedUser = user;
12039        }
12040    }
12041
12042    @Override
12043    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12044        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12045                != PackageManager.PERMISSION_GRANTED) {
12046            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12047                    + Binder.getCallingPid()
12048                    + ", uid=" + Binder.getCallingUid()
12049                    + " without permission "
12050                    + android.Manifest.permission.DUMP);
12051            return;
12052        }
12053
12054        DumpState dumpState = new DumpState();
12055        boolean fullPreferred = false;
12056        boolean checkin = false;
12057
12058        String packageName = null;
12059
12060        int opti = 0;
12061        while (opti < args.length) {
12062            String opt = args[opti];
12063            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12064                break;
12065            }
12066            opti++;
12067            if ("-a".equals(opt)) {
12068                // Right now we only know how to print all.
12069            } else if ("-h".equals(opt)) {
12070                pw.println("Package manager dump options:");
12071                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12072                pw.println("    --checkin: dump for a checkin");
12073                pw.println("    -f: print details of intent filters");
12074                pw.println("    -h: print this help");
12075                pw.println("  cmd may be one of:");
12076                pw.println("    l[ibraries]: list known shared libraries");
12077                pw.println("    f[ibraries]: list device features");
12078                pw.println("    k[eysets]: print known keysets");
12079                pw.println("    r[esolvers]: dump intent resolvers");
12080                pw.println("    perm[issions]: dump permissions");
12081                pw.println("    pref[erred]: print preferred package settings");
12082                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12083                pw.println("    prov[iders]: dump content providers");
12084                pw.println("    p[ackages]: dump installed packages");
12085                pw.println("    s[hared-users]: dump shared user IDs");
12086                pw.println("    m[essages]: print collected runtime messages");
12087                pw.println("    v[erifiers]: print package verifier info");
12088                pw.println("    version: print database version info");
12089                pw.println("    write: write current settings now");
12090                pw.println("    <package.name>: info about given package");
12091                pw.println("    installs: details about install sessions");
12092                return;
12093            } else if ("--checkin".equals(opt)) {
12094                checkin = true;
12095            } else if ("-f".equals(opt)) {
12096                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12097            } else {
12098                pw.println("Unknown argument: " + opt + "; use -h for help");
12099            }
12100        }
12101
12102        // Is the caller requesting to dump a particular piece of data?
12103        if (opti < args.length) {
12104            String cmd = args[opti];
12105            opti++;
12106            // Is this a package name?
12107            if ("android".equals(cmd) || cmd.contains(".")) {
12108                packageName = cmd;
12109                // When dumping a single package, we always dump all of its
12110                // filter information since the amount of data will be reasonable.
12111                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12112            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12113                dumpState.setDump(DumpState.DUMP_LIBS);
12114            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12115                dumpState.setDump(DumpState.DUMP_FEATURES);
12116            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12117                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12118            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12119                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12120            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12121                dumpState.setDump(DumpState.DUMP_PREFERRED);
12122            } else if ("preferred-xml".equals(cmd)) {
12123                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12124                if (opti < args.length && "--full".equals(args[opti])) {
12125                    fullPreferred = true;
12126                    opti++;
12127                }
12128            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12129                dumpState.setDump(DumpState.DUMP_PACKAGES);
12130            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12131                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12132            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12133                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12134            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12135                dumpState.setDump(DumpState.DUMP_MESSAGES);
12136            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12137                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12138            } else if ("version".equals(cmd)) {
12139                dumpState.setDump(DumpState.DUMP_VERSION);
12140            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12141                dumpState.setDump(DumpState.DUMP_KEYSETS);
12142            } else if ("write".equals(cmd)) {
12143                synchronized (mPackages) {
12144                    mSettings.writeLPr();
12145                    pw.println("Settings written.");
12146                    return;
12147                }
12148            } else if ("installs".equals(cmd)) {
12149                dumpState.setDump(DumpState.DUMP_INSTALLS);
12150            }
12151        }
12152
12153        if (checkin) {
12154            pw.println("vers,1");
12155        }
12156
12157        // reader
12158        synchronized (mPackages) {
12159            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12160                if (!checkin) {
12161                    if (dumpState.onTitlePrinted())
12162                        pw.println();
12163                    pw.println("Database versions:");
12164                    pw.print("  SDK Version:");
12165                    pw.print(" internal=");
12166                    pw.print(mSettings.mInternalSdkPlatform);
12167                    pw.print(" external=");
12168                    pw.println(mSettings.mExternalSdkPlatform);
12169                    pw.print("  DB Version:");
12170                    pw.print(" internal=");
12171                    pw.print(mSettings.mInternalDatabaseVersion);
12172                    pw.print(" external=");
12173                    pw.println(mSettings.mExternalDatabaseVersion);
12174                }
12175            }
12176
12177            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12178                if (!checkin) {
12179                    if (dumpState.onTitlePrinted())
12180                        pw.println();
12181                    pw.println("Verifiers:");
12182                    pw.print("  Required: ");
12183                    pw.print(mRequiredVerifierPackage);
12184                    pw.print(" (uid=");
12185                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12186                    pw.println(")");
12187                } else if (mRequiredVerifierPackage != null) {
12188                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12189                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12190                }
12191            }
12192
12193            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12194                boolean printedHeader = false;
12195                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12196                while (it.hasNext()) {
12197                    String name = it.next();
12198                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12199                    if (!checkin) {
12200                        if (!printedHeader) {
12201                            if (dumpState.onTitlePrinted())
12202                                pw.println();
12203                            pw.println("Libraries:");
12204                            printedHeader = true;
12205                        }
12206                        pw.print("  ");
12207                    } else {
12208                        pw.print("lib,");
12209                    }
12210                    pw.print(name);
12211                    if (!checkin) {
12212                        pw.print(" -> ");
12213                    }
12214                    if (ent.path != null) {
12215                        if (!checkin) {
12216                            pw.print("(jar) ");
12217                            pw.print(ent.path);
12218                        } else {
12219                            pw.print(",jar,");
12220                            pw.print(ent.path);
12221                        }
12222                    } else {
12223                        if (!checkin) {
12224                            pw.print("(apk) ");
12225                            pw.print(ent.apk);
12226                        } else {
12227                            pw.print(",apk,");
12228                            pw.print(ent.apk);
12229                        }
12230                    }
12231                    pw.println();
12232                }
12233            }
12234
12235            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12236                if (dumpState.onTitlePrinted())
12237                    pw.println();
12238                if (!checkin) {
12239                    pw.println("Features:");
12240                }
12241                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12242                while (it.hasNext()) {
12243                    String name = it.next();
12244                    if (!checkin) {
12245                        pw.print("  ");
12246                    } else {
12247                        pw.print("feat,");
12248                    }
12249                    pw.println(name);
12250                }
12251            }
12252
12253            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12254                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12255                        : "Activity Resolver Table:", "  ", packageName,
12256                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12257                    dumpState.setTitlePrinted(true);
12258                }
12259                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12260                        : "Receiver Resolver Table:", "  ", packageName,
12261                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12262                    dumpState.setTitlePrinted(true);
12263                }
12264                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12265                        : "Service Resolver Table:", "  ", packageName,
12266                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12267                    dumpState.setTitlePrinted(true);
12268                }
12269                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12270                        : "Provider Resolver Table:", "  ", packageName,
12271                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12272                    dumpState.setTitlePrinted(true);
12273                }
12274            }
12275
12276            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12277                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12278                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12279                    int user = mSettings.mPreferredActivities.keyAt(i);
12280                    if (pir.dump(pw,
12281                            dumpState.getTitlePrinted()
12282                                ? "\nPreferred Activities User " + user + ":"
12283                                : "Preferred Activities User " + user + ":", "  ",
12284                            packageName, true)) {
12285                        dumpState.setTitlePrinted(true);
12286                    }
12287                }
12288            }
12289
12290            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12291                pw.flush();
12292                FileOutputStream fout = new FileOutputStream(fd);
12293                BufferedOutputStream str = new BufferedOutputStream(fout);
12294                XmlSerializer serializer = new FastXmlSerializer();
12295                try {
12296                    serializer.setOutput(str, "utf-8");
12297                    serializer.startDocument(null, true);
12298                    serializer.setFeature(
12299                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12300                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12301                    serializer.endDocument();
12302                    serializer.flush();
12303                } catch (IllegalArgumentException e) {
12304                    pw.println("Failed writing: " + e);
12305                } catch (IllegalStateException e) {
12306                    pw.println("Failed writing: " + e);
12307                } catch (IOException e) {
12308                    pw.println("Failed writing: " + e);
12309                }
12310            }
12311
12312            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12313                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12314                if (packageName == null) {
12315                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12316                        if (iperm == 0) {
12317                            if (dumpState.onTitlePrinted())
12318                                pw.println();
12319                            pw.println("AppOp Permissions:");
12320                        }
12321                        pw.print("  AppOp Permission ");
12322                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12323                        pw.println(":");
12324                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12325                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12326                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12327                        }
12328                    }
12329                }
12330            }
12331
12332            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12333                boolean printedSomething = false;
12334                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12335                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12336                        continue;
12337                    }
12338                    if (!printedSomething) {
12339                        if (dumpState.onTitlePrinted())
12340                            pw.println();
12341                        pw.println("Registered ContentProviders:");
12342                        printedSomething = true;
12343                    }
12344                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12345                    pw.print("    "); pw.println(p.toString());
12346                }
12347                printedSomething = false;
12348                for (Map.Entry<String, PackageParser.Provider> entry :
12349                        mProvidersByAuthority.entrySet()) {
12350                    PackageParser.Provider p = entry.getValue();
12351                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12352                        continue;
12353                    }
12354                    if (!printedSomething) {
12355                        if (dumpState.onTitlePrinted())
12356                            pw.println();
12357                        pw.println("ContentProvider Authorities:");
12358                        printedSomething = true;
12359                    }
12360                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12361                    pw.print("    "); pw.println(p.toString());
12362                    if (p.info != null && p.info.applicationInfo != null) {
12363                        final String appInfo = p.info.applicationInfo.toString();
12364                        pw.print("      applicationInfo="); pw.println(appInfo);
12365                    }
12366                }
12367            }
12368
12369            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12370                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12371            }
12372
12373            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12374                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12375            }
12376
12377            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12378                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12379            }
12380
12381            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12382                if (dumpState.onTitlePrinted()) pw.println();
12383                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12384            }
12385
12386            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12387                if (dumpState.onTitlePrinted()) pw.println();
12388                mSettings.dumpReadMessagesLPr(pw, dumpState);
12389
12390                pw.println();
12391                pw.println("Package warning messages:");
12392                final File fname = getSettingsProblemFile();
12393                FileInputStream in = null;
12394                try {
12395                    in = new FileInputStream(fname);
12396                    final int avail = in.available();
12397                    final byte[] data = new byte[avail];
12398                    in.read(data);
12399                    pw.print(new String(data));
12400                } catch (FileNotFoundException e) {
12401                } catch (IOException e) {
12402                } finally {
12403                    if (in != null) {
12404                        try {
12405                            in.close();
12406                        } catch (IOException e) {
12407                        }
12408                    }
12409                }
12410            }
12411        }
12412    }
12413
12414    // ------- apps on sdcard specific code -------
12415    static final boolean DEBUG_SD_INSTALL = false;
12416
12417    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12418
12419    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12420
12421    private boolean mMediaMounted = false;
12422
12423    private String getEncryptKey() {
12424        try {
12425            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12426                    SD_ENCRYPTION_KEYSTORE_NAME);
12427            if (sdEncKey == null) {
12428                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12429                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12430                if (sdEncKey == null) {
12431                    Slog.e(TAG, "Failed to create encryption keys");
12432                    return null;
12433                }
12434            }
12435            return sdEncKey;
12436        } catch (NoSuchAlgorithmException nsae) {
12437            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12438            return null;
12439        } catch (IOException ioe) {
12440            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12441            return null;
12442        }
12443
12444    }
12445
12446    /* package */static String getTempContainerId() {
12447        int tmpIdx = 1;
12448        String list[] = PackageHelper.getSecureContainerList();
12449        if (list != null) {
12450            for (final String name : list) {
12451                // Ignore null and non-temporary container entries
12452                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12453                    continue;
12454                }
12455
12456                String subStr = name.substring(mTempContainerPrefix.length());
12457                try {
12458                    int cid = Integer.parseInt(subStr);
12459                    if (cid >= tmpIdx) {
12460                        tmpIdx = cid + 1;
12461                    }
12462                } catch (NumberFormatException e) {
12463                }
12464            }
12465        }
12466        return mTempContainerPrefix + tmpIdx;
12467    }
12468
12469    /*
12470     * Update media status on PackageManager.
12471     */
12472    @Override
12473    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12474        int callingUid = Binder.getCallingUid();
12475        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12476            throw new SecurityException("Media status can only be updated by the system");
12477        }
12478        // reader; this apparently protects mMediaMounted, but should probably
12479        // be a different lock in that case.
12480        synchronized (mPackages) {
12481            Log.i(TAG, "Updating external media status from "
12482                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12483                    + (mediaStatus ? "mounted" : "unmounted"));
12484            if (DEBUG_SD_INSTALL)
12485                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12486                        + ", mMediaMounted=" + mMediaMounted);
12487            if (mediaStatus == mMediaMounted) {
12488                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12489                        : 0, -1);
12490                mHandler.sendMessage(msg);
12491                return;
12492            }
12493            mMediaMounted = mediaStatus;
12494        }
12495        // Queue up an async operation since the package installation may take a
12496        // little while.
12497        mHandler.post(new Runnable() {
12498            public void run() {
12499                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12500            }
12501        });
12502    }
12503
12504    /**
12505     * Called by MountService when the initial ASECs to scan are available.
12506     * Should block until all the ASEC containers are finished being scanned.
12507     */
12508    public void scanAvailableAsecs() {
12509        updateExternalMediaStatusInner(true, false, false);
12510        if (mShouldRestoreconData) {
12511            SELinuxMMAC.setRestoreconDone();
12512            mShouldRestoreconData = false;
12513        }
12514    }
12515
12516    /*
12517     * Collect information of applications on external media, map them against
12518     * existing containers and update information based on current mount status.
12519     * Please note that we always have to report status if reportStatus has been
12520     * set to true especially when unloading packages.
12521     */
12522    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12523            boolean externalStorage) {
12524        // Collection of uids
12525        int uidArr[] = null;
12526        // Collection of stale containers
12527        HashSet<String> removeCids = new HashSet<String>();
12528        // Collection of packages on external media with valid containers.
12529        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12530        // Get list of secure containers.
12531        final String list[] = PackageHelper.getSecureContainerList();
12532        if (list == null || list.length == 0) {
12533            Log.i(TAG, "No secure containers on sdcard");
12534        } else {
12535            // Process list of secure containers and categorize them
12536            // as active or stale based on their package internal state.
12537            int uidList[] = new int[list.length];
12538            int num = 0;
12539            // reader
12540            synchronized (mPackages) {
12541                for (String cid : list) {
12542                    if (DEBUG_SD_INSTALL)
12543                        Log.i(TAG, "Processing container " + cid);
12544                    String pkgName = getAsecPackageName(cid);
12545                    if (pkgName == null) {
12546                        if (DEBUG_SD_INSTALL)
12547                            Log.i(TAG, "Container : " + cid + " stale");
12548                        removeCids.add(cid);
12549                        continue;
12550                    }
12551                    if (DEBUG_SD_INSTALL)
12552                        Log.i(TAG, "Looking for pkg : " + pkgName);
12553
12554                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12555                    if (ps == null) {
12556                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12557                        removeCids.add(cid);
12558                        continue;
12559                    }
12560
12561                    /*
12562                     * Skip packages that are not external if we're unmounting
12563                     * external storage.
12564                     */
12565                    if (externalStorage && !isMounted && !isExternal(ps)) {
12566                        continue;
12567                    }
12568
12569                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12570                            getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps));
12571                    // The package status is changed only if the code path
12572                    // matches between settings and the container id.
12573                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12574                        if (DEBUG_SD_INSTALL) {
12575                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12576                                    + " at code path: " + ps.codePathString);
12577                        }
12578
12579                        // We do have a valid package installed on sdcard
12580                        processCids.put(args, ps.codePathString);
12581                        final int uid = ps.appId;
12582                        if (uid != -1) {
12583                            uidList[num++] = uid;
12584                        }
12585                    } else {
12586                        Log.i(TAG, "Deleting stale container for " + cid);
12587                        removeCids.add(cid);
12588                    }
12589                }
12590            }
12591
12592            if (num > 0) {
12593                // Sort uid list
12594                Arrays.sort(uidList, 0, num);
12595                // Throw away duplicates
12596                uidArr = new int[num];
12597                uidArr[0] = uidList[0];
12598                int di = 0;
12599                for (int i = 1; i < num; i++) {
12600                    if (uidList[i - 1] != uidList[i]) {
12601                        uidArr[di++] = uidList[i];
12602                    }
12603                }
12604            }
12605        }
12606        // Process packages with valid entries.
12607        if (isMounted) {
12608            if (DEBUG_SD_INSTALL)
12609                Log.i(TAG, "Loading packages");
12610            loadMediaPackages(processCids, uidArr, removeCids);
12611            startCleaningPackages();
12612        } else {
12613            if (DEBUG_SD_INSTALL)
12614                Log.i(TAG, "Unloading packages");
12615            unloadMediaPackages(processCids, uidArr, reportStatus);
12616        }
12617    }
12618
12619   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12620           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12621        int size = pkgList.size();
12622        if (size > 0) {
12623            // Send broadcasts here
12624            Bundle extras = new Bundle();
12625            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12626                    .toArray(new String[size]));
12627            if (uidArr != null) {
12628                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12629            }
12630            if (replacing) {
12631                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12632            }
12633            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12634                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12635            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12636        }
12637    }
12638
12639   /*
12640     * Look at potentially valid container ids from processCids If package
12641     * information doesn't match the one on record or package scanning fails,
12642     * the cid is added to list of removeCids. We currently don't delete stale
12643     * containers.
12644     */
12645   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12646            HashSet<String> removeCids) {
12647        ArrayList<String> pkgList = new ArrayList<String>();
12648        Set<AsecInstallArgs> keys = processCids.keySet();
12649        boolean doGc = false;
12650        for (AsecInstallArgs args : keys) {
12651            String codePath = processCids.get(args);
12652            if (DEBUG_SD_INSTALL)
12653                Log.i(TAG, "Loading container : " + args.cid);
12654            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12655            try {
12656                // Make sure there are no container errors first.
12657                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12658                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12659                            + " when installing from sdcard");
12660                    continue;
12661                }
12662                // Check code path here.
12663                if (codePath == null || !codePath.equals(args.getCodePath())) {
12664                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12665                            + " does not match one in settings " + codePath);
12666                    continue;
12667                }
12668                // Parse package
12669                int parseFlags = mDefParseFlags;
12670                if (args.isExternal()) {
12671                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12672                }
12673                if (args.isFwdLocked()) {
12674                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12675                }
12676
12677                doGc = true;
12678                synchronized (mInstallLock) {
12679                    PackageParser.Package pkg = null;
12680                    try {
12681                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null);
12682                    } catch (PackageManagerException e) {
12683                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12684                    }
12685                    // Scan the package
12686                    if (pkg != null) {
12687                        /*
12688                         * TODO why is the lock being held? doPostInstall is
12689                         * called in other places without the lock. This needs
12690                         * to be straightened out.
12691                         */
12692                        // writer
12693                        synchronized (mPackages) {
12694                            retCode = PackageManager.INSTALL_SUCCEEDED;
12695                            pkgList.add(pkg.packageName);
12696                            // Post process args
12697                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12698                                    pkg.applicationInfo.uid);
12699                        }
12700                    } else {
12701                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12702                    }
12703                }
12704
12705            } finally {
12706                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12707                    // Don't destroy container here. Wait till gc clears things
12708                    // up.
12709                    removeCids.add(args.cid);
12710                }
12711            }
12712        }
12713        // writer
12714        synchronized (mPackages) {
12715            // If the platform SDK has changed since the last time we booted,
12716            // we need to re-grant app permission to catch any new ones that
12717            // appear. This is really a hack, and means that apps can in some
12718            // cases get permissions that the user didn't initially explicitly
12719            // allow... it would be nice to have some better way to handle
12720            // this situation.
12721            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12722            if (regrantPermissions)
12723                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12724                        + mSdkVersion + "; regranting permissions for external storage");
12725            mSettings.mExternalSdkPlatform = mSdkVersion;
12726
12727            // Make sure group IDs have been assigned, and any permission
12728            // changes in other apps are accounted for
12729            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12730                    | (regrantPermissions
12731                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12732                            : 0));
12733
12734            mSettings.updateExternalDatabaseVersion();
12735
12736            // can downgrade to reader
12737            // Persist settings
12738            mSettings.writeLPr();
12739        }
12740        // Send a broadcast to let everyone know we are done processing
12741        if (pkgList.size() > 0) {
12742            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12743        }
12744        // Force gc to avoid any stale parser references that we might have.
12745        if (doGc) {
12746            Runtime.getRuntime().gc();
12747        }
12748        // List stale containers and destroy stale temporary containers.
12749        if (removeCids != null) {
12750            for (String cid : removeCids) {
12751                if (cid.startsWith(mTempContainerPrefix)) {
12752                    Log.i(TAG, "Destroying stale temporary container " + cid);
12753                    PackageHelper.destroySdDir(cid);
12754                } else {
12755                    Log.w(TAG, "Container " + cid + " is stale");
12756               }
12757           }
12758        }
12759    }
12760
12761   /*
12762     * Utility method to unload a list of specified containers
12763     */
12764    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12765        // Just unmount all valid containers.
12766        for (AsecInstallArgs arg : cidArgs) {
12767            synchronized (mInstallLock) {
12768                arg.doPostDeleteLI(false);
12769           }
12770       }
12771   }
12772
12773    /*
12774     * Unload packages mounted on external media. This involves deleting package
12775     * data from internal structures, sending broadcasts about diabled packages,
12776     * gc'ing to free up references, unmounting all secure containers
12777     * corresponding to packages on external media, and posting a
12778     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12779     * that we always have to post this message if status has been requested no
12780     * matter what.
12781     */
12782    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12783            final boolean reportStatus) {
12784        if (DEBUG_SD_INSTALL)
12785            Log.i(TAG, "unloading media packages");
12786        ArrayList<String> pkgList = new ArrayList<String>();
12787        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12788        final Set<AsecInstallArgs> keys = processCids.keySet();
12789        for (AsecInstallArgs args : keys) {
12790            String pkgName = args.getPackageName();
12791            if (DEBUG_SD_INSTALL)
12792                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12793            // Delete package internally
12794            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12795            synchronized (mInstallLock) {
12796                boolean res = deletePackageLI(pkgName, null, false, null, null,
12797                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12798                if (res) {
12799                    pkgList.add(pkgName);
12800                } else {
12801                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12802                    failedList.add(args);
12803                }
12804            }
12805        }
12806
12807        // reader
12808        synchronized (mPackages) {
12809            // We didn't update the settings after removing each package;
12810            // write them now for all packages.
12811            mSettings.writeLPr();
12812        }
12813
12814        // We have to absolutely send UPDATED_MEDIA_STATUS only
12815        // after confirming that all the receivers processed the ordered
12816        // broadcast when packages get disabled, force a gc to clean things up.
12817        // and unload all the containers.
12818        if (pkgList.size() > 0) {
12819            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12820                    new IIntentReceiver.Stub() {
12821                public void performReceive(Intent intent, int resultCode, String data,
12822                        Bundle extras, boolean ordered, boolean sticky,
12823                        int sendingUser) throws RemoteException {
12824                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12825                            reportStatus ? 1 : 0, 1, keys);
12826                    mHandler.sendMessage(msg);
12827                }
12828            });
12829        } else {
12830            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12831                    keys);
12832            mHandler.sendMessage(msg);
12833        }
12834    }
12835
12836    /** Binder call */
12837    @Override
12838    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12839            final int flags) {
12840        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12841        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12842        int returnCode = PackageManager.MOVE_SUCCEEDED;
12843        int currFlags = 0;
12844        int newFlags = 0;
12845        // reader
12846        synchronized (mPackages) {
12847            PackageParser.Package pkg = mPackages.get(packageName);
12848            if (pkg == null) {
12849                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12850            } else {
12851                // Disable moving fwd locked apps and system packages
12852                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12853                    Slog.w(TAG, "Cannot move system application");
12854                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12855                } else if (pkg.mOperationPending) {
12856                    Slog.w(TAG, "Attempt to move package which has pending operations");
12857                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12858                } else {
12859                    // Find install location first
12860                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12861                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12862                        Slog.w(TAG, "Ambigous flags specified for move location.");
12863                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12864                    } else {
12865                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12866                                : PackageManager.INSTALL_INTERNAL;
12867                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12868                                : PackageManager.INSTALL_INTERNAL;
12869
12870                        if (newFlags == currFlags) {
12871                            Slog.w(TAG, "No move required. Trying to move to same location");
12872                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12873                        } else {
12874                            if (isForwardLocked(pkg)) {
12875                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12876                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12877                            }
12878                        }
12879                    }
12880                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12881                        pkg.mOperationPending = true;
12882                    }
12883                }
12884            }
12885
12886            /*
12887             * TODO this next block probably shouldn't be inside the lock. We
12888             * can't guarantee these won't change after this is fired off
12889             * anyway.
12890             */
12891            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12892                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false),
12893                        returnCode);
12894            } else {
12895                Message msg = mHandler.obtainMessage(INIT_COPY);
12896                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
12897                final boolean multiArch = isMultiArch(pkg.applicationInfo);
12898                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
12899                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
12900                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch);
12901                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12902                        instructionSets, pkg.applicationInfo.uid, user, multiArch);
12903                msg.obj = mp;
12904                mHandler.sendMessage(msg);
12905            }
12906        }
12907    }
12908
12909    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12910        // Queue up an async operation since the package deletion may take a
12911        // little while.
12912        mHandler.post(new Runnable() {
12913            public void run() {
12914                // TODO fix this; this does nothing.
12915                mHandler.removeCallbacks(this);
12916                int returnCode = currentStatus;
12917                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12918                    int uidArr[] = null;
12919                    ArrayList<String> pkgList = null;
12920                    synchronized (mPackages) {
12921                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12922                        if (pkg == null) {
12923                            Slog.w(TAG, " Package " + mp.packageName
12924                                    + " doesn't exist. Aborting move");
12925                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12926                        } else if (!mp.srcArgs.getCodePath().equals(
12927                                pkg.applicationInfo.getCodePath())) {
12928                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12929                                    + mp.srcArgs.getCodePath() + " to "
12930                                    + pkg.applicationInfo.getCodePath()
12931                                    + " Aborting move and returning error");
12932                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12933                        } else {
12934                            uidArr = new int[] {
12935                                pkg.applicationInfo.uid
12936                            };
12937                            pkgList = new ArrayList<String>();
12938                            pkgList.add(mp.packageName);
12939                        }
12940                    }
12941                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12942                        // Send resources unavailable broadcast
12943                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12944                        // Update package code and resource paths
12945                        synchronized (mInstallLock) {
12946                            synchronized (mPackages) {
12947                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12948                                // Recheck for package again.
12949                                if (pkg == null) {
12950                                    Slog.w(TAG, " Package " + mp.packageName
12951                                            + " doesn't exist. Aborting move");
12952                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12953                                } else if (!mp.srcArgs.getCodePath().equals(
12954                                        pkg.applicationInfo.getCodePath())) {
12955                                    Slog.w(TAG, "Package " + mp.packageName
12956                                            + " code path changed from " + mp.srcArgs.getCodePath()
12957                                            + " to " + pkg.applicationInfo.getCodePath()
12958                                            + " Aborting move and returning error");
12959                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12960                                } else {
12961                                    final String oldCodePath = pkg.codePath;
12962                                    final String newCodePath = mp.targetArgs.getCodePath();
12963                                    final String newResPath = mp.targetArgs.getResourcePath();
12964                                    // TODO: This assumes the new style of installation.
12965                                    // should we look at legacyNativeLibraryPath ?
12966                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
12967                                    final File newNativeDir = new File(newNativeRoot);
12968
12969                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12970                                        // TODO(multiArch): Fix this so that it looks at the existing
12971                                        // recorded CPU abis from the package. There's no need for a separate
12972                                        // round of ABI scanning here.
12973                                        NativeLibraryHelper.Handle handle = null;
12974                                        try {
12975                                            handle = NativeLibraryHelper.Handle.create(
12976                                                    new File(newCodePath));
12977                                            final int abi = NativeLibraryHelper.findSupportedAbi(
12978                                                    handle, Build.SUPPORTED_ABIS);
12979                                            if (abi >= 0) {
12980                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12981                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12982                                            }
12983                                        } catch (IOException ioe) {
12984                                            Slog.w(TAG, "Unable to extract native libs for package :"
12985                                                    + mp.packageName, ioe);
12986                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12987                                        } finally {
12988                                            IoUtils.closeQuietly(handle);
12989                                        }
12990                                    }
12991
12992                                    final int[] users = sUserManager.getUserIds();
12993                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12994                                        for (int user : users) {
12995                                            // TODO(multiArch): Fix this so that it links to the
12996                                            // correct directory. We're currently pointing to root. but we
12997                                            // must point to the arch specific subdirectory (if applicable).
12998                                            //
12999                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13000                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13001                                                    newNativeRoot, user) < 0) {
13002                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13003                                            }
13004                                        }
13005                                    }
13006
13007                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13008                                        pkg.codePath = newCodePath;
13009                                        pkg.baseCodePath = newCodePath;
13010                                        // Move dex files around
13011                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13012                                            // Moving of dex files failed. Set
13013                                            // error code and abort move.
13014                                            pkg.codePath = oldCodePath;
13015                                            pkg.baseCodePath = oldCodePath;
13016                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13017                                        }
13018                                    }
13019
13020                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13021                                        pkg.applicationInfo.setCodePath(newCodePath);
13022                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13023                                        pkg.applicationInfo.setSplitCodePaths(null);
13024                                        pkg.applicationInfo.setResourcePath(newResPath);
13025                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13026                                        pkg.applicationInfo.setSplitResourcePaths(null);
13027
13028                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13029                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13030                                        ps.codePathString = ps.codePath.getPath();
13031                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13032                                        ps.resourcePathString = ps.resourcePath.getPath();
13033
13034                                        // Note that we don't have to recalculate the primary and secondary
13035                                        // CPU ABIs because they must already have been calculated during the
13036                                        // initial install of the app.
13037                                        ps.legacyNativeLibraryPathString = null;
13038
13039                                        // Set the application info flag
13040                                        // correctly.
13041                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13042                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13043                                        } else {
13044                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13045                                        }
13046                                        ps.setFlags(pkg.applicationInfo.flags);
13047                                        mAppDirs.remove(oldCodePath);
13048                                        mAppDirs.put(newCodePath, pkg);
13049                                        // Persist settings
13050                                        mSettings.writeLPr();
13051                                    }
13052                                }
13053                            }
13054                        }
13055                        // Send resources available broadcast
13056                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13057                    }
13058                }
13059                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13060                    // Clean up failed installation
13061                    if (mp.targetArgs != null) {
13062                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13063                                -1);
13064                    }
13065                } else {
13066                    // Force a gc to clear things up.
13067                    Runtime.getRuntime().gc();
13068                    // Delete older code
13069                    synchronized (mInstallLock) {
13070                        mp.srcArgs.doPostDeleteLI(true);
13071                    }
13072                }
13073
13074                // Allow more operations on this file if we didn't fail because
13075                // an operation was already pending for this package.
13076                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13077                    synchronized (mPackages) {
13078                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13079                        if (pkg != null) {
13080                            pkg.mOperationPending = false;
13081                       }
13082                   }
13083                }
13084
13085                IPackageMoveObserver observer = mp.observer;
13086                if (observer != null) {
13087                    try {
13088                        observer.packageMoved(mp.packageName, returnCode);
13089                    } catch (RemoteException e) {
13090                        Log.i(TAG, "Observer no longer exists.");
13091                    }
13092                }
13093            }
13094        });
13095    }
13096
13097    @Override
13098    public boolean setInstallLocation(int loc) {
13099        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13100                null);
13101        if (getInstallLocation() == loc) {
13102            return true;
13103        }
13104        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13105                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13106            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13107                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13108            return true;
13109        }
13110        return false;
13111   }
13112
13113    @Override
13114    public int getInstallLocation() {
13115        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13116                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13117                PackageHelper.APP_INSTALL_AUTO);
13118    }
13119
13120    /** Called by UserManagerService */
13121    void cleanUpUserLILPw(int userHandle) {
13122        mDirtyUsers.remove(userHandle);
13123        mSettings.removeUserLPw(userHandle);
13124        mPendingBroadcasts.remove(userHandle);
13125        if (mInstaller != null) {
13126            // Technically, we shouldn't be doing this with the package lock
13127            // held.  However, this is very rare, and there is already so much
13128            // other disk I/O going on, that we'll let it slide for now.
13129            mInstaller.removeUserDataDirs(userHandle);
13130        }
13131        mUserNeedsBadging.delete(userHandle);
13132    }
13133
13134    /** Called by UserManagerService */
13135    void createNewUserLILPw(int userHandle, File path) {
13136        if (mInstaller != null) {
13137            mInstaller.createUserConfig(userHandle);
13138            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13139        }
13140    }
13141
13142    @Override
13143    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13144        mContext.enforceCallingOrSelfPermission(
13145                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13146                "Only package verification agents can read the verifier device identity");
13147
13148        synchronized (mPackages) {
13149            return mSettings.getVerifierDeviceIdentityLPw();
13150        }
13151    }
13152
13153    @Override
13154    public void setPermissionEnforced(String permission, boolean enforced) {
13155        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13156        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13157            synchronized (mPackages) {
13158                if (mSettings.mReadExternalStorageEnforced == null
13159                        || mSettings.mReadExternalStorageEnforced != enforced) {
13160                    mSettings.mReadExternalStorageEnforced = enforced;
13161                    mSettings.writeLPr();
13162                }
13163            }
13164            // kill any non-foreground processes so we restart them and
13165            // grant/revoke the GID.
13166            final IActivityManager am = ActivityManagerNative.getDefault();
13167            if (am != null) {
13168                final long token = Binder.clearCallingIdentity();
13169                try {
13170                    am.killProcessesBelowForeground("setPermissionEnforcement");
13171                } catch (RemoteException e) {
13172                } finally {
13173                    Binder.restoreCallingIdentity(token);
13174                }
13175            }
13176        } else {
13177            throw new IllegalArgumentException("No selective enforcement for " + permission);
13178        }
13179    }
13180
13181    @Override
13182    @Deprecated
13183    public boolean isPermissionEnforced(String permission) {
13184        return true;
13185    }
13186
13187    @Override
13188    public boolean isStorageLow() {
13189        final long token = Binder.clearCallingIdentity();
13190        try {
13191            final DeviceStorageMonitorInternal
13192                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13193            if (dsm != null) {
13194                return dsm.isMemoryLow();
13195            } else {
13196                return false;
13197            }
13198        } finally {
13199            Binder.restoreCallingIdentity(token);
13200        }
13201    }
13202
13203    @Override
13204    public IPackageInstaller getPackageInstaller() {
13205        return mInstallerService;
13206    }
13207
13208    private boolean userNeedsBadging(int userId) {
13209        int index = mUserNeedsBadging.indexOfKey(userId);
13210        if (index < 0) {
13211            final UserInfo userInfo;
13212            final long token = Binder.clearCallingIdentity();
13213            try {
13214                userInfo = sUserManager.getUserInfo(userId);
13215            } finally {
13216                Binder.restoreCallingIdentity(token);
13217            }
13218            final boolean b;
13219            if (userInfo != null && userInfo.isManagedProfile()) {
13220                b = true;
13221            } else {
13222                b = false;
13223            }
13224            mUserNeedsBadging.put(userId, b);
13225            return b;
13226        }
13227        return mUserNeedsBadging.valueAt(index);
13228    }
13229
13230    @Override
13231    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13232        if (packageName == null || alias == null) {
13233            return null;
13234        }
13235        synchronized(mPackages) {
13236            final PackageParser.Package pkg = mPackages.get(packageName);
13237            if (pkg == null) {
13238                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13239                throw new IllegalArgumentException("Unknown package: " + packageName);
13240            }
13241            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13242                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13243                throw new SecurityException("May not access KeySets defined by"
13244                        + " aliases in other applications.");
13245            }
13246            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13247            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13248        }
13249    }
13250
13251    @Override
13252    public KeySetHandle getSigningKeySet(String packageName) {
13253        if (packageName == null) {
13254            return null;
13255        }
13256        synchronized(mPackages) {
13257            final PackageParser.Package pkg = mPackages.get(packageName);
13258            if (pkg == null) {
13259                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13260                throw new IllegalArgumentException("Unknown package: " + packageName);
13261            }
13262            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13263                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13264                throw new SecurityException("May not access signing KeySet of other apps.");
13265            }
13266            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13267            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13268        }
13269    }
13270
13271    @Override
13272    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13273        if (packageName == null || ks == null) {
13274            return false;
13275        }
13276        synchronized(mPackages) {
13277            final PackageParser.Package pkg = mPackages.get(packageName);
13278            if (pkg == null) {
13279                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13280                throw new IllegalArgumentException("Unknown package: " + packageName);
13281            }
13282            if (ks instanceof KeySetHandle) {
13283                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13284                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13285            }
13286            return false;
13287        }
13288    }
13289
13290    @Override
13291    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13292        if (packageName == null || ks == null) {
13293            return false;
13294        }
13295        synchronized(mPackages) {
13296            final PackageParser.Package pkg = mPackages.get(packageName);
13297            if (pkg == null) {
13298                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13299                throw new IllegalArgumentException("Unknown package: " + packageName);
13300            }
13301            if (ks instanceof KeySetHandle) {
13302                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13303                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13304            }
13305            return false;
13306        }
13307    }
13308}
13309