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