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