PackageManagerService.java revision 78a130144bdd047665f00782c481d31edb3e5fb7
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_CPU_ABI_INCOMPATIBLE;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
47import static android.content.pm.PackageParser.isApkFile;
48import static android.os.Process.PACKAGE_INFO_GID;
49import static android.os.Process.SYSTEM_UID;
50import static android.system.OsConstants.O_CREAT;
51import static android.system.OsConstants.O_RDWR;
52import static android.system.OsConstants.S_IRGRP;
53import static android.system.OsConstants.S_IROTH;
54import static android.system.OsConstants.S_IRWXU;
55import static android.system.OsConstants.S_IXGRP;
56import static android.system.OsConstants.S_IXOTH;
57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
58import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
59import static com.android.internal.util.ArrayUtils.appendInt;
60import static com.android.internal.util.ArrayUtils.removeInt;
61
62import android.util.ArrayMap;
63
64import com.android.internal.R;
65import com.android.internal.app.IMediaContainerService;
66import com.android.internal.app.ResolverActivity;
67import com.android.internal.content.NativeLibraryHelper;
68import com.android.internal.content.PackageHelper;
69import com.android.internal.os.IParcelFileDescriptorFactory;
70import com.android.internal.util.ArrayUtils;
71import com.android.internal.util.FastPrintWriter;
72import com.android.internal.util.FastXmlSerializer;
73import com.android.internal.util.IndentingPrintWriter;
74import com.android.internal.util.Preconditions;
75import com.android.server.EventLogTags;
76import com.android.server.IntentResolver;
77import com.android.server.LocalServices;
78import com.android.server.ServiceThread;
79import com.android.server.SystemConfig;
80import com.android.server.Watchdog;
81import com.android.server.pm.Settings.DatabaseVersion;
82import com.android.server.storage.DeviceStorageMonitorInternal;
83
84import org.xmlpull.v1.XmlSerializer;
85
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.IActivityManager;
89import android.app.admin.IDevicePolicyManager;
90import android.app.backup.IBackupManager;
91import android.content.BroadcastReceiver;
92import android.content.ComponentName;
93import android.content.Context;
94import android.content.IIntentReceiver;
95import android.content.Intent;
96import android.content.IntentFilter;
97import android.content.IntentSender;
98import android.content.IntentSender.SendIntentException;
99import android.content.ServiceConnection;
100import android.content.pm.ActivityInfo;
101import android.content.pm.ApplicationInfo;
102import android.content.pm.FeatureInfo;
103import android.content.pm.IPackageDataObserver;
104import android.content.pm.IPackageDeleteObserver;
105import android.content.pm.IPackageInstallObserver2;
106import android.content.pm.IPackageInstaller;
107import android.content.pm.IPackageManager;
108import android.content.pm.IPackageMoveObserver;
109import android.content.pm.IPackageStatsObserver;
110import android.content.pm.InstallSessionParams;
111import android.content.pm.InstrumentationInfo;
112import android.content.pm.ManifestDigest;
113import android.content.pm.PackageCleanItem;
114import android.content.pm.PackageInfo;
115import android.content.pm.PackageInfoLite;
116import android.content.pm.PackageManager;
117import android.content.pm.PackageParser.ActivityIntentInfo;
118import android.content.pm.PackageParser.PackageLite;
119import android.content.pm.PackageParser.PackageParserException;
120import android.content.pm.PackageParser;
121import android.content.pm.PackageStats;
122import android.content.pm.PackageUserState;
123import android.content.pm.ParceledListSlice;
124import android.content.pm.PermissionGroupInfo;
125import android.content.pm.PermissionInfo;
126import android.content.pm.ProviderInfo;
127import android.content.pm.ResolveInfo;
128import android.content.pm.ServiceInfo;
129import android.content.pm.Signature;
130import android.content.pm.UserInfo;
131import android.content.pm.VerificationParams;
132import android.content.pm.VerifierDeviceIdentity;
133import android.content.pm.VerifierInfo;
134import android.content.res.Resources;
135import android.hardware.display.DisplayManager;
136import android.net.Uri;
137import android.os.Binder;
138import android.os.Build;
139import android.os.Bundle;
140import android.os.Environment;
141import android.os.Environment.UserEnvironment;
142import android.os.FileObserver;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteException;
152import android.os.SELinux;
153import android.os.ServiceManager;
154import android.os.SystemClock;
155import android.os.SystemProperties;
156import android.os.UserHandle;
157import android.os.UserManager;
158import android.security.KeyStore;
159import android.security.SystemKeyStore;
160import android.system.ErrnoException;
161import android.system.Os;
162import android.system.StructStat;
163import android.text.TextUtils;
164import android.util.ArraySet;
165import android.util.AtomicFile;
166import android.util.DisplayMetrics;
167import android.util.EventLog;
168import android.util.ExceptionUtils;
169import android.util.Log;
170import android.util.LogPrinter;
171import android.util.PrintStreamPrinter;
172import android.util.Slog;
173import android.util.SparseArray;
174import android.util.SparseBooleanArray;
175import android.view.Display;
176
177import java.io.BufferedInputStream;
178import java.io.BufferedOutputStream;
179import java.io.File;
180import java.io.FileDescriptor;
181import java.io.FileInputStream;
182import java.io.FileNotFoundException;
183import java.io.FileOutputStream;
184import java.io.FilenameFilter;
185import java.io.IOException;
186import java.io.InputStream;
187import java.io.PrintWriter;
188import java.nio.charset.StandardCharsets;
189import java.security.NoSuchAlgorithmException;
190import java.security.PublicKey;
191import java.security.cert.CertificateEncodingException;
192import java.security.cert.CertificateException;
193import java.text.SimpleDateFormat;
194import java.util.ArrayList;
195import java.util.Arrays;
196import java.util.Collection;
197import java.util.Collections;
198import java.util.Comparator;
199import java.util.Date;
200import java.util.HashMap;
201import java.util.HashSet;
202import java.util.Iterator;
203import java.util.List;
204import java.util.Map;
205import java.util.Set;
206import java.util.concurrent.atomic.AtomicBoolean;
207import java.util.concurrent.atomic.AtomicLong;
208
209import dalvik.system.DexFile;
210import dalvik.system.StaleDexCacheError;
211import dalvik.system.VMRuntime;
212
213import libcore.io.IoUtils;
214
215/**
216 * Keep track of all those .apks everywhere.
217 *
218 * This is very central to the platform's security; please run the unit
219 * tests whenever making modifications here:
220 *
221mmm frameworks/base/tests/AndroidTests
222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
224 *
225 * {@hide}
226 */
227public class PackageManagerService extends IPackageManager.Stub {
228    static final String TAG = "PackageManager";
229    static final boolean DEBUG_SETTINGS = false;
230    static final boolean DEBUG_PREFERRED = false;
231    static final boolean DEBUG_UPGRADE = false;
232    private static final boolean DEBUG_INSTALL = false;
233    private static final boolean DEBUG_REMOVE = false;
234    private static final boolean DEBUG_BROADCASTS = false;
235    private static final boolean DEBUG_SHOW_INFO = false;
236    private static final boolean DEBUG_PACKAGE_INFO = false;
237    private static final boolean DEBUG_INTENT_MATCHING = false;
238    private static final boolean DEBUG_PACKAGE_SCANNING = false;
239    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
240    private static final boolean DEBUG_VERIFY = false;
241    private static final boolean DEBUG_DEXOPT = false;
242    private static final boolean DEBUG_ABI_SELECTION = false;
243
244    private static final int RADIO_UID = Process.PHONE_UID;
245    private static final int LOG_UID = Process.LOG_UID;
246    private static final int NFC_UID = Process.NFC_UID;
247    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
248    private static final int SHELL_UID = Process.SHELL_UID;
249
250    // Cap the size of permission trees that 3rd party apps can define
251    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
252
253    private static final int REMOVE_EVENTS =
254        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
255    private static final int ADD_EVENTS =
256        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
257
258    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
259    // Suffix used during package installation when copying/moving
260    // package apks to install directory.
261    private static final String INSTALL_PACKAGE_SUFFIX = "-";
262
263    static final int SCAN_MONITOR = 1<<0;
264    static final int SCAN_NO_DEX = 1<<1;
265    static final int SCAN_FORCE_DEX = 1<<2;
266    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
267    static final int SCAN_NEW_INSTALL = 1<<4;
268    static final int SCAN_NO_PATHS = 1<<5;
269    static final int SCAN_UPDATE_TIME = 1<<6;
270    static final int SCAN_DEFER_DEX = 1<<7;
271    static final int SCAN_BOOTING = 1<<8;
272    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
273    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
274
275    static final int REMOVE_CHATTY = 1<<16;
276
277    /**
278     * Timeout (in milliseconds) after which the watchdog should declare that
279     * our handler thread is wedged.  The usual default for such things is one
280     * minute but we sometimes do very lengthy I/O operations on this thread,
281     * such as installing multi-gigabyte applications, so ours needs to be longer.
282     */
283    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
284
285    /**
286     * Whether verification is enabled by default.
287     */
288    private static final boolean DEFAULT_VERIFY_ENABLE = true;
289
290    /**
291     * The default maximum time to wait for the verification agent to return in
292     * milliseconds.
293     */
294    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
295
296    /**
297     * The default response for package verification timeout.
298     *
299     * This can be either PackageManager.VERIFICATION_ALLOW or
300     * PackageManager.VERIFICATION_REJECT.
301     */
302    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
303
304    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
305
306    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
307            DEFAULT_CONTAINER_PACKAGE,
308            "com.android.defcontainer.DefaultContainerService");
309
310    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
311
312    private static final String LIB_DIR_NAME = "lib";
313    private static final String LIB64_DIR_NAME = "lib64";
314
315    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
316
317    static final String mTempContainerPrefix = "smdl2tmp";
318
319    private static String sPreferredInstructionSet;
320
321    final ServiceThread mHandlerThread;
322
323    private static final String IDMAP_PREFIX = "/data/resource-cache/";
324    private static final String IDMAP_SUFFIX = "@idmap";
325
326    final PackageHandler mHandler;
327
328    final int mSdkVersion = Build.VERSION.SDK_INT;
329
330    final Context mContext;
331    final boolean mFactoryTest;
332    final boolean mOnlyCore;
333    final DisplayMetrics mMetrics;
334    final int mDefParseFlags;
335    final String[] mSeparateProcesses;
336
337    // This is where all application persistent data goes.
338    final File mAppDataDir;
339
340    // This is where all application persistent data goes for secondary users.
341    final File mUserAppDataDir;
342
343    /** The location for ASEC container files on internal storage. */
344    final String mAsecInternalPath;
345
346    // This is the object monitoring the framework dir.
347    final FileObserver mFrameworkInstallObserver;
348
349    // This is the object monitoring the system app dir.
350    final FileObserver mSystemInstallObserver;
351
352    // This is the object monitoring the privileged system app dir.
353    final FileObserver mPrivilegedInstallObserver;
354
355    // This is the object monitoring the vendor app dir.
356    final FileObserver mVendorInstallObserver;
357
358    // This is the object monitoring the vendor overlay package dir.
359    final FileObserver mVendorOverlayInstallObserver;
360
361    // This is the object monitoring the OEM app dir.
362    final FileObserver mOemInstallObserver;
363
364    // This is the object monitoring mAppInstallDir.
365    final FileObserver mAppInstallObserver;
366
367    // This is the object monitoring mDrmAppPrivateInstallDir.
368    final FileObserver mDrmAppInstallObserver;
369
370    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
371    // LOCK HELD.  Can be called with mInstallLock held.
372    final Installer mInstaller;
373
374    /** Directory where installed third-party apps stored */
375    final File mAppInstallDir;
376
377    /**
378     * Directory to which applications installed internally have their
379     * 32 bit native libraries copied.
380     */
381    private File mAppLib32InstallDir;
382
383    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
384    // apps.
385    final File mDrmAppPrivateInstallDir;
386
387    // ----------------------------------------------------------------
388
389    // Lock for state used when installing and doing other long running
390    // operations.  Methods that must be called with this lock held have
391    // the suffix "LI".
392    final Object mInstallLock = new Object();
393
394    // These are the directories in the 3rd party applications installed dir
395    // that we have currently loaded packages from.  Keys are the application's
396    // installed zip file (absolute codePath), and values are Package.
397    final HashMap<String, PackageParser.Package> mAppDirs =
398            new HashMap<String, PackageParser.Package>();
399
400    // ----------------------------------------------------------------
401
402    // Keys are String (package name), values are Package.  This also serves
403    // as the lock for the global state.  Methods that must be called with
404    // this lock held have the prefix "LP".
405    final HashMap<String, PackageParser.Package> mPackages =
406            new HashMap<String, PackageParser.Package>();
407
408    // Tracks available target package names -> overlay package paths.
409    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
410        new HashMap<String, HashMap<String, PackageParser.Package>>();
411
412    final Settings mSettings;
413    boolean mRestoredSettings;
414
415    // System configuration read by SystemConfig.
416    final int[] mGlobalGids;
417    final SparseArray<HashSet<String>> mSystemPermissions;
418    final HashMap<String, FeatureInfo> mAvailableFeatures;
419
420    // If mac_permissions.xml was found for seinfo labeling.
421    boolean mFoundPolicyFile;
422
423    // If a recursive restorecon of /data/data/<pkg> is needed.
424    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
425
426    public static final class SharedLibraryEntry {
427        public final String path;
428        public final String apk;
429
430        SharedLibraryEntry(String _path, String _apk) {
431            path = _path;
432            apk = _apk;
433        }
434    }
435
436    // Currently known shared libraries.
437    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
438            new HashMap<String, SharedLibraryEntry>();
439
440    // All available activities, for your resolving pleasure.
441    final ActivityIntentResolver mActivities =
442            new ActivityIntentResolver();
443
444    // All available receivers, for your resolving pleasure.
445    final ActivityIntentResolver mReceivers =
446            new ActivityIntentResolver();
447
448    // All available services, for your resolving pleasure.
449    final ServiceIntentResolver mServices = new ServiceIntentResolver();
450
451    // All available providers, for your resolving pleasure.
452    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
453
454    // Mapping from provider base names (first directory in content URI codePath)
455    // to the provider information.
456    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
457            new HashMap<String, PackageParser.Provider>();
458
459    // Mapping from instrumentation class names to info about them.
460    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
461            new HashMap<ComponentName, PackageParser.Instrumentation>();
462
463    // Mapping from permission names to info about them.
464    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
465            new HashMap<String, PackageParser.PermissionGroup>();
466
467    // Packages whose data we have transfered into another package, thus
468    // should no longer exist.
469    final HashSet<String> mTransferedPackages = new HashSet<String>();
470
471    // Broadcast actions that are only available to the system.
472    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
473
474    /** List of packages waiting for verification. */
475    final SparseArray<PackageVerificationState> mPendingVerification
476            = new SparseArray<PackageVerificationState>();
477
478    final PackageInstallerService mInstallerService;
479
480    HashSet<PackageParser.Package> mDeferredDexOpt = null;
481
482    // Cache of users who need badging.
483    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
484
485    /** Token for keys in mPendingVerification. */
486    private int mPendingVerificationToken = 0;
487
488    boolean mSystemReady;
489    boolean mSafeMode;
490    boolean mHasSystemUidErrors;
491
492    ApplicationInfo mAndroidApplication;
493    final ActivityInfo mResolveActivity = new ActivityInfo();
494    final ResolveInfo mResolveInfo = new ResolveInfo();
495    ComponentName mResolveComponentName;
496    PackageParser.Package mPlatformPackage;
497    ComponentName mCustomResolverComponentName;
498
499    boolean mResolverReplaced = false;
500
501    // Set of pending broadcasts for aggregating enable/disable of components.
502    static class PendingPackageBroadcasts {
503        // for each user id, a map of <package name -> components within that package>
504        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
505
506        public PendingPackageBroadcasts() {
507            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
508        }
509
510        public ArrayList<String> get(int userId, String packageName) {
511            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
512            return packages.get(packageName);
513        }
514
515        public void put(int userId, String packageName, ArrayList<String> components) {
516            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
517            packages.put(packageName, components);
518        }
519
520        public void remove(int userId, String packageName) {
521            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
522            if (packages != null) {
523                packages.remove(packageName);
524            }
525        }
526
527        public void remove(int userId) {
528            mUidMap.remove(userId);
529        }
530
531        public int userIdCount() {
532            return mUidMap.size();
533        }
534
535        public int userIdAt(int n) {
536            return mUidMap.keyAt(n);
537        }
538
539        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
540            return mUidMap.get(userId);
541        }
542
543        public int size() {
544            // total number of pending broadcast entries across all userIds
545            int num = 0;
546            for (int i = 0; i< mUidMap.size(); i++) {
547                num += mUidMap.valueAt(i).size();
548            }
549            return num;
550        }
551
552        public void clear() {
553            mUidMap.clear();
554        }
555
556        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
557            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
558            if (map == null) {
559                map = new HashMap<String, ArrayList<String>>();
560                mUidMap.put(userId, map);
561            }
562            return map;
563        }
564    }
565    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
566
567    // Service Connection to remote media container service to copy
568    // package uri's from external media onto secure containers
569    // or internal storage.
570    private IMediaContainerService mContainerService = null;
571
572    static final int SEND_PENDING_BROADCAST = 1;
573    static final int MCS_BOUND = 3;
574    static final int END_COPY = 4;
575    static final int INIT_COPY = 5;
576    static final int MCS_UNBIND = 6;
577    static final int START_CLEANING_PACKAGE = 7;
578    static final int FIND_INSTALL_LOC = 8;
579    static final int POST_INSTALL = 9;
580    static final int MCS_RECONNECT = 10;
581    static final int MCS_GIVE_UP = 11;
582    static final int UPDATED_MEDIA_STATUS = 12;
583    static final int WRITE_SETTINGS = 13;
584    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
585    static final int PACKAGE_VERIFIED = 15;
586    static final int CHECK_PENDING_VERIFICATION = 16;
587
588    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
589
590    // Delay time in millisecs
591    static final int BROADCAST_DELAY = 10 * 1000;
592
593    static UserManagerService sUserManager;
594
595    // Stores a list of users whose package restrictions file needs to be updated
596    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
597
598    final private DefaultContainerConnection mDefContainerConn =
599            new DefaultContainerConnection();
600    class DefaultContainerConnection implements ServiceConnection {
601        public void onServiceConnected(ComponentName name, IBinder service) {
602            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
603            IMediaContainerService imcs =
604                IMediaContainerService.Stub.asInterface(service);
605            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
606        }
607
608        public void onServiceDisconnected(ComponentName name) {
609            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
610        }
611    };
612
613    // Recordkeeping of restore-after-install operations that are currently in flight
614    // between the Package Manager and the Backup Manager
615    class PostInstallData {
616        public InstallArgs args;
617        public PackageInstalledInfo res;
618
619        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
620            args = _a;
621            res = _r;
622        }
623    };
624    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
625    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
626
627    private final String mRequiredVerifierPackage;
628
629    private final PackageUsage mPackageUsage = new PackageUsage();
630
631    private class PackageUsage {
632        private static final int WRITE_INTERVAL
633            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
634
635        private final Object mFileLock = new Object();
636        private final AtomicLong mLastWritten = new AtomicLong(0);
637        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
638
639        private boolean mIsHistoricalPackageUsageAvailable = true;
640
641        boolean isHistoricalPackageUsageAvailable() {
642            return mIsHistoricalPackageUsageAvailable;
643        }
644
645        void write(boolean force) {
646            if (force) {
647                writeInternal();
648                return;
649            }
650            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
651                && !DEBUG_DEXOPT) {
652                return;
653            }
654            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
655                new Thread("PackageUsage_DiskWriter") {
656                    @Override
657                    public void run() {
658                        try {
659                            writeInternal();
660                        } finally {
661                            mBackgroundWriteRunning.set(false);
662                        }
663                    }
664                }.start();
665            }
666        }
667
668        private void writeInternal() {
669            synchronized (mPackages) {
670                synchronized (mFileLock) {
671                    AtomicFile file = getFile();
672                    FileOutputStream f = null;
673                    try {
674                        f = file.startWrite();
675                        BufferedOutputStream out = new BufferedOutputStream(f);
676                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
677                        StringBuilder sb = new StringBuilder();
678                        for (PackageParser.Package pkg : mPackages.values()) {
679                            if (pkg.mLastPackageUsageTimeInMills == 0) {
680                                continue;
681                            }
682                            sb.setLength(0);
683                            sb.append(pkg.packageName);
684                            sb.append(' ');
685                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
686                            sb.append('\n');
687                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
688                        }
689                        out.flush();
690                        file.finishWrite(f);
691                    } catch (IOException e) {
692                        if (f != null) {
693                            file.failWrite(f);
694                        }
695                        Log.e(TAG, "Failed to write package usage times", e);
696                    }
697                }
698            }
699            mLastWritten.set(SystemClock.elapsedRealtime());
700        }
701
702        void readLP() {
703            synchronized (mFileLock) {
704                AtomicFile file = getFile();
705                BufferedInputStream in = null;
706                try {
707                    in = new BufferedInputStream(file.openRead());
708                    StringBuffer sb = new StringBuffer();
709                    while (true) {
710                        String packageName = readToken(in, sb, ' ');
711                        if (packageName == null) {
712                            break;
713                        }
714                        String timeInMillisString = readToken(in, sb, '\n');
715                        if (timeInMillisString == null) {
716                            throw new IOException("Failed to find last usage time for package "
717                                                  + packageName);
718                        }
719                        PackageParser.Package pkg = mPackages.get(packageName);
720                        if (pkg == null) {
721                            continue;
722                        }
723                        long timeInMillis;
724                        try {
725                            timeInMillis = Long.parseLong(timeInMillisString.toString());
726                        } catch (NumberFormatException e) {
727                            throw new IOException("Failed to parse " + timeInMillisString
728                                                  + " as a long.", e);
729                        }
730                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
731                    }
732                } catch (FileNotFoundException expected) {
733                    mIsHistoricalPackageUsageAvailable = false;
734                } catch (IOException e) {
735                    Log.w(TAG, "Failed to read package usage times", e);
736                } finally {
737                    IoUtils.closeQuietly(in);
738                }
739            }
740            mLastWritten.set(SystemClock.elapsedRealtime());
741        }
742
743        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
744                throws IOException {
745            sb.setLength(0);
746            while (true) {
747                int ch = in.read();
748                if (ch == -1) {
749                    if (sb.length() == 0) {
750                        return null;
751                    }
752                    throw new IOException("Unexpected EOF");
753                }
754                if (ch == endOfToken) {
755                    return sb.toString();
756                }
757                sb.append((char)ch);
758            }
759        }
760
761        private AtomicFile getFile() {
762            File dataDir = Environment.getDataDirectory();
763            File systemDir = new File(dataDir, "system");
764            File fname = new File(systemDir, "package-usage.list");
765            return new AtomicFile(fname);
766        }
767    }
768
769    class PackageHandler extends Handler {
770        private boolean mBound = false;
771        final ArrayList<HandlerParams> mPendingInstalls =
772            new ArrayList<HandlerParams>();
773
774        private boolean connectToService() {
775            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
776                    " DefaultContainerService");
777            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
778            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
779            if (mContext.bindServiceAsUser(service, mDefContainerConn,
780                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
781                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
782                mBound = true;
783                return true;
784            }
785            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
786            return false;
787        }
788
789        private void disconnectService() {
790            mContainerService = null;
791            mBound = false;
792            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
793            mContext.unbindService(mDefContainerConn);
794            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
795        }
796
797        PackageHandler(Looper looper) {
798            super(looper);
799        }
800
801        public void handleMessage(Message msg) {
802            try {
803                doHandleMessage(msg);
804            } finally {
805                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
806            }
807        }
808
809        void doHandleMessage(Message msg) {
810            switch (msg.what) {
811                case INIT_COPY: {
812                    HandlerParams params = (HandlerParams) msg.obj;
813                    int idx = mPendingInstalls.size();
814                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
815                    // If a bind was already initiated we dont really
816                    // need to do anything. The pending install
817                    // will be processed later on.
818                    if (!mBound) {
819                        // If this is the only one pending we might
820                        // have to bind to the service again.
821                        if (!connectToService()) {
822                            Slog.e(TAG, "Failed to bind to media container service");
823                            params.serviceError();
824                            return;
825                        } else {
826                            // Once we bind to the service, the first
827                            // pending request will be processed.
828                            mPendingInstalls.add(idx, params);
829                        }
830                    } else {
831                        mPendingInstalls.add(idx, params);
832                        // Already bound to the service. Just make
833                        // sure we trigger off processing the first request.
834                        if (idx == 0) {
835                            mHandler.sendEmptyMessage(MCS_BOUND);
836                        }
837                    }
838                    break;
839                }
840                case MCS_BOUND: {
841                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
842                    if (msg.obj != null) {
843                        mContainerService = (IMediaContainerService) msg.obj;
844                    }
845                    if (mContainerService == null) {
846                        // Something seriously wrong. Bail out
847                        Slog.e(TAG, "Cannot bind to media container service");
848                        for (HandlerParams params : mPendingInstalls) {
849                            // Indicate service bind error
850                            params.serviceError();
851                        }
852                        mPendingInstalls.clear();
853                    } else if (mPendingInstalls.size() > 0) {
854                        HandlerParams params = mPendingInstalls.get(0);
855                        if (params != null) {
856                            if (params.startCopy()) {
857                                // We are done...  look for more work or to
858                                // go idle.
859                                if (DEBUG_SD_INSTALL) Log.i(TAG,
860                                        "Checking for more work or unbind...");
861                                // Delete pending install
862                                if (mPendingInstalls.size() > 0) {
863                                    mPendingInstalls.remove(0);
864                                }
865                                if (mPendingInstalls.size() == 0) {
866                                    if (mBound) {
867                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
868                                                "Posting delayed MCS_UNBIND");
869                                        removeMessages(MCS_UNBIND);
870                                        Message ubmsg = obtainMessage(MCS_UNBIND);
871                                        // Unbind after a little delay, to avoid
872                                        // continual thrashing.
873                                        sendMessageDelayed(ubmsg, 10000);
874                                    }
875                                } else {
876                                    // There are more pending requests in queue.
877                                    // Just post MCS_BOUND message to trigger processing
878                                    // of next pending install.
879                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
880                                            "Posting MCS_BOUND for next work");
881                                    mHandler.sendEmptyMessage(MCS_BOUND);
882                                }
883                            }
884                        }
885                    } else {
886                        // Should never happen ideally.
887                        Slog.w(TAG, "Empty queue");
888                    }
889                    break;
890                }
891                case MCS_RECONNECT: {
892                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
893                    if (mPendingInstalls.size() > 0) {
894                        if (mBound) {
895                            disconnectService();
896                        }
897                        if (!connectToService()) {
898                            Slog.e(TAG, "Failed to bind to media container service");
899                            for (HandlerParams params : mPendingInstalls) {
900                                // Indicate service bind error
901                                params.serviceError();
902                            }
903                            mPendingInstalls.clear();
904                        }
905                    }
906                    break;
907                }
908                case MCS_UNBIND: {
909                    // If there is no actual work left, then time to unbind.
910                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
911
912                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
913                        if (mBound) {
914                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
915
916                            disconnectService();
917                        }
918                    } else if (mPendingInstalls.size() > 0) {
919                        // There are more pending requests in queue.
920                        // Just post MCS_BOUND message to trigger processing
921                        // of next pending install.
922                        mHandler.sendEmptyMessage(MCS_BOUND);
923                    }
924
925                    break;
926                }
927                case MCS_GIVE_UP: {
928                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
929                    mPendingInstalls.remove(0);
930                    break;
931                }
932                case SEND_PENDING_BROADCAST: {
933                    String packages[];
934                    ArrayList<String> components[];
935                    int size = 0;
936                    int uids[];
937                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
938                    synchronized (mPackages) {
939                        if (mPendingBroadcasts == null) {
940                            return;
941                        }
942                        size = mPendingBroadcasts.size();
943                        if (size <= 0) {
944                            // Nothing to be done. Just return
945                            return;
946                        }
947                        packages = new String[size];
948                        components = new ArrayList[size];
949                        uids = new int[size];
950                        int i = 0;  // filling out the above arrays
951
952                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
953                            int packageUserId = mPendingBroadcasts.userIdAt(n);
954                            Iterator<Map.Entry<String, ArrayList<String>>> it
955                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
956                                            .entrySet().iterator();
957                            while (it.hasNext() && i < size) {
958                                Map.Entry<String, ArrayList<String>> ent = it.next();
959                                packages[i] = ent.getKey();
960                                components[i] = ent.getValue();
961                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
962                                uids[i] = (ps != null)
963                                        ? UserHandle.getUid(packageUserId, ps.appId)
964                                        : -1;
965                                i++;
966                            }
967                        }
968                        size = i;
969                        mPendingBroadcasts.clear();
970                    }
971                    // Send broadcasts
972                    for (int i = 0; i < size; i++) {
973                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
974                    }
975                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
976                    break;
977                }
978                case START_CLEANING_PACKAGE: {
979                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
980                    final String packageName = (String)msg.obj;
981                    final int userId = msg.arg1;
982                    final boolean andCode = msg.arg2 != 0;
983                    synchronized (mPackages) {
984                        if (userId == UserHandle.USER_ALL) {
985                            int[] users = sUserManager.getUserIds();
986                            for (int user : users) {
987                                mSettings.addPackageToCleanLPw(
988                                        new PackageCleanItem(user, packageName, andCode));
989                            }
990                        } else {
991                            mSettings.addPackageToCleanLPw(
992                                    new PackageCleanItem(userId, packageName, andCode));
993                        }
994                    }
995                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
996                    startCleaningPackages();
997                } break;
998                case POST_INSTALL: {
999                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1000                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1001                    mRunningInstalls.delete(msg.arg1);
1002                    boolean deleteOld = false;
1003
1004                    if (data != null) {
1005                        InstallArgs args = data.args;
1006                        PackageInstalledInfo res = data.res;
1007
1008                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1009                            res.removedInfo.sendBroadcast(false, true, false);
1010                            Bundle extras = new Bundle(1);
1011                            extras.putInt(Intent.EXTRA_UID, res.uid);
1012                            // Determine the set of users who are adding this
1013                            // package for the first time vs. those who are seeing
1014                            // an update.
1015                            int[] firstUsers;
1016                            int[] updateUsers = new int[0];
1017                            if (res.origUsers == null || res.origUsers.length == 0) {
1018                                firstUsers = res.newUsers;
1019                            } else {
1020                                firstUsers = new int[0];
1021                                for (int i=0; i<res.newUsers.length; i++) {
1022                                    int user = res.newUsers[i];
1023                                    boolean isNew = true;
1024                                    for (int j=0; j<res.origUsers.length; j++) {
1025                                        if (res.origUsers[j] == user) {
1026                                            isNew = false;
1027                                            break;
1028                                        }
1029                                    }
1030                                    if (isNew) {
1031                                        int[] newFirst = new int[firstUsers.length+1];
1032                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1033                                                firstUsers.length);
1034                                        newFirst[firstUsers.length] = user;
1035                                        firstUsers = newFirst;
1036                                    } else {
1037                                        int[] newUpdate = new int[updateUsers.length+1];
1038                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1039                                                updateUsers.length);
1040                                        newUpdate[updateUsers.length] = user;
1041                                        updateUsers = newUpdate;
1042                                    }
1043                                }
1044                            }
1045                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1046                                    res.pkg.applicationInfo.packageName,
1047                                    extras, null, null, firstUsers);
1048                            final boolean update = res.removedInfo.removedPackage != null;
1049                            if (update) {
1050                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1051                            }
1052                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1053                                    res.pkg.applicationInfo.packageName,
1054                                    extras, null, null, updateUsers);
1055                            if (update) {
1056                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1057                                        res.pkg.applicationInfo.packageName,
1058                                        extras, null, null, updateUsers);
1059                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1060                                        null, null,
1061                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1062
1063                                // treat asec-hosted packages like removable media on upgrade
1064                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1065                                    if (DEBUG_INSTALL) {
1066                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1067                                                + " is ASEC-hosted -> AVAILABLE");
1068                                    }
1069                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1070                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1071                                    pkgList.add(res.pkg.applicationInfo.packageName);
1072                                    sendResourcesChangedBroadcast(true, true,
1073                                            pkgList,uidArray, null);
1074                                }
1075                            }
1076                            if (res.removedInfo.args != null) {
1077                                // Remove the replaced package's older resources safely now
1078                                deleteOld = true;
1079                            }
1080
1081                            // Log current value of "unknown sources" setting
1082                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1083                                getUnknownSourcesSettings());
1084                        }
1085                        // Force a gc to clear up things
1086                        Runtime.getRuntime().gc();
1087                        // We delete after a gc for applications  on sdcard.
1088                        if (deleteOld) {
1089                            synchronized (mInstallLock) {
1090                                res.removedInfo.args.doPostDeleteLI(true);
1091                            }
1092                        }
1093                        if (args.observer != null) {
1094                            try {
1095                                Bundle extras = extrasForInstallResult(res);
1096                                args.observer.packageInstalled(res.name, extras, res.returnCode,
1097                                        res.returnMsg);
1098                            } catch (RemoteException e) {
1099                                Slog.i(TAG, "Observer no longer exists.");
1100                            }
1101                        }
1102                    } else {
1103                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1104                    }
1105                } break;
1106                case UPDATED_MEDIA_STATUS: {
1107                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1108                    boolean reportStatus = msg.arg1 == 1;
1109                    boolean doGc = msg.arg2 == 1;
1110                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1111                    if (doGc) {
1112                        // Force a gc to clear up stale containers.
1113                        Runtime.getRuntime().gc();
1114                    }
1115                    if (msg.obj != null) {
1116                        @SuppressWarnings("unchecked")
1117                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1118                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1119                        // Unload containers
1120                        unloadAllContainers(args);
1121                    }
1122                    if (reportStatus) {
1123                        try {
1124                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1125                            PackageHelper.getMountService().finishMediaUpdate();
1126                        } catch (RemoteException e) {
1127                            Log.e(TAG, "MountService not running?");
1128                        }
1129                    }
1130                } break;
1131                case WRITE_SETTINGS: {
1132                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1133                    synchronized (mPackages) {
1134                        removeMessages(WRITE_SETTINGS);
1135                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1136                        mSettings.writeLPr();
1137                        mDirtyUsers.clear();
1138                    }
1139                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1140                } break;
1141                case WRITE_PACKAGE_RESTRICTIONS: {
1142                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1143                    synchronized (mPackages) {
1144                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1145                        for (int userId : mDirtyUsers) {
1146                            mSettings.writePackageRestrictionsLPr(userId);
1147                        }
1148                        mDirtyUsers.clear();
1149                    }
1150                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1151                } break;
1152                case CHECK_PENDING_VERIFICATION: {
1153                    final int verificationId = msg.arg1;
1154                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1155
1156                    if ((state != null) && !state.timeoutExtended()) {
1157                        final InstallArgs args = state.getInstallArgs();
1158                        final Uri originUri = Uri.fromFile(args.originFile);
1159
1160                        Slog.i(TAG, "Verification timed out for " + originUri);
1161                        mPendingVerification.remove(verificationId);
1162
1163                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1164
1165                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1166                            Slog.i(TAG, "Continuing with installation of " + originUri);
1167                            state.setVerifierResponse(Binder.getCallingUid(),
1168                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1169                            broadcastPackageVerified(verificationId, originUri,
1170                                    PackageManager.VERIFICATION_ALLOW,
1171                                    state.getInstallArgs().getUser());
1172                            try {
1173                                ret = args.copyApk(mContainerService, true);
1174                            } catch (RemoteException e) {
1175                                Slog.e(TAG, "Could not contact the ContainerService");
1176                            }
1177                        } else {
1178                            broadcastPackageVerified(verificationId, originUri,
1179                                    PackageManager.VERIFICATION_REJECT,
1180                                    state.getInstallArgs().getUser());
1181                        }
1182
1183                        processPendingInstall(args, ret);
1184                        mHandler.sendEmptyMessage(MCS_UNBIND);
1185                    }
1186                    break;
1187                }
1188                case PACKAGE_VERIFIED: {
1189                    final int verificationId = msg.arg1;
1190
1191                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1192                    if (state == null) {
1193                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1194                        break;
1195                    }
1196
1197                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1198
1199                    state.setVerifierResponse(response.callerUid, response.code);
1200
1201                    if (state.isVerificationComplete()) {
1202                        mPendingVerification.remove(verificationId);
1203
1204                        final InstallArgs args = state.getInstallArgs();
1205                        final Uri originUri = Uri.fromFile(args.originFile);
1206
1207                        int ret;
1208                        if (state.isInstallAllowed()) {
1209                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1210                            broadcastPackageVerified(verificationId, originUri,
1211                                    response.code, state.getInstallArgs().getUser());
1212                            try {
1213                                ret = args.copyApk(mContainerService, true);
1214                            } catch (RemoteException e) {
1215                                Slog.e(TAG, "Could not contact the ContainerService");
1216                            }
1217                        } else {
1218                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1219                        }
1220
1221                        processPendingInstall(args, ret);
1222
1223                        mHandler.sendEmptyMessage(MCS_UNBIND);
1224                    }
1225
1226                    break;
1227                }
1228            }
1229        }
1230    }
1231
1232    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1233        Bundle extras = null;
1234        switch (res.returnCode) {
1235            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1236                extras = new Bundle();
1237                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1238                        res.origPermission);
1239                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1240                        res.origPackage);
1241                break;
1242            }
1243        }
1244        return extras;
1245    }
1246
1247    void scheduleWriteSettingsLocked() {
1248        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1249            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1250        }
1251    }
1252
1253    void scheduleWritePackageRestrictionsLocked(int userId) {
1254        if (!sUserManager.exists(userId)) return;
1255        mDirtyUsers.add(userId);
1256        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1257            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1258        }
1259    }
1260
1261    public static final PackageManagerService main(Context context, Installer installer,
1262            boolean factoryTest, boolean onlyCore) {
1263        PackageManagerService m = new PackageManagerService(context, installer,
1264                factoryTest, onlyCore);
1265        ServiceManager.addService("package", m);
1266        return m;
1267    }
1268
1269    static String[] splitString(String str, char sep) {
1270        int count = 1;
1271        int i = 0;
1272        while ((i=str.indexOf(sep, i)) >= 0) {
1273            count++;
1274            i++;
1275        }
1276
1277        String[] res = new String[count];
1278        i=0;
1279        count = 0;
1280        int lastI=0;
1281        while ((i=str.indexOf(sep, i)) >= 0) {
1282            res[count] = str.substring(lastI, i);
1283            count++;
1284            i++;
1285            lastI = i;
1286        }
1287        res[count] = str.substring(lastI, str.length());
1288        return res;
1289    }
1290
1291    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1292        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1293                Context.DISPLAY_SERVICE);
1294        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1295    }
1296
1297    public PackageManagerService(Context context, Installer installer,
1298            boolean factoryTest, boolean onlyCore) {
1299        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1300                SystemClock.uptimeMillis());
1301
1302        if (mSdkVersion <= 0) {
1303            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1304        }
1305
1306        mContext = context;
1307        mFactoryTest = factoryTest;
1308        mOnlyCore = onlyCore;
1309        mMetrics = new DisplayMetrics();
1310        mSettings = new Settings(context);
1311        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1312                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1313        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1314                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1315        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1316                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1317        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1318                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1319        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1320                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1321        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1322                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1323
1324        String separateProcesses = SystemProperties.get("debug.separate_processes");
1325        if (separateProcesses != null && separateProcesses.length() > 0) {
1326            if ("*".equals(separateProcesses)) {
1327                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1328                mSeparateProcesses = null;
1329                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1330            } else {
1331                mDefParseFlags = 0;
1332                mSeparateProcesses = separateProcesses.split(",");
1333                Slog.w(TAG, "Running with debug.separate_processes: "
1334                        + separateProcesses);
1335            }
1336        } else {
1337            mDefParseFlags = 0;
1338            mSeparateProcesses = null;
1339        }
1340
1341        mInstaller = installer;
1342
1343        getDefaultDisplayMetrics(context, mMetrics);
1344
1345        SystemConfig systemConfig = SystemConfig.getInstance();
1346        mGlobalGids = systemConfig.getGlobalGids();
1347        mSystemPermissions = systemConfig.getSystemPermissions();
1348        mAvailableFeatures = systemConfig.getAvailableFeatures();
1349
1350        synchronized (mInstallLock) {
1351        // writer
1352        synchronized (mPackages) {
1353            mHandlerThread = new ServiceThread(TAG,
1354                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1355            mHandlerThread.start();
1356            mHandler = new PackageHandler(mHandlerThread.getLooper());
1357            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1358
1359            File dataDir = Environment.getDataDirectory();
1360            mAppDataDir = new File(dataDir, "data");
1361            mAppInstallDir = new File(dataDir, "app");
1362            mAppLib32InstallDir = new File(dataDir, "app-lib");
1363            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1364            mUserAppDataDir = new File(dataDir, "user");
1365            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1366
1367            sUserManager = new UserManagerService(context, this,
1368                    mInstallLock, mPackages);
1369
1370            // Propagate permission configuration in to package manager.
1371            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1372                    = systemConfig.getPermissions();
1373            for (int i=0; i<permConfig.size(); i++) {
1374                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1375                BasePermission bp = mSettings.mPermissions.get(perm.name);
1376                if (bp == null) {
1377                    bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN);
1378                    mSettings.mPermissions.put(perm.name, bp);
1379                }
1380                if (perm.gids != null) {
1381                    bp.gids = appendInts(bp.gids, perm.gids);
1382                }
1383            }
1384
1385            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1386            for (int i=0; i<libConfig.size(); i++) {
1387                mSharedLibraries.put(libConfig.keyAt(i),
1388                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1389            }
1390
1391            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1392
1393            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1394                    mSdkVersion, mOnlyCore);
1395
1396            String customResolverActivity = Resources.getSystem().getString(
1397                    R.string.config_customResolverActivity);
1398            if (TextUtils.isEmpty(customResolverActivity)) {
1399                customResolverActivity = null;
1400            } else {
1401                mCustomResolverComponentName = ComponentName.unflattenFromString(
1402                        customResolverActivity);
1403            }
1404
1405            long startTime = SystemClock.uptimeMillis();
1406
1407            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1408                    startTime);
1409
1410            // Set flag to monitor and not change apk file paths when
1411            // scanning install directories.
1412            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1413
1414            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1415
1416            /**
1417             * Add everything in the in the boot class path to the
1418             * list of process files because dexopt will have been run
1419             * if necessary during zygote startup.
1420             */
1421            String bootClassPath = System.getProperty("java.boot.class.path");
1422            if (bootClassPath != null) {
1423                String[] paths = splitString(bootClassPath, ':');
1424                for (int i=0; i<paths.length; i++) {
1425                    alreadyDexOpted.add(paths[i]);
1426                }
1427            } else {
1428                Slog.w(TAG, "No BOOTCLASSPATH found!");
1429            }
1430
1431            boolean didDexOptLibraryOrTool = false;
1432
1433            final List<String> instructionSets = getAllInstructionSets();
1434
1435            /**
1436             * Ensure all external libraries have had dexopt run on them.
1437             */
1438            if (mSharedLibraries.size() > 0) {
1439                // NOTE: For now, we're compiling these system "shared libraries"
1440                // (and framework jars) into all available architectures. It's possible
1441                // to compile them only when we come across an app that uses them (there's
1442                // already logic for that in scanPackageLI) but that adds some complexity.
1443                for (String instructionSet : instructionSets) {
1444                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1445                        final String lib = libEntry.path;
1446                        if (lib == null) {
1447                            continue;
1448                        }
1449
1450                        try {
1451                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1452                                alreadyDexOpted.add(lib);
1453
1454                                // The list of "shared libraries" we have at this point is
1455                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1456                                didDexOptLibraryOrTool = true;
1457                            }
1458                        } catch (FileNotFoundException e) {
1459                            Slog.w(TAG, "Library not found: " + lib);
1460                        } catch (IOException e) {
1461                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1462                                    + e.getMessage());
1463                        }
1464                    }
1465                }
1466            }
1467
1468            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1469
1470            // Gross hack for now: we know this file doesn't contain any
1471            // code, so don't dexopt it to avoid the resulting log spew.
1472            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1473
1474            // Gross hack for now: we know this file is only part of
1475            // the boot class path for art, so don't dexopt it to
1476            // avoid the resulting log spew.
1477            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1478
1479            /**
1480             * And there are a number of commands implemented in Java, which
1481             * we currently need to do the dexopt on so that they can be
1482             * run from a non-root shell.
1483             */
1484            String[] frameworkFiles = frameworkDir.list();
1485            if (frameworkFiles != null) {
1486                // TODO: We could compile these only for the most preferred ABI. We should
1487                // first double check that the dex files for these commands are not referenced
1488                // by other system apps.
1489                for (String instructionSet : instructionSets) {
1490                    for (int i=0; i<frameworkFiles.length; i++) {
1491                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1492                        String path = libPath.getPath();
1493                        // Skip the file if we already did it.
1494                        if (alreadyDexOpted.contains(path)) {
1495                            continue;
1496                        }
1497                        // Skip the file if it is not a type we want to dexopt.
1498                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1499                            continue;
1500                        }
1501                        try {
1502                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1503                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1504                                didDexOptLibraryOrTool = true;
1505                            }
1506                        } catch (FileNotFoundException e) {
1507                            Slog.w(TAG, "Jar not found: " + path);
1508                        } catch (IOException e) {
1509                            Slog.w(TAG, "Exception reading jar: " + path, e);
1510                        }
1511                    }
1512                }
1513            }
1514
1515            if (didDexOptLibraryOrTool) {
1516                // If we dexopted a library or tool, then something on the system has
1517                // changed. Consider this significant, and wipe away all other
1518                // existing dexopt files to ensure we don't leave any dangling around.
1519                //
1520                // TODO: This should be revisited because it isn't as good an indicator
1521                // as it used to be. It used to include the boot classpath but at some point
1522                // DexFile.isDexOptNeeded started returning false for the boot
1523                // class path files in all cases. It is very possible in a
1524                // small maintenance release update that the library and tool
1525                // jars may be unchanged but APK could be removed resulting in
1526                // unused dalvik-cache files.
1527                for (String instructionSet : instructionSets) {
1528                    mInstaller.pruneDexCache(instructionSet);
1529                }
1530
1531                // Additionally, delete all dex files from the root directory
1532                // since there shouldn't be any there anyway, unless we're upgrading
1533                // from an older OS version or a build that contained the "old" style
1534                // flat scheme.
1535                mInstaller.pruneDexCache(".");
1536            }
1537
1538            // Collect vendor overlay packages.
1539            // (Do this before scanning any apps.)
1540            // For security and version matching reason, only consider
1541            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1542            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1543            mVendorOverlayInstallObserver = new AppDirObserver(
1544                    vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1545            mVendorOverlayInstallObserver.startWatching();
1546            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1547                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1548
1549            // Find base frameworks (resource packages without code).
1550            mFrameworkInstallObserver = new AppDirObserver(
1551                    frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1552            mFrameworkInstallObserver.startWatching();
1553            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1554                    | PackageParser.PARSE_IS_SYSTEM_DIR
1555                    | PackageParser.PARSE_IS_PRIVILEGED,
1556                    scanMode | SCAN_NO_DEX, 0);
1557
1558            // Collected privileged system packages.
1559            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1560            mPrivilegedInstallObserver = new AppDirObserver(
1561                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1562            mPrivilegedInstallObserver.startWatching();
1563            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1564                    | PackageParser.PARSE_IS_SYSTEM_DIR
1565                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1566
1567            // Collect ordinary system packages.
1568            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1569            mSystemInstallObserver = new AppDirObserver(
1570                    systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1571            mSystemInstallObserver.startWatching();
1572            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1573                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1574
1575            // Collect all vendor packages.
1576            File vendorAppDir = new File("/vendor/app");
1577            try {
1578                vendorAppDir = vendorAppDir.getCanonicalFile();
1579            } catch (IOException e) {
1580                // failed to look up canonical path, continue with original one
1581            }
1582            mVendorInstallObserver = new AppDirObserver(
1583                    vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1584            mVendorInstallObserver.startWatching();
1585            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1586                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1587
1588            // Collect all OEM packages.
1589            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1590            mOemInstallObserver = new AppDirObserver(
1591                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1592            mOemInstallObserver.startWatching();
1593            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1594                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1595
1596            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1597            mInstaller.moveFiles();
1598
1599            // Prune any system packages that no longer exist.
1600            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1601            if (!mOnlyCore) {
1602                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1603                while (psit.hasNext()) {
1604                    PackageSetting ps = psit.next();
1605
1606                    /*
1607                     * If this is not a system app, it can't be a
1608                     * disable system app.
1609                     */
1610                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1611                        continue;
1612                    }
1613
1614                    /*
1615                     * If the package is scanned, it's not erased.
1616                     */
1617                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1618                    if (scannedPkg != null) {
1619                        /*
1620                         * If the system app is both scanned and in the
1621                         * disabled packages list, then it must have been
1622                         * added via OTA. Remove it from the currently
1623                         * scanned package so the previously user-installed
1624                         * application can be scanned.
1625                         */
1626                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1627                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1628                                    + "; removing system app");
1629                            removePackageLI(ps, true);
1630                        }
1631
1632                        continue;
1633                    }
1634
1635                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1636                        psit.remove();
1637                        String msg = "System package " + ps.name
1638                                + " no longer exists; wiping its data";
1639                        reportSettingsProblem(Log.WARN, msg);
1640                        removeDataDirsLI(ps.name);
1641                    } else {
1642                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1643                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1644                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1645                        }
1646                    }
1647                }
1648            }
1649
1650            //look for any incomplete package installations
1651            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1652            //clean up list
1653            for(int i = 0; i < deletePkgsList.size(); i++) {
1654                //clean up here
1655                cleanupInstallFailedPackage(deletePkgsList.get(i));
1656            }
1657            //delete tmp files
1658            deleteTempPackageFiles();
1659
1660            // Remove any shared userIDs that have no associated packages
1661            mSettings.pruneSharedUsersLPw();
1662
1663            if (!mOnlyCore) {
1664                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1665                        SystemClock.uptimeMillis());
1666                mAppInstallObserver = new AppDirObserver(
1667                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1668                mAppInstallObserver.startWatching();
1669                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1670
1671                mDrmAppInstallObserver = new AppDirObserver(
1672                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1673                mDrmAppInstallObserver.startWatching();
1674                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1675                        scanMode, 0);
1676
1677                /**
1678                 * Remove disable package settings for any updated system
1679                 * apps that were removed via an OTA. If they're not a
1680                 * previously-updated app, remove them completely.
1681                 * Otherwise, just revoke their system-level permissions.
1682                 */
1683                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1684                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1685                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1686
1687                    String msg;
1688                    if (deletedPkg == null) {
1689                        msg = "Updated system package " + deletedAppName
1690                                + " no longer exists; wiping its data";
1691                        removeDataDirsLI(deletedAppName);
1692                    } else {
1693                        msg = "Updated system app + " + deletedAppName
1694                                + " no longer present; removing system privileges for "
1695                                + deletedAppName;
1696
1697                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1698
1699                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1700                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1701                    }
1702                    reportSettingsProblem(Log.WARN, msg);
1703                }
1704            } else {
1705                mAppInstallObserver = null;
1706                mDrmAppInstallObserver = null;
1707            }
1708
1709            // Now that we know all of the shared libraries, update all clients to have
1710            // the correct library paths.
1711            updateAllSharedLibrariesLPw();
1712
1713            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1714                // NOTE: We ignore potential failures here during a system scan (like
1715                // the rest of the commands above) because there's precious little we
1716                // can do about it. A settings error is reported, though.
1717                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1718                        false /* force dexopt */, false /* defer dexopt */);
1719            }
1720
1721            // Now that we know all the packages we are keeping,
1722            // read and update their last usage times.
1723            mPackageUsage.readLP();
1724
1725            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1726                    SystemClock.uptimeMillis());
1727            Slog.i(TAG, "Time to scan packages: "
1728                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1729                    + " seconds");
1730
1731            // If the platform SDK has changed since the last time we booted,
1732            // we need to re-grant app permission to catch any new ones that
1733            // appear.  This is really a hack, and means that apps can in some
1734            // cases get permissions that the user didn't initially explicitly
1735            // allow...  it would be nice to have some better way to handle
1736            // this situation.
1737            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1738                    != mSdkVersion;
1739            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1740                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1741                    + "; regranting permissions for internal storage");
1742            mSettings.mInternalSdkPlatform = mSdkVersion;
1743
1744            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1745                    | (regrantPermissions
1746                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1747                            : 0));
1748
1749            // If this is the first boot, and it is a normal boot, then
1750            // we need to initialize the default preferred apps.
1751            if (!mRestoredSettings && !onlyCore) {
1752                mSettings.readDefaultPreferredAppsLPw(this, 0);
1753            }
1754
1755            // All the changes are done during package scanning.
1756            mSettings.updateInternalDatabaseVersion();
1757
1758            // can downgrade to reader
1759            mSettings.writeLPr();
1760
1761            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1762                    SystemClock.uptimeMillis());
1763
1764
1765            mRequiredVerifierPackage = getRequiredVerifierLPr();
1766        } // synchronized (mPackages)
1767        } // synchronized (mInstallLock)
1768
1769        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1770
1771        // Now after opening every single application zip, make sure they
1772        // are all flushed.  Not really needed, but keeps things nice and
1773        // tidy.
1774        Runtime.getRuntime().gc();
1775    }
1776
1777    @Override
1778    public boolean isFirstBoot() {
1779        return !mRestoredSettings;
1780    }
1781
1782    @Override
1783    public boolean isOnlyCoreApps() {
1784        return mOnlyCore;
1785    }
1786
1787    private String getRequiredVerifierLPr() {
1788        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1789        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1790                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1791
1792        String requiredVerifier = null;
1793
1794        final int N = receivers.size();
1795        for (int i = 0; i < N; i++) {
1796            final ResolveInfo info = receivers.get(i);
1797
1798            if (info.activityInfo == null) {
1799                continue;
1800            }
1801
1802            final String packageName = info.activityInfo.packageName;
1803
1804            final PackageSetting ps = mSettings.mPackages.get(packageName);
1805            if (ps == null) {
1806                continue;
1807            }
1808
1809            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1810            if (!gp.grantedPermissions
1811                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1812                continue;
1813            }
1814
1815            if (requiredVerifier != null) {
1816                throw new RuntimeException("There can be only one required verifier");
1817            }
1818
1819            requiredVerifier = packageName;
1820        }
1821
1822        return requiredVerifier;
1823    }
1824
1825    @Override
1826    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1827            throws RemoteException {
1828        try {
1829            return super.onTransact(code, data, reply, flags);
1830        } catch (RuntimeException e) {
1831            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1832                Slog.wtf(TAG, "Package Manager Crash", e);
1833            }
1834            throw e;
1835        }
1836    }
1837
1838    void cleanupInstallFailedPackage(PackageSetting ps) {
1839        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1840        removeDataDirsLI(ps.name);
1841
1842        // TODO: try cleaning up codePath directory contents first, since it
1843        // might be a cluster
1844
1845        if (ps.codePath != null) {
1846            if (!ps.codePath.delete()) {
1847                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1848            }
1849        }
1850        if (ps.resourcePath != null) {
1851            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1852                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1853            }
1854        }
1855        mSettings.removePackageLPw(ps.name);
1856    }
1857
1858    static int[] appendInts(int[] cur, int[] add) {
1859        if (add == null) return cur;
1860        if (cur == null) return add;
1861        final int N = add.length;
1862        for (int i=0; i<N; i++) {
1863            cur = appendInt(cur, add[i]);
1864        }
1865        return cur;
1866    }
1867
1868    static int[] removeInts(int[] cur, int[] rem) {
1869        if (rem == null) return cur;
1870        if (cur == null) return cur;
1871        final int N = rem.length;
1872        for (int i=0; i<N; i++) {
1873            cur = removeInt(cur, rem[i]);
1874        }
1875        return cur;
1876    }
1877
1878    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1879        if (!sUserManager.exists(userId)) return null;
1880        final PackageSetting ps = (PackageSetting) p.mExtras;
1881        if (ps == null) {
1882            return null;
1883        }
1884        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1885        final PackageUserState state = ps.readUserState(userId);
1886        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1887                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1888                state, userId);
1889    }
1890
1891    @Override
1892    public boolean isPackageAvailable(String packageName, int userId) {
1893        if (!sUserManager.exists(userId)) return false;
1894        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1895        synchronized (mPackages) {
1896            PackageParser.Package p = mPackages.get(packageName);
1897            if (p != null) {
1898                final PackageSetting ps = (PackageSetting) p.mExtras;
1899                if (ps != null) {
1900                    final PackageUserState state = ps.readUserState(userId);
1901                    if (state != null) {
1902                        return PackageParser.isAvailable(state);
1903                    }
1904                }
1905            }
1906        }
1907        return false;
1908    }
1909
1910    @Override
1911    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1912        if (!sUserManager.exists(userId)) return null;
1913        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1914        // reader
1915        synchronized (mPackages) {
1916            PackageParser.Package p = mPackages.get(packageName);
1917            if (DEBUG_PACKAGE_INFO)
1918                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1919            if (p != null) {
1920                return generatePackageInfo(p, flags, userId);
1921            }
1922            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1923                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1924            }
1925        }
1926        return null;
1927    }
1928
1929    @Override
1930    public String[] currentToCanonicalPackageNames(String[] names) {
1931        String[] out = new String[names.length];
1932        // reader
1933        synchronized (mPackages) {
1934            for (int i=names.length-1; i>=0; i--) {
1935                PackageSetting ps = mSettings.mPackages.get(names[i]);
1936                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1937            }
1938        }
1939        return out;
1940    }
1941
1942    @Override
1943    public String[] canonicalToCurrentPackageNames(String[] names) {
1944        String[] out = new String[names.length];
1945        // reader
1946        synchronized (mPackages) {
1947            for (int i=names.length-1; i>=0; i--) {
1948                String cur = mSettings.mRenamedPackages.get(names[i]);
1949                out[i] = cur != null ? cur : names[i];
1950            }
1951        }
1952        return out;
1953    }
1954
1955    @Override
1956    public int getPackageUid(String packageName, int userId) {
1957        if (!sUserManager.exists(userId)) return -1;
1958        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1959        // reader
1960        synchronized (mPackages) {
1961            PackageParser.Package p = mPackages.get(packageName);
1962            if(p != null) {
1963                return UserHandle.getUid(userId, p.applicationInfo.uid);
1964            }
1965            PackageSetting ps = mSettings.mPackages.get(packageName);
1966            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1967                return -1;
1968            }
1969            p = ps.pkg;
1970            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1971        }
1972    }
1973
1974    @Override
1975    public int[] getPackageGids(String packageName) {
1976        // reader
1977        synchronized (mPackages) {
1978            PackageParser.Package p = mPackages.get(packageName);
1979            if (DEBUG_PACKAGE_INFO)
1980                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1981            if (p != null) {
1982                final PackageSetting ps = (PackageSetting)p.mExtras;
1983                return ps.getGids();
1984            }
1985        }
1986        // stupid thing to indicate an error.
1987        return new int[0];
1988    }
1989
1990    static final PermissionInfo generatePermissionInfo(
1991            BasePermission bp, int flags) {
1992        if (bp.perm != null) {
1993            return PackageParser.generatePermissionInfo(bp.perm, flags);
1994        }
1995        PermissionInfo pi = new PermissionInfo();
1996        pi.name = bp.name;
1997        pi.packageName = bp.sourcePackage;
1998        pi.nonLocalizedLabel = bp.name;
1999        pi.protectionLevel = bp.protectionLevel;
2000        return pi;
2001    }
2002
2003    @Override
2004    public PermissionInfo getPermissionInfo(String name, int flags) {
2005        // reader
2006        synchronized (mPackages) {
2007            final BasePermission p = mSettings.mPermissions.get(name);
2008            if (p != null) {
2009                return generatePermissionInfo(p, flags);
2010            }
2011            return null;
2012        }
2013    }
2014
2015    @Override
2016    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2017        // reader
2018        synchronized (mPackages) {
2019            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2020            for (BasePermission p : mSettings.mPermissions.values()) {
2021                if (group == null) {
2022                    if (p.perm == null || p.perm.info.group == null) {
2023                        out.add(generatePermissionInfo(p, flags));
2024                    }
2025                } else {
2026                    if (p.perm != null && group.equals(p.perm.info.group)) {
2027                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2028                    }
2029                }
2030            }
2031
2032            if (out.size() > 0) {
2033                return out;
2034            }
2035            return mPermissionGroups.containsKey(group) ? out : null;
2036        }
2037    }
2038
2039    @Override
2040    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2041        // reader
2042        synchronized (mPackages) {
2043            return PackageParser.generatePermissionGroupInfo(
2044                    mPermissionGroups.get(name), flags);
2045        }
2046    }
2047
2048    @Override
2049    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2050        // reader
2051        synchronized (mPackages) {
2052            final int N = mPermissionGroups.size();
2053            ArrayList<PermissionGroupInfo> out
2054                    = new ArrayList<PermissionGroupInfo>(N);
2055            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2056                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2057            }
2058            return out;
2059        }
2060    }
2061
2062    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2063            int userId) {
2064        if (!sUserManager.exists(userId)) return null;
2065        PackageSetting ps = mSettings.mPackages.get(packageName);
2066        if (ps != null) {
2067            if (ps.pkg == null) {
2068                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2069                        flags, userId);
2070                if (pInfo != null) {
2071                    return pInfo.applicationInfo;
2072                }
2073                return null;
2074            }
2075            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2076                    ps.readUserState(userId), userId);
2077        }
2078        return null;
2079    }
2080
2081    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2082            int userId) {
2083        if (!sUserManager.exists(userId)) return null;
2084        PackageSetting ps = mSettings.mPackages.get(packageName);
2085        if (ps != null) {
2086            PackageParser.Package pkg = ps.pkg;
2087            if (pkg == null) {
2088                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2089                    return null;
2090                }
2091                // Only data remains, so we aren't worried about code paths
2092                pkg = new PackageParser.Package(packageName);
2093                pkg.applicationInfo.packageName = packageName;
2094                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2095                pkg.applicationInfo.dataDir =
2096                        getDataPathForPackage(packageName, 0).getPath();
2097                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2098                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2099            }
2100            return generatePackageInfo(pkg, flags, userId);
2101        }
2102        return null;
2103    }
2104
2105    @Override
2106    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2107        if (!sUserManager.exists(userId)) return null;
2108        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2109        // writer
2110        synchronized (mPackages) {
2111            PackageParser.Package p = mPackages.get(packageName);
2112            if (DEBUG_PACKAGE_INFO) Log.v(
2113                    TAG, "getApplicationInfo " + packageName
2114                    + ": " + p);
2115            if (p != null) {
2116                PackageSetting ps = mSettings.mPackages.get(packageName);
2117                if (ps == null) return null;
2118                // Note: isEnabledLP() does not apply here - always return info
2119                return PackageParser.generateApplicationInfo(
2120                        p, flags, ps.readUserState(userId), userId);
2121            }
2122            if ("android".equals(packageName)||"system".equals(packageName)) {
2123                return mAndroidApplication;
2124            }
2125            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2126                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2127            }
2128        }
2129        return null;
2130    }
2131
2132
2133    @Override
2134    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2135        mContext.enforceCallingOrSelfPermission(
2136                android.Manifest.permission.CLEAR_APP_CACHE, null);
2137        // Queue up an async operation since clearing cache may take a little while.
2138        mHandler.post(new Runnable() {
2139            public void run() {
2140                mHandler.removeCallbacks(this);
2141                int retCode = -1;
2142                synchronized (mInstallLock) {
2143                    retCode = mInstaller.freeCache(freeStorageSize);
2144                    if (retCode < 0) {
2145                        Slog.w(TAG, "Couldn't clear application caches");
2146                    }
2147                }
2148                if (observer != null) {
2149                    try {
2150                        observer.onRemoveCompleted(null, (retCode >= 0));
2151                    } catch (RemoteException e) {
2152                        Slog.w(TAG, "RemoveException when invoking call back");
2153                    }
2154                }
2155            }
2156        });
2157    }
2158
2159    @Override
2160    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2161        mContext.enforceCallingOrSelfPermission(
2162                android.Manifest.permission.CLEAR_APP_CACHE, null);
2163        // Queue up an async operation since clearing cache may take a little while.
2164        mHandler.post(new Runnable() {
2165            public void run() {
2166                mHandler.removeCallbacks(this);
2167                int retCode = -1;
2168                synchronized (mInstallLock) {
2169                    retCode = mInstaller.freeCache(freeStorageSize);
2170                    if (retCode < 0) {
2171                        Slog.w(TAG, "Couldn't clear application caches");
2172                    }
2173                }
2174                if(pi != null) {
2175                    try {
2176                        // Callback via pending intent
2177                        int code = (retCode >= 0) ? 1 : 0;
2178                        pi.sendIntent(null, code, null,
2179                                null, null);
2180                    } catch (SendIntentException e1) {
2181                        Slog.i(TAG, "Failed to send pending intent");
2182                    }
2183                }
2184            }
2185        });
2186    }
2187
2188    void freeStorage(long freeStorageSize) throws IOException {
2189        synchronized (mInstallLock) {
2190            if (mInstaller.freeCache(freeStorageSize) < 0) {
2191                throw new IOException("Failed to free enough space");
2192            }
2193        }
2194    }
2195
2196    @Override
2197    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2198        if (!sUserManager.exists(userId)) return null;
2199        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2200        synchronized (mPackages) {
2201            PackageParser.Activity a = mActivities.mActivities.get(component);
2202
2203            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2204            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2205                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2206                if (ps == null) return null;
2207                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2208                        userId);
2209            }
2210            if (mResolveComponentName.equals(component)) {
2211                return mResolveActivity;
2212            }
2213        }
2214        return null;
2215    }
2216
2217    @Override
2218    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2219            String resolvedType) {
2220        synchronized (mPackages) {
2221            PackageParser.Activity a = mActivities.mActivities.get(component);
2222            if (a == null) {
2223                return false;
2224            }
2225            for (int i=0; i<a.intents.size(); i++) {
2226                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2227                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2228                    return true;
2229                }
2230            }
2231            return false;
2232        }
2233    }
2234
2235    @Override
2236    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2237        if (!sUserManager.exists(userId)) return null;
2238        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2239        synchronized (mPackages) {
2240            PackageParser.Activity a = mReceivers.mActivities.get(component);
2241            if (DEBUG_PACKAGE_INFO) Log.v(
2242                TAG, "getReceiverInfo " + component + ": " + a);
2243            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2244                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2245                if (ps == null) return null;
2246                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2247                        userId);
2248            }
2249        }
2250        return null;
2251    }
2252
2253    @Override
2254    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2255        if (!sUserManager.exists(userId)) return null;
2256        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2257        synchronized (mPackages) {
2258            PackageParser.Service s = mServices.mServices.get(component);
2259            if (DEBUG_PACKAGE_INFO) Log.v(
2260                TAG, "getServiceInfo " + component + ": " + s);
2261            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2262                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2263                if (ps == null) return null;
2264                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2265                        userId);
2266            }
2267        }
2268        return null;
2269    }
2270
2271    @Override
2272    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2273        if (!sUserManager.exists(userId)) return null;
2274        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2275        synchronized (mPackages) {
2276            PackageParser.Provider p = mProviders.mProviders.get(component);
2277            if (DEBUG_PACKAGE_INFO) Log.v(
2278                TAG, "getProviderInfo " + component + ": " + p);
2279            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2280                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2281                if (ps == null) return null;
2282                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2283                        userId);
2284            }
2285        }
2286        return null;
2287    }
2288
2289    @Override
2290    public String[] getSystemSharedLibraryNames() {
2291        Set<String> libSet;
2292        synchronized (mPackages) {
2293            libSet = mSharedLibraries.keySet();
2294            int size = libSet.size();
2295            if (size > 0) {
2296                String[] libs = new String[size];
2297                libSet.toArray(libs);
2298                return libs;
2299            }
2300        }
2301        return null;
2302    }
2303
2304    @Override
2305    public FeatureInfo[] getSystemAvailableFeatures() {
2306        Collection<FeatureInfo> featSet;
2307        synchronized (mPackages) {
2308            featSet = mAvailableFeatures.values();
2309            int size = featSet.size();
2310            if (size > 0) {
2311                FeatureInfo[] features = new FeatureInfo[size+1];
2312                featSet.toArray(features);
2313                FeatureInfo fi = new FeatureInfo();
2314                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2315                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2316                features[size] = fi;
2317                return features;
2318            }
2319        }
2320        return null;
2321    }
2322
2323    @Override
2324    public boolean hasSystemFeature(String name) {
2325        synchronized (mPackages) {
2326            return mAvailableFeatures.containsKey(name);
2327        }
2328    }
2329
2330    private void checkValidCaller(int uid, int userId) {
2331        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2332            return;
2333
2334        throw new SecurityException("Caller uid=" + uid
2335                + " is not privileged to communicate with user=" + userId);
2336    }
2337
2338    @Override
2339    public int checkPermission(String permName, String pkgName) {
2340        synchronized (mPackages) {
2341            PackageParser.Package p = mPackages.get(pkgName);
2342            if (p != null && p.mExtras != null) {
2343                PackageSetting ps = (PackageSetting)p.mExtras;
2344                if (ps.sharedUser != null) {
2345                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2346                        return PackageManager.PERMISSION_GRANTED;
2347                    }
2348                } else if (ps.grantedPermissions.contains(permName)) {
2349                    return PackageManager.PERMISSION_GRANTED;
2350                }
2351            }
2352        }
2353        return PackageManager.PERMISSION_DENIED;
2354    }
2355
2356    @Override
2357    public int checkUidPermission(String permName, int uid) {
2358        synchronized (mPackages) {
2359            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2360            if (obj != null) {
2361                GrantedPermissions gp = (GrantedPermissions)obj;
2362                if (gp.grantedPermissions.contains(permName)) {
2363                    return PackageManager.PERMISSION_GRANTED;
2364                }
2365            } else {
2366                HashSet<String> perms = mSystemPermissions.get(uid);
2367                if (perms != null && perms.contains(permName)) {
2368                    return PackageManager.PERMISSION_GRANTED;
2369                }
2370            }
2371        }
2372        return PackageManager.PERMISSION_DENIED;
2373    }
2374
2375    /**
2376     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2377     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2378     * @param message the message to log on security exception
2379     */
2380    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2381            String message) {
2382        if (userId < 0) {
2383            throw new IllegalArgumentException("Invalid userId " + userId);
2384        }
2385        if (userId == UserHandle.getUserId(callingUid)) return;
2386        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2387            if (requireFullPermission) {
2388                mContext.enforceCallingOrSelfPermission(
2389                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2390            } else {
2391                try {
2392                    mContext.enforceCallingOrSelfPermission(
2393                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2394                } catch (SecurityException se) {
2395                    mContext.enforceCallingOrSelfPermission(
2396                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2397                }
2398            }
2399        }
2400    }
2401
2402    private BasePermission findPermissionTreeLP(String permName) {
2403        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2404            if (permName.startsWith(bp.name) &&
2405                    permName.length() > bp.name.length() &&
2406                    permName.charAt(bp.name.length()) == '.') {
2407                return bp;
2408            }
2409        }
2410        return null;
2411    }
2412
2413    private BasePermission checkPermissionTreeLP(String permName) {
2414        if (permName != null) {
2415            BasePermission bp = findPermissionTreeLP(permName);
2416            if (bp != null) {
2417                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2418                    return bp;
2419                }
2420                throw new SecurityException("Calling uid "
2421                        + Binder.getCallingUid()
2422                        + " is not allowed to add to permission tree "
2423                        + bp.name + " owned by uid " + bp.uid);
2424            }
2425        }
2426        throw new SecurityException("No permission tree found for " + permName);
2427    }
2428
2429    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2430        if (s1 == null) {
2431            return s2 == null;
2432        }
2433        if (s2 == null) {
2434            return false;
2435        }
2436        if (s1.getClass() != s2.getClass()) {
2437            return false;
2438        }
2439        return s1.equals(s2);
2440    }
2441
2442    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2443        if (pi1.icon != pi2.icon) return false;
2444        if (pi1.logo != pi2.logo) return false;
2445        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2446        if (!compareStrings(pi1.name, pi2.name)) return false;
2447        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2448        // We'll take care of setting this one.
2449        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2450        // These are not currently stored in settings.
2451        //if (!compareStrings(pi1.group, pi2.group)) return false;
2452        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2453        //if (pi1.labelRes != pi2.labelRes) return false;
2454        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2455        return true;
2456    }
2457
2458    int permissionInfoFootprint(PermissionInfo info) {
2459        int size = info.name.length();
2460        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2461        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2462        return size;
2463    }
2464
2465    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2466        int size = 0;
2467        for (BasePermission perm : mSettings.mPermissions.values()) {
2468            if (perm.uid == tree.uid) {
2469                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2470            }
2471        }
2472        return size;
2473    }
2474
2475    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2476        // We calculate the max size of permissions defined by this uid and throw
2477        // if that plus the size of 'info' would exceed our stated maximum.
2478        if (tree.uid != Process.SYSTEM_UID) {
2479            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2480            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2481                throw new SecurityException("Permission tree size cap exceeded");
2482            }
2483        }
2484    }
2485
2486    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2487        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2488            throw new SecurityException("Label must be specified in permission");
2489        }
2490        BasePermission tree = checkPermissionTreeLP(info.name);
2491        BasePermission bp = mSettings.mPermissions.get(info.name);
2492        boolean added = bp == null;
2493        boolean changed = true;
2494        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2495        if (added) {
2496            enforcePermissionCapLocked(info, tree);
2497            bp = new BasePermission(info.name, tree.sourcePackage,
2498                    BasePermission.TYPE_DYNAMIC);
2499        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2500            throw new SecurityException(
2501                    "Not allowed to modify non-dynamic permission "
2502                    + info.name);
2503        } else {
2504            if (bp.protectionLevel == fixedLevel
2505                    && bp.perm.owner.equals(tree.perm.owner)
2506                    && bp.uid == tree.uid
2507                    && comparePermissionInfos(bp.perm.info, info)) {
2508                changed = false;
2509            }
2510        }
2511        bp.protectionLevel = fixedLevel;
2512        info = new PermissionInfo(info);
2513        info.protectionLevel = fixedLevel;
2514        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2515        bp.perm.info.packageName = tree.perm.info.packageName;
2516        bp.uid = tree.uid;
2517        if (added) {
2518            mSettings.mPermissions.put(info.name, bp);
2519        }
2520        if (changed) {
2521            if (!async) {
2522                mSettings.writeLPr();
2523            } else {
2524                scheduleWriteSettingsLocked();
2525            }
2526        }
2527        return added;
2528    }
2529
2530    @Override
2531    public boolean addPermission(PermissionInfo info) {
2532        synchronized (mPackages) {
2533            return addPermissionLocked(info, false);
2534        }
2535    }
2536
2537    @Override
2538    public boolean addPermissionAsync(PermissionInfo info) {
2539        synchronized (mPackages) {
2540            return addPermissionLocked(info, true);
2541        }
2542    }
2543
2544    @Override
2545    public void removePermission(String name) {
2546        synchronized (mPackages) {
2547            checkPermissionTreeLP(name);
2548            BasePermission bp = mSettings.mPermissions.get(name);
2549            if (bp != null) {
2550                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2551                    throw new SecurityException(
2552                            "Not allowed to modify non-dynamic permission "
2553                            + name);
2554                }
2555                mSettings.mPermissions.remove(name);
2556                mSettings.writeLPr();
2557            }
2558        }
2559    }
2560
2561    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2562        int index = pkg.requestedPermissions.indexOf(bp.name);
2563        if (index == -1) {
2564            throw new SecurityException("Package " + pkg.packageName
2565                    + " has not requested permission " + bp.name);
2566        }
2567        boolean isNormal =
2568                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2569                        == PermissionInfo.PROTECTION_NORMAL);
2570        boolean isDangerous =
2571                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2572                        == PermissionInfo.PROTECTION_DANGEROUS);
2573        boolean isDevelopment =
2574                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2575
2576        if (!isNormal && !isDangerous && !isDevelopment) {
2577            throw new SecurityException("Permission " + bp.name
2578                    + " is not a changeable permission type");
2579        }
2580
2581        if (isNormal || isDangerous) {
2582            if (pkg.requestedPermissionsRequired.get(index)) {
2583                throw new SecurityException("Can't change " + bp.name
2584                        + ". It is required by the application");
2585            }
2586        }
2587    }
2588
2589    @Override
2590    public void grantPermission(String packageName, String permissionName) {
2591        mContext.enforceCallingOrSelfPermission(
2592                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2593        synchronized (mPackages) {
2594            final PackageParser.Package pkg = mPackages.get(packageName);
2595            if (pkg == null) {
2596                throw new IllegalArgumentException("Unknown package: " + packageName);
2597            }
2598            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2599            if (bp == null) {
2600                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2601            }
2602
2603            checkGrantRevokePermissions(pkg, bp);
2604
2605            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2606            if (ps == null) {
2607                return;
2608            }
2609            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2610            if (gp.grantedPermissions.add(permissionName)) {
2611                if (ps.haveGids) {
2612                    gp.gids = appendInts(gp.gids, bp.gids);
2613                }
2614                mSettings.writeLPr();
2615            }
2616        }
2617    }
2618
2619    @Override
2620    public void revokePermission(String packageName, String permissionName) {
2621        int changedAppId = -1;
2622
2623        synchronized (mPackages) {
2624            final PackageParser.Package pkg = mPackages.get(packageName);
2625            if (pkg == null) {
2626                throw new IllegalArgumentException("Unknown package: " + packageName);
2627            }
2628            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2629                mContext.enforceCallingOrSelfPermission(
2630                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2631            }
2632            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2633            if (bp == null) {
2634                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2635            }
2636
2637            checkGrantRevokePermissions(pkg, bp);
2638
2639            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2640            if (ps == null) {
2641                return;
2642            }
2643            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2644            if (gp.grantedPermissions.remove(permissionName)) {
2645                gp.grantedPermissions.remove(permissionName);
2646                if (ps.haveGids) {
2647                    gp.gids = removeInts(gp.gids, bp.gids);
2648                }
2649                mSettings.writeLPr();
2650                changedAppId = ps.appId;
2651            }
2652        }
2653
2654        if (changedAppId >= 0) {
2655            // We changed the perm on someone, kill its processes.
2656            IActivityManager am = ActivityManagerNative.getDefault();
2657            if (am != null) {
2658                final int callingUserId = UserHandle.getCallingUserId();
2659                final long ident = Binder.clearCallingIdentity();
2660                try {
2661                    //XXX we should only revoke for the calling user's app permissions,
2662                    // but for now we impact all users.
2663                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2664                    //        "revoke " + permissionName);
2665                    int[] users = sUserManager.getUserIds();
2666                    for (int user : users) {
2667                        am.killUid(UserHandle.getUid(user, changedAppId),
2668                                "revoke " + permissionName);
2669                    }
2670                } catch (RemoteException e) {
2671                } finally {
2672                    Binder.restoreCallingIdentity(ident);
2673                }
2674            }
2675        }
2676    }
2677
2678    @Override
2679    public boolean isProtectedBroadcast(String actionName) {
2680        synchronized (mPackages) {
2681            return mProtectedBroadcasts.contains(actionName);
2682        }
2683    }
2684
2685    @Override
2686    public int checkSignatures(String pkg1, String pkg2) {
2687        synchronized (mPackages) {
2688            final PackageParser.Package p1 = mPackages.get(pkg1);
2689            final PackageParser.Package p2 = mPackages.get(pkg2);
2690            if (p1 == null || p1.mExtras == null
2691                    || p2 == null || p2.mExtras == null) {
2692                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2693            }
2694            return compareSignatures(p1.mSignatures, p2.mSignatures);
2695        }
2696    }
2697
2698    @Override
2699    public int checkUidSignatures(int uid1, int uid2) {
2700        // Map to base uids.
2701        uid1 = UserHandle.getAppId(uid1);
2702        uid2 = UserHandle.getAppId(uid2);
2703        // reader
2704        synchronized (mPackages) {
2705            Signature[] s1;
2706            Signature[] s2;
2707            Object obj = mSettings.getUserIdLPr(uid1);
2708            if (obj != null) {
2709                if (obj instanceof SharedUserSetting) {
2710                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2711                } else if (obj instanceof PackageSetting) {
2712                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2713                } else {
2714                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2715                }
2716            } else {
2717                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2718            }
2719            obj = mSettings.getUserIdLPr(uid2);
2720            if (obj != null) {
2721                if (obj instanceof SharedUserSetting) {
2722                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2723                } else if (obj instanceof PackageSetting) {
2724                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2725                } else {
2726                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2727                }
2728            } else {
2729                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2730            }
2731            return compareSignatures(s1, s2);
2732        }
2733    }
2734
2735    /**
2736     * Compares two sets of signatures. Returns:
2737     * <br />
2738     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2739     * <br />
2740     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2741     * <br />
2742     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2743     * <br />
2744     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2745     * <br />
2746     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2747     */
2748    static int compareSignatures(Signature[] s1, Signature[] s2) {
2749        if (s1 == null) {
2750            return s2 == null
2751                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2752                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2753        }
2754
2755        if (s2 == null) {
2756            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2757        }
2758
2759        if (s1.length != s2.length) {
2760            return PackageManager.SIGNATURE_NO_MATCH;
2761        }
2762
2763        // Since both signature sets are of size 1, we can compare without HashSets.
2764        if (s1.length == 1) {
2765            return s1[0].equals(s2[0]) ?
2766                    PackageManager.SIGNATURE_MATCH :
2767                    PackageManager.SIGNATURE_NO_MATCH;
2768        }
2769
2770        HashSet<Signature> set1 = new HashSet<Signature>();
2771        for (Signature sig : s1) {
2772            set1.add(sig);
2773        }
2774        HashSet<Signature> set2 = new HashSet<Signature>();
2775        for (Signature sig : s2) {
2776            set2.add(sig);
2777        }
2778        // Make sure s2 contains all signatures in s1.
2779        if (set1.equals(set2)) {
2780            return PackageManager.SIGNATURE_MATCH;
2781        }
2782        return PackageManager.SIGNATURE_NO_MATCH;
2783    }
2784
2785    /**
2786     * If the database version for this type of package (internal storage or
2787     * external storage) is less than the version where package signatures
2788     * were updated, return true.
2789     */
2790    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2791        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2792                DatabaseVersion.SIGNATURE_END_ENTITY))
2793                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2794                        DatabaseVersion.SIGNATURE_END_ENTITY));
2795    }
2796
2797    /**
2798     * Used for backward compatibility to make sure any packages with
2799     * certificate chains get upgraded to the new style. {@code existingSigs}
2800     * will be in the old format (since they were stored on disk from before the
2801     * system upgrade) and {@code scannedSigs} will be in the newer format.
2802     */
2803    private int compareSignaturesCompat(PackageSignatures existingSigs,
2804            PackageParser.Package scannedPkg) {
2805        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2806            return PackageManager.SIGNATURE_NO_MATCH;
2807        }
2808
2809        HashSet<Signature> existingSet = new HashSet<Signature>();
2810        for (Signature sig : existingSigs.mSignatures) {
2811            existingSet.add(sig);
2812        }
2813        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2814        for (Signature sig : scannedPkg.mSignatures) {
2815            try {
2816                Signature[] chainSignatures = sig.getChainSignatures();
2817                for (Signature chainSig : chainSignatures) {
2818                    scannedCompatSet.add(chainSig);
2819                }
2820            } catch (CertificateEncodingException e) {
2821                scannedCompatSet.add(sig);
2822            }
2823        }
2824        /*
2825         * Make sure the expanded scanned set contains all signatures in the
2826         * existing one.
2827         */
2828        if (scannedCompatSet.equals(existingSet)) {
2829            // Migrate the old signatures to the new scheme.
2830            existingSigs.assignSignatures(scannedPkg.mSignatures);
2831            // The new KeySets will be re-added later in the scanning process.
2832            synchronized (mPackages) {
2833                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2834            }
2835            return PackageManager.SIGNATURE_MATCH;
2836        }
2837        return PackageManager.SIGNATURE_NO_MATCH;
2838    }
2839
2840    @Override
2841    public String[] getPackagesForUid(int uid) {
2842        uid = UserHandle.getAppId(uid);
2843        // reader
2844        synchronized (mPackages) {
2845            Object obj = mSettings.getUserIdLPr(uid);
2846            if (obj instanceof SharedUserSetting) {
2847                final SharedUserSetting sus = (SharedUserSetting) obj;
2848                final int N = sus.packages.size();
2849                final String[] res = new String[N];
2850                final Iterator<PackageSetting> it = sus.packages.iterator();
2851                int i = 0;
2852                while (it.hasNext()) {
2853                    res[i++] = it.next().name;
2854                }
2855                return res;
2856            } else if (obj instanceof PackageSetting) {
2857                final PackageSetting ps = (PackageSetting) obj;
2858                return new String[] { ps.name };
2859            }
2860        }
2861        return null;
2862    }
2863
2864    @Override
2865    public String getNameForUid(int uid) {
2866        // reader
2867        synchronized (mPackages) {
2868            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2869            if (obj instanceof SharedUserSetting) {
2870                final SharedUserSetting sus = (SharedUserSetting) obj;
2871                return sus.name + ":" + sus.userId;
2872            } else if (obj instanceof PackageSetting) {
2873                final PackageSetting ps = (PackageSetting) obj;
2874                return ps.name;
2875            }
2876        }
2877        return null;
2878    }
2879
2880    @Override
2881    public int getUidForSharedUser(String sharedUserName) {
2882        if(sharedUserName == null) {
2883            return -1;
2884        }
2885        // reader
2886        synchronized (mPackages) {
2887            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2888            if (suid == null) {
2889                return -1;
2890            }
2891            return suid.userId;
2892        }
2893    }
2894
2895    @Override
2896    public int getFlagsForUid(int uid) {
2897        synchronized (mPackages) {
2898            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2899            if (obj instanceof SharedUserSetting) {
2900                final SharedUserSetting sus = (SharedUserSetting) obj;
2901                return sus.pkgFlags;
2902            } else if (obj instanceof PackageSetting) {
2903                final PackageSetting ps = (PackageSetting) obj;
2904                return ps.pkgFlags;
2905            }
2906        }
2907        return 0;
2908    }
2909
2910    @Override
2911    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2912            int flags, int userId) {
2913        if (!sUserManager.exists(userId)) return null;
2914        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2915        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2916        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2917    }
2918
2919    @Override
2920    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2921            IntentFilter filter, int match, ComponentName activity) {
2922        final int userId = UserHandle.getCallingUserId();
2923        if (DEBUG_PREFERRED) {
2924            Log.v(TAG, "setLastChosenActivity intent=" + intent
2925                + " resolvedType=" + resolvedType
2926                + " flags=" + flags
2927                + " filter=" + filter
2928                + " match=" + match
2929                + " activity=" + activity);
2930            filter.dump(new PrintStreamPrinter(System.out), "    ");
2931        }
2932        intent.setComponent(null);
2933        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2934        // Find any earlier preferred or last chosen entries and nuke them
2935        findPreferredActivity(intent, resolvedType,
2936                flags, query, 0, false, true, false, userId);
2937        // Add the new activity as the last chosen for this filter
2938        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2939    }
2940
2941    @Override
2942    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2943        final int userId = UserHandle.getCallingUserId();
2944        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2945        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2946        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2947                false, false, false, userId);
2948    }
2949
2950    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2951            int flags, List<ResolveInfo> query, int userId) {
2952        if (query != null) {
2953            final int N = query.size();
2954            if (N == 1) {
2955                return query.get(0);
2956            } else if (N > 1) {
2957                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2958                // If there is more than one activity with the same priority,
2959                // then let the user decide between them.
2960                ResolveInfo r0 = query.get(0);
2961                ResolveInfo r1 = query.get(1);
2962                if (DEBUG_INTENT_MATCHING || debug) {
2963                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2964                            + r1.activityInfo.name + "=" + r1.priority);
2965                }
2966                // If the first activity has a higher priority, or a different
2967                // default, then it is always desireable to pick it.
2968                if (r0.priority != r1.priority
2969                        || r0.preferredOrder != r1.preferredOrder
2970                        || r0.isDefault != r1.isDefault) {
2971                    return query.get(0);
2972                }
2973                // If we have saved a preference for a preferred activity for
2974                // this Intent, use that.
2975                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2976                        flags, query, r0.priority, true, false, debug, userId);
2977                if (ri != null) {
2978                    return ri;
2979                }
2980                if (userId != 0) {
2981                    ri = new ResolveInfo(mResolveInfo);
2982                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2983                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2984                            ri.activityInfo.applicationInfo);
2985                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2986                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2987                    return ri;
2988                }
2989                return mResolveInfo;
2990            }
2991        }
2992        return null;
2993    }
2994
2995    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2996            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2997        final int N = query.size();
2998        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2999                .get(userId);
3000        // Get the list of persistent preferred activities that handle the intent
3001        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3002        List<PersistentPreferredActivity> pprefs = ppir != null
3003                ? ppir.queryIntent(intent, resolvedType,
3004                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3005                : null;
3006        if (pprefs != null && pprefs.size() > 0) {
3007            final int M = pprefs.size();
3008            for (int i=0; i<M; i++) {
3009                final PersistentPreferredActivity ppa = pprefs.get(i);
3010                if (DEBUG_PREFERRED || debug) {
3011                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3012                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3013                            + "\n  component=" + ppa.mComponent);
3014                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3015                }
3016                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3017                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3018                if (DEBUG_PREFERRED || debug) {
3019                    Slog.v(TAG, "Found persistent preferred activity:");
3020                    if (ai != null) {
3021                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3022                    } else {
3023                        Slog.v(TAG, "  null");
3024                    }
3025                }
3026                if (ai == null) {
3027                    // This previously registered persistent preferred activity
3028                    // component is no longer known. Ignore it and do NOT remove it.
3029                    continue;
3030                }
3031                for (int j=0; j<N; j++) {
3032                    final ResolveInfo ri = query.get(j);
3033                    if (!ri.activityInfo.applicationInfo.packageName
3034                            .equals(ai.applicationInfo.packageName)) {
3035                        continue;
3036                    }
3037                    if (!ri.activityInfo.name.equals(ai.name)) {
3038                        continue;
3039                    }
3040                    //  Found a persistent preference that can handle the intent.
3041                    if (DEBUG_PREFERRED || debug) {
3042                        Slog.v(TAG, "Returning persistent preferred activity: " +
3043                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3044                    }
3045                    return ri;
3046                }
3047            }
3048        }
3049        return null;
3050    }
3051
3052    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3053            List<ResolveInfo> query, int priority, boolean always,
3054            boolean removeMatches, boolean debug, int userId) {
3055        if (!sUserManager.exists(userId)) return null;
3056        // writer
3057        synchronized (mPackages) {
3058            if (intent.getSelector() != null) {
3059                intent = intent.getSelector();
3060            }
3061            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3062
3063            // Try to find a matching persistent preferred activity.
3064            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3065                    debug, userId);
3066
3067            // If a persistent preferred activity matched, use it.
3068            if (pri != null) {
3069                return pri;
3070            }
3071
3072            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3073            // Get the list of preferred activities that handle the intent
3074            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3075            List<PreferredActivity> prefs = pir != null
3076                    ? pir.queryIntent(intent, resolvedType,
3077                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3078                    : null;
3079            if (prefs != null && prefs.size() > 0) {
3080                // First figure out how good the original match set is.
3081                // We will only allow preferred activities that came
3082                // from the same match quality.
3083                int match = 0;
3084
3085                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3086
3087                final int N = query.size();
3088                for (int j=0; j<N; j++) {
3089                    final ResolveInfo ri = query.get(j);
3090                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3091                            + ": 0x" + Integer.toHexString(match));
3092                    if (ri.match > match) {
3093                        match = ri.match;
3094                    }
3095                }
3096
3097                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3098                        + Integer.toHexString(match));
3099
3100                match &= IntentFilter.MATCH_CATEGORY_MASK;
3101                final int M = prefs.size();
3102                for (int i=0; i<M; i++) {
3103                    final PreferredActivity pa = prefs.get(i);
3104                    if (DEBUG_PREFERRED || debug) {
3105                        Slog.v(TAG, "Checking PreferredActivity ds="
3106                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3107                                + "\n  component=" + pa.mPref.mComponent);
3108                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3109                    }
3110                    if (pa.mPref.mMatch != match) {
3111                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3112                                + Integer.toHexString(pa.mPref.mMatch));
3113                        continue;
3114                    }
3115                    // If it's not an "always" type preferred activity and that's what we're
3116                    // looking for, skip it.
3117                    if (always && !pa.mPref.mAlways) {
3118                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3119                        continue;
3120                    }
3121                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3122                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3123                    if (DEBUG_PREFERRED || debug) {
3124                        Slog.v(TAG, "Found preferred activity:");
3125                        if (ai != null) {
3126                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3127                        } else {
3128                            Slog.v(TAG, "  null");
3129                        }
3130                    }
3131                    if (ai == null) {
3132                        // This previously registered preferred activity
3133                        // component is no longer known.  Most likely an update
3134                        // to the app was installed and in the new version this
3135                        // component no longer exists.  Clean it up by removing
3136                        // it from the preferred activities list, and skip it.
3137                        Slog.w(TAG, "Removing dangling preferred activity: "
3138                                + pa.mPref.mComponent);
3139                        pir.removeFilter(pa);
3140                        continue;
3141                    }
3142                    for (int j=0; j<N; j++) {
3143                        final ResolveInfo ri = query.get(j);
3144                        if (!ri.activityInfo.applicationInfo.packageName
3145                                .equals(ai.applicationInfo.packageName)) {
3146                            continue;
3147                        }
3148                        if (!ri.activityInfo.name.equals(ai.name)) {
3149                            continue;
3150                        }
3151
3152                        if (removeMatches) {
3153                            pir.removeFilter(pa);
3154                            if (DEBUG_PREFERRED) {
3155                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3156                            }
3157                            break;
3158                        }
3159
3160                        // Okay we found a previously set preferred or last chosen app.
3161                        // If the result set is different from when this
3162                        // was created, we need to clear it and re-ask the
3163                        // user their preference, if we're looking for an "always" type entry.
3164                        if (always && !pa.mPref.sameSet(query, priority)) {
3165                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3166                                    + intent + " type " + resolvedType);
3167                            if (DEBUG_PREFERRED) {
3168                                Slog.v(TAG, "Removing preferred activity since set changed "
3169                                        + pa.mPref.mComponent);
3170                            }
3171                            pir.removeFilter(pa);
3172                            // Re-add the filter as a "last chosen" entry (!always)
3173                            PreferredActivity lastChosen = new PreferredActivity(
3174                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3175                            pir.addFilter(lastChosen);
3176                            mSettings.writePackageRestrictionsLPr(userId);
3177                            return null;
3178                        }
3179
3180                        // Yay! Either the set matched or we're looking for the last chosen
3181                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3182                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3183                        mSettings.writePackageRestrictionsLPr(userId);
3184                        return ri;
3185                    }
3186                }
3187            }
3188            mSettings.writePackageRestrictionsLPr(userId);
3189        }
3190        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3191        return null;
3192    }
3193
3194    /*
3195     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3196     */
3197    @Override
3198    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3199            int targetUserId) {
3200        mContext.enforceCallingOrSelfPermission(
3201                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3202        List<CrossProfileIntentFilter> matches =
3203                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3204        if (matches != null) {
3205            int size = matches.size();
3206            for (int i = 0; i < size; i++) {
3207                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3208            }
3209        }
3210
3211        ArrayList<String> packageNames = null;
3212        SparseArray<ArrayList<String>> fromSource =
3213                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3214        if (fromSource != null) {
3215            packageNames = fromSource.get(targetUserId);
3216        }
3217        if (packageNames.contains(intent.getPackage())) {
3218            return true;
3219        }
3220        // We need the package name, so we try to resolve with the loosest flags possible
3221        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3222                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3223        int count = resolveInfos.size();
3224        for (int i = 0; i < count; i++) {
3225            ResolveInfo resolveInfo = resolveInfos.get(i);
3226            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3227                return true;
3228            }
3229        }
3230        return false;
3231    }
3232
3233    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3234            String resolvedType, int userId) {
3235        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3236        if (resolver != null) {
3237            return resolver.queryIntent(intent, resolvedType, false, userId);
3238        }
3239        return null;
3240    }
3241
3242    @Override
3243    public List<ResolveInfo> queryIntentActivities(Intent intent,
3244            String resolvedType, int flags, int userId) {
3245        if (!sUserManager.exists(userId)) return Collections.emptyList();
3246        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3247        ComponentName comp = intent.getComponent();
3248        if (comp == null) {
3249            if (intent.getSelector() != null) {
3250                intent = intent.getSelector();
3251                comp = intent.getComponent();
3252            }
3253        }
3254
3255        if (comp != null) {
3256            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3257            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3258            if (ai != null) {
3259                final ResolveInfo ri = new ResolveInfo();
3260                ri.activityInfo = ai;
3261                list.add(ri);
3262            }
3263            return list;
3264        }
3265
3266        // reader
3267        synchronized (mPackages) {
3268            final String pkgName = intent.getPackage();
3269            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3270            if (pkgName == null) {
3271                ResolveInfo resolveInfo = null;
3272                if (queryCrossProfile) {
3273                    // Check if the intent needs to be forwarded to another user for this package
3274                    ArrayList<ResolveInfo> crossProfileResult =
3275                            queryIntentActivitiesCrossProfilePackage(
3276                                    intent, resolvedType, flags, userId);
3277                    if (!crossProfileResult.isEmpty()) {
3278                        // Skip the current profile
3279                        return crossProfileResult;
3280                    }
3281                    List<CrossProfileIntentFilter> matchingFilters =
3282                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3283                    // Check for results that need to skip the current profile.
3284                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3285                            resolvedType, flags, userId);
3286                    if (resolveInfo != null) {
3287                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3288                        result.add(resolveInfo);
3289                        return result;
3290                    }
3291                    // Check for cross profile results.
3292                    resolveInfo = queryCrossProfileIntents(
3293                            matchingFilters, intent, resolvedType, flags, userId);
3294                }
3295                // Check for results in the current profile.
3296                List<ResolveInfo> result = mActivities.queryIntent(
3297                        intent, resolvedType, flags, userId);
3298                if (resolveInfo != null) {
3299                    result.add(resolveInfo);
3300                }
3301                return result;
3302            }
3303            final PackageParser.Package pkg = mPackages.get(pkgName);
3304            if (pkg != null) {
3305                if (queryCrossProfile) {
3306                    ArrayList<ResolveInfo> crossProfileResult =
3307                            queryIntentActivitiesCrossProfilePackage(
3308                                    intent, resolvedType, flags, userId, pkg, pkgName);
3309                    if (!crossProfileResult.isEmpty()) {
3310                        // Skip the current profile
3311                        return crossProfileResult;
3312                    }
3313                }
3314                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3315                        pkg.activities, userId);
3316            }
3317            return new ArrayList<ResolveInfo>();
3318        }
3319    }
3320
3321    private ResolveInfo querySkipCurrentProfileIntents(
3322            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3323            int flags, int sourceUserId) {
3324        if (matchingFilters != null) {
3325            int size = matchingFilters.size();
3326            for (int i = 0; i < size; i ++) {
3327                CrossProfileIntentFilter filter = matchingFilters.get(i);
3328                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3329                    // Checking if there are activities in the target user that can handle the
3330                    // intent.
3331                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3332                            flags, sourceUserId);
3333                    if (resolveInfo != null) {
3334                        return resolveInfo;
3335                    }
3336                }
3337            }
3338        }
3339        return null;
3340    }
3341
3342    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3343            Intent intent, String resolvedType, int flags, int userId) {
3344        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3345        SparseArray<ArrayList<String>> sourceForwardingInfo =
3346                mSettings.mCrossProfilePackageInfo.get(userId);
3347        if (sourceForwardingInfo != null) {
3348            int NI = sourceForwardingInfo.size();
3349            for (int i = 0; i < NI; i++) {
3350                int targetUserId = sourceForwardingInfo.keyAt(i);
3351                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3352                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3353                        intent, resolvedType, flags, targetUserId);
3354                int NJ = resolveInfos.size();
3355                for (int j = 0; j < NJ; j++) {
3356                    ResolveInfo resolveInfo = resolveInfos.get(j);
3357                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3358                        matchingResolveInfos.add(createForwardingResolveInfo(
3359                                resolveInfo.filter, userId, targetUserId));
3360                    }
3361                }
3362            }
3363        }
3364        return matchingResolveInfos;
3365    }
3366
3367    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3368            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3369            String packageName) {
3370        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3371        SparseArray<ArrayList<String>> sourceForwardingInfo =
3372                mSettings.mCrossProfilePackageInfo.get(userId);
3373        if (sourceForwardingInfo != null) {
3374            int NI = sourceForwardingInfo.size();
3375            for (int i = 0; i < NI; i++) {
3376                int targetUserId = sourceForwardingInfo.keyAt(i);
3377                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3378                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3379                            intent, resolvedType, flags, pkg.activities, targetUserId);
3380                    int NJ = resolveInfos.size();
3381                    for (int j = 0; j < NJ; j++) {
3382                        ResolveInfo resolveInfo = resolveInfos.get(j);
3383                        matchingResolveInfos.add(createForwardingResolveInfo(
3384                                resolveInfo.filter, userId, targetUserId));
3385                    }
3386                }
3387            }
3388        }
3389        return matchingResolveInfos;
3390    }
3391
3392    // Return matching ResolveInfo if any for skip current profile intent filters.
3393    private ResolveInfo queryCrossProfileIntents(
3394            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3395            int flags, int sourceUserId) {
3396        if (matchingFilters != null) {
3397            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3398            // match the same intent. For performance reasons, it is better not to
3399            // run queryIntent twice for the same userId
3400            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3401            int size = matchingFilters.size();
3402            for (int i = 0; i < size; i++) {
3403                CrossProfileIntentFilter filter = matchingFilters.get(i);
3404                int targetUserId = filter.getTargetUserId();
3405                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3406                        && !alreadyTriedUserIds.get(targetUserId)) {
3407                    // Checking if there are activities in the target user that can handle the
3408                    // intent.
3409                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3410                            flags, sourceUserId);
3411                    if (resolveInfo != null) return resolveInfo;
3412                    alreadyTriedUserIds.put(targetUserId, true);
3413                }
3414            }
3415        }
3416        return null;
3417    }
3418
3419    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3420            String resolvedType, int flags, int sourceUserId) {
3421        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3422                resolvedType, flags, filter.getTargetUserId());
3423        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3424            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3425        }
3426        return null;
3427    }
3428
3429    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3430            int sourceUserId, int targetUserId) {
3431        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3432        String className;
3433        if (targetUserId == UserHandle.USER_OWNER) {
3434            className = FORWARD_INTENT_TO_USER_OWNER;
3435        } else {
3436            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3437        }
3438        ComponentName forwardingActivityComponentName = new ComponentName(
3439                mAndroidApplication.packageName, className);
3440        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3441                sourceUserId);
3442        if (targetUserId == UserHandle.USER_OWNER) {
3443            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3444            forwardingResolveInfo.noResourceId = true;
3445        }
3446        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3447        forwardingResolveInfo.priority = 0;
3448        forwardingResolveInfo.preferredOrder = 0;
3449        forwardingResolveInfo.match = 0;
3450        forwardingResolveInfo.isDefault = true;
3451        forwardingResolveInfo.filter = filter;
3452        forwardingResolveInfo.targetUserId = targetUserId;
3453        return forwardingResolveInfo;
3454    }
3455
3456    @Override
3457    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3458            Intent[] specifics, String[] specificTypes, Intent intent,
3459            String resolvedType, int flags, int userId) {
3460        if (!sUserManager.exists(userId)) return Collections.emptyList();
3461        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3462                "query intent activity options");
3463        final String resultsAction = intent.getAction();
3464
3465        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3466                | PackageManager.GET_RESOLVED_FILTER, userId);
3467
3468        if (DEBUG_INTENT_MATCHING) {
3469            Log.v(TAG, "Query " + intent + ": " + results);
3470        }
3471
3472        int specificsPos = 0;
3473        int N;
3474
3475        // todo: note that the algorithm used here is O(N^2).  This
3476        // isn't a problem in our current environment, but if we start running
3477        // into situations where we have more than 5 or 10 matches then this
3478        // should probably be changed to something smarter...
3479
3480        // First we go through and resolve each of the specific items
3481        // that were supplied, taking care of removing any corresponding
3482        // duplicate items in the generic resolve list.
3483        if (specifics != null) {
3484            for (int i=0; i<specifics.length; i++) {
3485                final Intent sintent = specifics[i];
3486                if (sintent == null) {
3487                    continue;
3488                }
3489
3490                if (DEBUG_INTENT_MATCHING) {
3491                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3492                }
3493
3494                String action = sintent.getAction();
3495                if (resultsAction != null && resultsAction.equals(action)) {
3496                    // If this action was explicitly requested, then don't
3497                    // remove things that have it.
3498                    action = null;
3499                }
3500
3501                ResolveInfo ri = null;
3502                ActivityInfo ai = null;
3503
3504                ComponentName comp = sintent.getComponent();
3505                if (comp == null) {
3506                    ri = resolveIntent(
3507                        sintent,
3508                        specificTypes != null ? specificTypes[i] : null,
3509                            flags, userId);
3510                    if (ri == null) {
3511                        continue;
3512                    }
3513                    if (ri == mResolveInfo) {
3514                        // ACK!  Must do something better with this.
3515                    }
3516                    ai = ri.activityInfo;
3517                    comp = new ComponentName(ai.applicationInfo.packageName,
3518                            ai.name);
3519                } else {
3520                    ai = getActivityInfo(comp, flags, userId);
3521                    if (ai == null) {
3522                        continue;
3523                    }
3524                }
3525
3526                // Look for any generic query activities that are duplicates
3527                // of this specific one, and remove them from the results.
3528                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3529                N = results.size();
3530                int j;
3531                for (j=specificsPos; j<N; j++) {
3532                    ResolveInfo sri = results.get(j);
3533                    if ((sri.activityInfo.name.equals(comp.getClassName())
3534                            && sri.activityInfo.applicationInfo.packageName.equals(
3535                                    comp.getPackageName()))
3536                        || (action != null && sri.filter.matchAction(action))) {
3537                        results.remove(j);
3538                        if (DEBUG_INTENT_MATCHING) Log.v(
3539                            TAG, "Removing duplicate item from " + j
3540                            + " due to specific " + specificsPos);
3541                        if (ri == null) {
3542                            ri = sri;
3543                        }
3544                        j--;
3545                        N--;
3546                    }
3547                }
3548
3549                // Add this specific item to its proper place.
3550                if (ri == null) {
3551                    ri = new ResolveInfo();
3552                    ri.activityInfo = ai;
3553                }
3554                results.add(specificsPos, ri);
3555                ri.specificIndex = i;
3556                specificsPos++;
3557            }
3558        }
3559
3560        // Now we go through the remaining generic results and remove any
3561        // duplicate actions that are found here.
3562        N = results.size();
3563        for (int i=specificsPos; i<N-1; i++) {
3564            final ResolveInfo rii = results.get(i);
3565            if (rii.filter == null) {
3566                continue;
3567            }
3568
3569            // Iterate over all of the actions of this result's intent
3570            // filter...  typically this should be just one.
3571            final Iterator<String> it = rii.filter.actionsIterator();
3572            if (it == null) {
3573                continue;
3574            }
3575            while (it.hasNext()) {
3576                final String action = it.next();
3577                if (resultsAction != null && resultsAction.equals(action)) {
3578                    // If this action was explicitly requested, then don't
3579                    // remove things that have it.
3580                    continue;
3581                }
3582                for (int j=i+1; j<N; j++) {
3583                    final ResolveInfo rij = results.get(j);
3584                    if (rij.filter != null && rij.filter.hasAction(action)) {
3585                        results.remove(j);
3586                        if (DEBUG_INTENT_MATCHING) Log.v(
3587                            TAG, "Removing duplicate item from " + j
3588                            + " due to action " + action + " at " + i);
3589                        j--;
3590                        N--;
3591                    }
3592                }
3593            }
3594
3595            // If the caller didn't request filter information, drop it now
3596            // so we don't have to marshall/unmarshall it.
3597            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3598                rii.filter = null;
3599            }
3600        }
3601
3602        // Filter out the caller activity if so requested.
3603        if (caller != null) {
3604            N = results.size();
3605            for (int i=0; i<N; i++) {
3606                ActivityInfo ainfo = results.get(i).activityInfo;
3607                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3608                        && caller.getClassName().equals(ainfo.name)) {
3609                    results.remove(i);
3610                    break;
3611                }
3612            }
3613        }
3614
3615        // If the caller didn't request filter information,
3616        // drop them now so we don't have to
3617        // marshall/unmarshall it.
3618        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3619            N = results.size();
3620            for (int i=0; i<N; i++) {
3621                results.get(i).filter = null;
3622            }
3623        }
3624
3625        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3626        return results;
3627    }
3628
3629    @Override
3630    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3631            int userId) {
3632        if (!sUserManager.exists(userId)) return Collections.emptyList();
3633        ComponentName comp = intent.getComponent();
3634        if (comp == null) {
3635            if (intent.getSelector() != null) {
3636                intent = intent.getSelector();
3637                comp = intent.getComponent();
3638            }
3639        }
3640        if (comp != null) {
3641            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3642            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3643            if (ai != null) {
3644                ResolveInfo ri = new ResolveInfo();
3645                ri.activityInfo = ai;
3646                list.add(ri);
3647            }
3648            return list;
3649        }
3650
3651        // reader
3652        synchronized (mPackages) {
3653            String pkgName = intent.getPackage();
3654            if (pkgName == null) {
3655                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3656            }
3657            final PackageParser.Package pkg = mPackages.get(pkgName);
3658            if (pkg != null) {
3659                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3660                        userId);
3661            }
3662            return null;
3663        }
3664    }
3665
3666    @Override
3667    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3668        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3669        if (!sUserManager.exists(userId)) return null;
3670        if (query != null) {
3671            if (query.size() >= 1) {
3672                // If there is more than one service with the same priority,
3673                // just arbitrarily pick the first one.
3674                return query.get(0);
3675            }
3676        }
3677        return null;
3678    }
3679
3680    @Override
3681    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3682            int userId) {
3683        if (!sUserManager.exists(userId)) return Collections.emptyList();
3684        ComponentName comp = intent.getComponent();
3685        if (comp == null) {
3686            if (intent.getSelector() != null) {
3687                intent = intent.getSelector();
3688                comp = intent.getComponent();
3689            }
3690        }
3691        if (comp != null) {
3692            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3693            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3694            if (si != null) {
3695                final ResolveInfo ri = new ResolveInfo();
3696                ri.serviceInfo = si;
3697                list.add(ri);
3698            }
3699            return list;
3700        }
3701
3702        // reader
3703        synchronized (mPackages) {
3704            String pkgName = intent.getPackage();
3705            if (pkgName == null) {
3706                return mServices.queryIntent(intent, resolvedType, flags, userId);
3707            }
3708            final PackageParser.Package pkg = mPackages.get(pkgName);
3709            if (pkg != null) {
3710                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3711                        userId);
3712            }
3713            return null;
3714        }
3715    }
3716
3717    @Override
3718    public List<ResolveInfo> queryIntentContentProviders(
3719            Intent intent, String resolvedType, int flags, int userId) {
3720        if (!sUserManager.exists(userId)) return Collections.emptyList();
3721        ComponentName comp = intent.getComponent();
3722        if (comp == null) {
3723            if (intent.getSelector() != null) {
3724                intent = intent.getSelector();
3725                comp = intent.getComponent();
3726            }
3727        }
3728        if (comp != null) {
3729            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3730            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3731            if (pi != null) {
3732                final ResolveInfo ri = new ResolveInfo();
3733                ri.providerInfo = pi;
3734                list.add(ri);
3735            }
3736            return list;
3737        }
3738
3739        // reader
3740        synchronized (mPackages) {
3741            String pkgName = intent.getPackage();
3742            if (pkgName == null) {
3743                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3744            }
3745            final PackageParser.Package pkg = mPackages.get(pkgName);
3746            if (pkg != null) {
3747                return mProviders.queryIntentForPackage(
3748                        intent, resolvedType, flags, pkg.providers, userId);
3749            }
3750            return null;
3751        }
3752    }
3753
3754    @Override
3755    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3756        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3757
3758        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3759
3760        // writer
3761        synchronized (mPackages) {
3762            ArrayList<PackageInfo> list;
3763            if (listUninstalled) {
3764                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3765                for (PackageSetting ps : mSettings.mPackages.values()) {
3766                    PackageInfo pi;
3767                    if (ps.pkg != null) {
3768                        pi = generatePackageInfo(ps.pkg, flags, userId);
3769                    } else {
3770                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3771                    }
3772                    if (pi != null) {
3773                        list.add(pi);
3774                    }
3775                }
3776            } else {
3777                list = new ArrayList<PackageInfo>(mPackages.size());
3778                for (PackageParser.Package p : mPackages.values()) {
3779                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3780                    if (pi != null) {
3781                        list.add(pi);
3782                    }
3783                }
3784            }
3785
3786            return new ParceledListSlice<PackageInfo>(list);
3787        }
3788    }
3789
3790    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3791            String[] permissions, boolean[] tmp, int flags, int userId) {
3792        int numMatch = 0;
3793        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3794        for (int i=0; i<permissions.length; i++) {
3795            if (gp.grantedPermissions.contains(permissions[i])) {
3796                tmp[i] = true;
3797                numMatch++;
3798            } else {
3799                tmp[i] = false;
3800            }
3801        }
3802        if (numMatch == 0) {
3803            return;
3804        }
3805        PackageInfo pi;
3806        if (ps.pkg != null) {
3807            pi = generatePackageInfo(ps.pkg, flags, userId);
3808        } else {
3809            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3810        }
3811        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3812            if (numMatch == permissions.length) {
3813                pi.requestedPermissions = permissions;
3814            } else {
3815                pi.requestedPermissions = new String[numMatch];
3816                numMatch = 0;
3817                for (int i=0; i<permissions.length; i++) {
3818                    if (tmp[i]) {
3819                        pi.requestedPermissions[numMatch] = permissions[i];
3820                        numMatch++;
3821                    }
3822                }
3823            }
3824        }
3825        list.add(pi);
3826    }
3827
3828    @Override
3829    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3830            String[] permissions, int flags, int userId) {
3831        if (!sUserManager.exists(userId)) return null;
3832        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3833
3834        // writer
3835        synchronized (mPackages) {
3836            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3837            boolean[] tmpBools = new boolean[permissions.length];
3838            if (listUninstalled) {
3839                for (PackageSetting ps : mSettings.mPackages.values()) {
3840                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3841                }
3842            } else {
3843                for (PackageParser.Package pkg : mPackages.values()) {
3844                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3845                    if (ps != null) {
3846                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3847                                userId);
3848                    }
3849                }
3850            }
3851
3852            return new ParceledListSlice<PackageInfo>(list);
3853        }
3854    }
3855
3856    @Override
3857    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3858        if (!sUserManager.exists(userId)) return null;
3859        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3860
3861        // writer
3862        synchronized (mPackages) {
3863            ArrayList<ApplicationInfo> list;
3864            if (listUninstalled) {
3865                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3866                for (PackageSetting ps : mSettings.mPackages.values()) {
3867                    ApplicationInfo ai;
3868                    if (ps.pkg != null) {
3869                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3870                                ps.readUserState(userId), userId);
3871                    } else {
3872                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3873                    }
3874                    if (ai != null) {
3875                        list.add(ai);
3876                    }
3877                }
3878            } else {
3879                list = new ArrayList<ApplicationInfo>(mPackages.size());
3880                for (PackageParser.Package p : mPackages.values()) {
3881                    if (p.mExtras != null) {
3882                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3883                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3884                        if (ai != null) {
3885                            list.add(ai);
3886                        }
3887                    }
3888                }
3889            }
3890
3891            return new ParceledListSlice<ApplicationInfo>(list);
3892        }
3893    }
3894
3895    public List<ApplicationInfo> getPersistentApplications(int flags) {
3896        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3897
3898        // reader
3899        synchronized (mPackages) {
3900            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3901            final int userId = UserHandle.getCallingUserId();
3902            while (i.hasNext()) {
3903                final PackageParser.Package p = i.next();
3904                if (p.applicationInfo != null
3905                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3906                        && (!mSafeMode || isSystemApp(p))) {
3907                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3908                    if (ps != null) {
3909                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3910                                ps.readUserState(userId), userId);
3911                        if (ai != null) {
3912                            finalList.add(ai);
3913                        }
3914                    }
3915                }
3916            }
3917        }
3918
3919        return finalList;
3920    }
3921
3922    @Override
3923    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3924        if (!sUserManager.exists(userId)) return null;
3925        // reader
3926        synchronized (mPackages) {
3927            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3928            PackageSetting ps = provider != null
3929                    ? mSettings.mPackages.get(provider.owner.packageName)
3930                    : null;
3931            return ps != null
3932                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3933                    && (!mSafeMode || (provider.info.applicationInfo.flags
3934                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3935                    ? PackageParser.generateProviderInfo(provider, flags,
3936                            ps.readUserState(userId), userId)
3937                    : null;
3938        }
3939    }
3940
3941    /**
3942     * @deprecated
3943     */
3944    @Deprecated
3945    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3946        // reader
3947        synchronized (mPackages) {
3948            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3949                    .entrySet().iterator();
3950            final int userId = UserHandle.getCallingUserId();
3951            while (i.hasNext()) {
3952                Map.Entry<String, PackageParser.Provider> entry = i.next();
3953                PackageParser.Provider p = entry.getValue();
3954                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3955
3956                if (ps != null && p.syncable
3957                        && (!mSafeMode || (p.info.applicationInfo.flags
3958                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3959                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3960                            ps.readUserState(userId), userId);
3961                    if (info != null) {
3962                        outNames.add(entry.getKey());
3963                        outInfo.add(info);
3964                    }
3965                }
3966            }
3967        }
3968    }
3969
3970    @Override
3971    public List<ProviderInfo> queryContentProviders(String processName,
3972            int uid, int flags) {
3973        ArrayList<ProviderInfo> finalList = null;
3974        // reader
3975        synchronized (mPackages) {
3976            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3977            final int userId = processName != null ?
3978                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3979            while (i.hasNext()) {
3980                final PackageParser.Provider p = i.next();
3981                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3982                if (ps != null && p.info.authority != null
3983                        && (processName == null
3984                                || (p.info.processName.equals(processName)
3985                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3986                        && mSettings.isEnabledLPr(p.info, flags, userId)
3987                        && (!mSafeMode
3988                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3989                    if (finalList == null) {
3990                        finalList = new ArrayList<ProviderInfo>(3);
3991                    }
3992                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3993                            ps.readUserState(userId), userId);
3994                    if (info != null) {
3995                        finalList.add(info);
3996                    }
3997                }
3998            }
3999        }
4000
4001        if (finalList != null) {
4002            Collections.sort(finalList, mProviderInitOrderSorter);
4003        }
4004
4005        return finalList;
4006    }
4007
4008    @Override
4009    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4010            int flags) {
4011        // reader
4012        synchronized (mPackages) {
4013            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4014            return PackageParser.generateInstrumentationInfo(i, flags);
4015        }
4016    }
4017
4018    @Override
4019    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4020            int flags) {
4021        ArrayList<InstrumentationInfo> finalList =
4022            new ArrayList<InstrumentationInfo>();
4023
4024        // reader
4025        synchronized (mPackages) {
4026            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4027            while (i.hasNext()) {
4028                final PackageParser.Instrumentation p = i.next();
4029                if (targetPackage == null
4030                        || targetPackage.equals(p.info.targetPackage)) {
4031                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4032                            flags);
4033                    if (ii != null) {
4034                        finalList.add(ii);
4035                    }
4036                }
4037            }
4038        }
4039
4040        return finalList;
4041    }
4042
4043    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4044        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4045        if (overlays == null) {
4046            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4047            return;
4048        }
4049        for (PackageParser.Package opkg : overlays.values()) {
4050            // Not much to do if idmap fails: we already logged the error
4051            // and we certainly don't want to abort installation of pkg simply
4052            // because an overlay didn't fit properly. For these reasons,
4053            // ignore the return value of createIdmapForPackagePairLI.
4054            createIdmapForPackagePairLI(pkg, opkg);
4055        }
4056    }
4057
4058    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4059            PackageParser.Package opkg) {
4060        if (!opkg.mTrustedOverlay) {
4061            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4062                    opkg.baseCodePath + ": overlay not trusted");
4063            return false;
4064        }
4065        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4066        if (overlaySet == null) {
4067            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4068                    opkg.baseCodePath + " but target package has no known overlays");
4069            return false;
4070        }
4071        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4072        // TODO: generate idmap for split APKs
4073        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4074            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4075                    + opkg.baseCodePath);
4076            return false;
4077        }
4078        PackageParser.Package[] overlayArray =
4079            overlaySet.values().toArray(new PackageParser.Package[0]);
4080        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4081            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4082                return p1.mOverlayPriority - p2.mOverlayPriority;
4083            }
4084        };
4085        Arrays.sort(overlayArray, cmp);
4086
4087        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4088        int i = 0;
4089        for (PackageParser.Package p : overlayArray) {
4090            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4091        }
4092        return true;
4093    }
4094
4095    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4096        final File[] files = dir.listFiles();
4097        if (ArrayUtils.isEmpty(files)) {
4098            Log.d(TAG, "No files in app dir " + dir);
4099            return;
4100        }
4101
4102        if (DEBUG_PACKAGE_SCANNING) {
4103            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4104                    + " flags=0x" + Integer.toHexString(flags));
4105        }
4106
4107        for (File file : files) {
4108            final boolean isPackage = isApkFile(file) || file.isDirectory();
4109            if (!isPackage) {
4110                // Ignore entries which are not apk's
4111                continue;
4112            }
4113            try {
4114                scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime,
4115                        null, null);
4116            } catch (PackageManagerException e) {
4117                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4118
4119                // Don't mess around with apps in system partition.
4120                if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4121                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4122                    // Delete the apk
4123                    Slog.w(TAG, "Cleaning up failed install of " + file);
4124                    file.delete();
4125                }
4126            }
4127        }
4128    }
4129
4130    private static File getSettingsProblemFile() {
4131        File dataDir = Environment.getDataDirectory();
4132        File systemDir = new File(dataDir, "system");
4133        File fname = new File(systemDir, "uiderrors.txt");
4134        return fname;
4135    }
4136
4137    static void reportSettingsProblem(int priority, String msg) {
4138        try {
4139            File fname = getSettingsProblemFile();
4140            FileOutputStream out = new FileOutputStream(fname, true);
4141            PrintWriter pw = new FastPrintWriter(out);
4142            SimpleDateFormat formatter = new SimpleDateFormat();
4143            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4144            pw.println(dateString + ": " + msg);
4145            pw.close();
4146            FileUtils.setPermissions(
4147                    fname.toString(),
4148                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4149                    -1, -1);
4150        } catch (java.io.IOException e) {
4151        }
4152        Slog.println(priority, TAG, msg);
4153    }
4154
4155    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4156            PackageParser.Package pkg, File srcFile, int parseFlags)
4157            throws PackageManagerException {
4158        if (ps != null
4159                && ps.codePath.equals(srcFile)
4160                && ps.timeStamp == srcFile.lastModified()
4161                && !isCompatSignatureUpdateNeeded(pkg)) {
4162            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4163            if (ps.signatures.mSignatures != null
4164                    && ps.signatures.mSignatures.length != 0
4165                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4166                // Optimization: reuse the existing cached certificates
4167                // if the package appears to be unchanged.
4168                pkg.mSignatures = ps.signatures.mSignatures;
4169                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4170                synchronized (mPackages) {
4171                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4172                }
4173                return;
4174            }
4175
4176            Slog.w(TAG, "PackageSetting for " + ps.name
4177                    + " is missing signatures.  Collecting certs again to recover them.");
4178        } else {
4179            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4180        }
4181
4182        try {
4183            pp.collectCertificates(pkg, parseFlags);
4184            pp.collectManifestDigest(pkg);
4185        } catch (PackageParserException e) {
4186            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4187                    + pkg.packageName + ": " + e.getMessage());
4188        }
4189    }
4190
4191    /*
4192     *  Scan a package and return the newly parsed package.
4193     *  Returns null in case of errors and the error code is stored in mLastScanError
4194     */
4195    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode,
4196            long currentTime, UserHandle user, String abiOverride) throws PackageManagerException {
4197        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4198        parseFlags |= mDefParseFlags;
4199        PackageParser pp = new PackageParser();
4200        pp.setSeparateProcesses(mSeparateProcesses);
4201        pp.setOnlyCoreApps(mOnlyCore);
4202        pp.setDisplayMetrics(mMetrics);
4203
4204        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4205            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4206        }
4207
4208        final PackageParser.Package pkg;
4209        try {
4210            pkg = pp.parsePackage(scanFile, parseFlags);
4211        } catch (PackageParserException e) {
4212            throw new PackageManagerException(e.error,
4213                    "Failed to scan " + scanFile + ": " + e.getMessage());
4214        }
4215
4216        PackageSetting ps = null;
4217        PackageSetting updatedPkg;
4218        // reader
4219        synchronized (mPackages) {
4220            // Look to see if we already know about this package.
4221            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4222            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4223                // This package has been renamed to its original name.  Let's
4224                // use that.
4225                ps = mSettings.peekPackageLPr(oldName);
4226            }
4227            // If there was no original package, see one for the real package name.
4228            if (ps == null) {
4229                ps = mSettings.peekPackageLPr(pkg.packageName);
4230            }
4231            // Check to see if this package could be hiding/updating a system
4232            // package.  Must look for it either under the original or real
4233            // package name depending on our state.
4234            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4235            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4236        }
4237        boolean updatedPkgBetter = false;
4238        // First check if this is a system package that may involve an update
4239        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4240            if (ps != null && !ps.codePath.equals(scanFile)) {
4241                // The path has changed from what was last scanned...  check the
4242                // version of the new path against what we have stored to determine
4243                // what to do.
4244                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4245                if (pkg.mVersionCode < ps.versionCode) {
4246                    // The system package has been updated and the code path does not match
4247                    // Ignore entry. Skip it.
4248                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4249                            + " ignored: updated version " + ps.versionCode
4250                            + " better than this " + pkg.mVersionCode);
4251                    if (!updatedPkg.codePath.equals(scanFile)) {
4252                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4253                                + ps.name + " changing from " + updatedPkg.codePathString
4254                                + " to " + scanFile);
4255                        updatedPkg.codePath = scanFile;
4256                        updatedPkg.codePathString = scanFile.toString();
4257                        // This is the point at which we know that the system-disk APK
4258                        // for this package has moved during a reboot (e.g. due to an OTA),
4259                        // so we need to reevaluate it for privilege policy.
4260                        if (locationIsPrivileged(scanFile)) {
4261                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4262                        }
4263                    }
4264                    updatedPkg.pkg = pkg;
4265                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4266                } else {
4267                    // The current app on the system partition is better than
4268                    // what we have updated to on the data partition; switch
4269                    // back to the system partition version.
4270                    // At this point, its safely assumed that package installation for
4271                    // apps in system partition will go through. If not there won't be a working
4272                    // version of the app
4273                    // writer
4274                    synchronized (mPackages) {
4275                        // Just remove the loaded entries from package lists.
4276                        mPackages.remove(ps.name);
4277                    }
4278                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4279                            + "reverting from " + ps.codePathString
4280                            + ": new version " + pkg.mVersionCode
4281                            + " better than installed " + ps.versionCode);
4282
4283                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4284                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4285                            getAppDexInstructionSets(ps), isMultiArch(ps));
4286                    synchronized (mInstallLock) {
4287                        args.cleanUpResourcesLI();
4288                    }
4289                    synchronized (mPackages) {
4290                        mSettings.enableSystemPackageLPw(ps.name);
4291                    }
4292                    updatedPkgBetter = true;
4293                }
4294            }
4295        }
4296
4297        if (updatedPkg != null) {
4298            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4299            // initially
4300            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4301
4302            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4303            // flag set initially
4304            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4305                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4306            }
4307        }
4308
4309        // Verify certificates against what was last scanned
4310        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4311
4312        /*
4313         * A new system app appeared, but we already had a non-system one of the
4314         * same name installed earlier.
4315         */
4316        boolean shouldHideSystemApp = false;
4317        if (updatedPkg == null && ps != null
4318                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4319            /*
4320             * Check to make sure the signatures match first. If they don't,
4321             * wipe the installed application and its data.
4322             */
4323            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4324                    != PackageManager.SIGNATURE_MATCH) {
4325                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4326                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4327                ps = null;
4328            } else {
4329                /*
4330                 * If the newly-added system app is an older version than the
4331                 * already installed version, hide it. It will be scanned later
4332                 * and re-added like an update.
4333                 */
4334                if (pkg.mVersionCode < ps.versionCode) {
4335                    shouldHideSystemApp = true;
4336                } else {
4337                    /*
4338                     * The newly found system app is a newer version that the
4339                     * one previously installed. Simply remove the
4340                     * already-installed application and replace it with our own
4341                     * while keeping the application data.
4342                     */
4343                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4344                            + ps.codePathString + ": new version " + pkg.mVersionCode
4345                            + " better than installed " + ps.versionCode);
4346                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4347                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4348                            getAppDexInstructionSets(ps), isMultiArch(ps));
4349                    synchronized (mInstallLock) {
4350                        args.cleanUpResourcesLI();
4351                    }
4352                }
4353            }
4354        }
4355
4356        // The apk is forward locked (not public) if its code and resources
4357        // are kept in different files. (except for app in either system or
4358        // vendor path).
4359        // TODO grab this value from PackageSettings
4360        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4361            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4362                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4363            }
4364        }
4365
4366        // TODO: extend to support forward-locked splits
4367        String resourcePath = null;
4368        String baseResourcePath = null;
4369        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4370            if (ps != null && ps.resourcePathString != null) {
4371                resourcePath = ps.resourcePathString;
4372                baseResourcePath = ps.resourcePathString;
4373            } else {
4374                // Should not happen at all. Just log an error.
4375                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4376            }
4377        } else {
4378            resourcePath = pkg.codePath;
4379            baseResourcePath = pkg.baseCodePath;
4380        }
4381
4382        // Set application objects path explicitly.
4383        pkg.applicationInfo.setCodePath(pkg.codePath);
4384        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4385        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4386        pkg.applicationInfo.setResourcePath(resourcePath);
4387        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4388        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4389
4390        // Note that we invoke the following method only if we are about to unpack an application
4391        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4392                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4393
4394        /*
4395         * If the system app should be overridden by a previously installed
4396         * data, hide the system app now and let the /data/app scan pick it up
4397         * again.
4398         */
4399        if (shouldHideSystemApp) {
4400            synchronized (mPackages) {
4401                /*
4402                 * We have to grant systems permissions before we hide, because
4403                 * grantPermissions will assume the package update is trying to
4404                 * expand its permissions.
4405                 */
4406                grantPermissionsLPw(pkg, true);
4407                mSettings.disableSystemPackageLPw(pkg.packageName);
4408            }
4409        }
4410
4411        return scannedPkg;
4412    }
4413
4414    private static String fixProcessName(String defProcessName,
4415            String processName, int uid) {
4416        if (processName == null) {
4417            return defProcessName;
4418        }
4419        return processName;
4420    }
4421
4422    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4423            throws PackageManagerException {
4424        if (pkgSetting.signatures.mSignatures != null) {
4425            // Already existing package. Make sure signatures match
4426            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4427                    == PackageManager.SIGNATURE_MATCH;
4428            if (!match) {
4429                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4430                        == PackageManager.SIGNATURE_MATCH;
4431            }
4432            if (!match) {
4433                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4434                        + pkg.packageName + " signatures do not match the "
4435                        + "previously installed version; ignoring!");
4436            }
4437        }
4438
4439        // Check for shared user signatures
4440        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4441            // Already existing package. Make sure signatures match
4442            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4443                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4444            if (!match) {
4445                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4446                        == PackageManager.SIGNATURE_MATCH;
4447            }
4448            if (!match) {
4449                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4450                        "Package " + pkg.packageName
4451                        + " has no signatures that match those in shared user "
4452                        + pkgSetting.sharedUser.name + "; ignoring!");
4453            }
4454        }
4455    }
4456
4457    /**
4458     * Enforces that only the system UID or root's UID can call a method exposed
4459     * via Binder.
4460     *
4461     * @param message used as message if SecurityException is thrown
4462     * @throws SecurityException if the caller is not system or root
4463     */
4464    private static final void enforceSystemOrRoot(String message) {
4465        final int uid = Binder.getCallingUid();
4466        if (uid != Process.SYSTEM_UID && uid != 0) {
4467            throw new SecurityException(message);
4468        }
4469    }
4470
4471    @Override
4472    public void performBootDexOpt() {
4473        enforceSystemOrRoot("Only the system can request dexopt be performed");
4474
4475        final HashSet<PackageParser.Package> pkgs;
4476        synchronized (mPackages) {
4477            pkgs = mDeferredDexOpt;
4478            mDeferredDexOpt = null;
4479        }
4480
4481        if (pkgs != null) {
4482            // Filter out packages that aren't recently used.
4483            //
4484            // The exception is first boot of a non-eng device, which
4485            // should do a full dexopt.
4486            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4487            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4488                // TODO: add a property to control this?
4489                long dexOptLRUThresholdInMinutes;
4490                if (eng) {
4491                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4492                } else {
4493                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4494                }
4495                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4496
4497                int total = pkgs.size();
4498                int skipped = 0;
4499                long now = System.currentTimeMillis();
4500                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4501                    PackageParser.Package pkg = i.next();
4502                    long then = pkg.mLastPackageUsageTimeInMills;
4503                    if (then + dexOptLRUThresholdInMills < now) {
4504                        if (DEBUG_DEXOPT) {
4505                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4506                                  ((then == 0) ? "never" : new Date(then)));
4507                        }
4508                        i.remove();
4509                        skipped++;
4510                    }
4511                }
4512                if (DEBUG_DEXOPT) {
4513                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4514                }
4515            }
4516
4517            int i = 0;
4518            for (PackageParser.Package pkg : pkgs) {
4519                i++;
4520                if (DEBUG_DEXOPT) {
4521                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4522                          + ": " + pkg.packageName);
4523                }
4524                if (!isFirstBoot()) {
4525                    try {
4526                        ActivityManagerNative.getDefault().showBootMessage(
4527                                mContext.getResources().getString(
4528                                        R.string.android_upgrading_apk,
4529                                        i, pkgs.size()), true);
4530                    } catch (RemoteException e) {
4531                    }
4532                }
4533                PackageParser.Package p = pkg;
4534                synchronized (mInstallLock) {
4535                    if (p.mDexOptNeeded) {
4536                        performDexOptLI(p, false /* force dex */, false /* defer */,
4537                                true /* include dependencies */);
4538                    }
4539                }
4540            }
4541        }
4542    }
4543
4544    @Override
4545    public boolean performDexOpt(String packageName) {
4546        enforceSystemOrRoot("Only the system can request dexopt be performed");
4547        return performDexOpt(packageName, true);
4548    }
4549
4550    public boolean performDexOpt(String packageName, boolean updateUsage) {
4551
4552        PackageParser.Package p;
4553        synchronized (mPackages) {
4554            p = mPackages.get(packageName);
4555            if (p == null) {
4556                return false;
4557            }
4558            if (updateUsage) {
4559                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4560            }
4561            mPackageUsage.write(false);
4562            if (!p.mDexOptNeeded) {
4563                return false;
4564            }
4565        }
4566
4567        synchronized (mInstallLock) {
4568            return performDexOptLI(p, false /* force dex */, false /* defer */,
4569                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4570        }
4571    }
4572
4573    public HashSet<String> getPackagesThatNeedDexOpt() {
4574        HashSet<String> pkgs = null;
4575        synchronized (mPackages) {
4576            for (PackageParser.Package p : mPackages.values()) {
4577                if (DEBUG_DEXOPT) {
4578                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4579                }
4580                if (!p.mDexOptNeeded) {
4581                    continue;
4582                }
4583                if (pkgs == null) {
4584                    pkgs = new HashSet<String>();
4585                }
4586                pkgs.add(p.packageName);
4587            }
4588        }
4589        return pkgs;
4590    }
4591
4592    public void shutdown() {
4593        mPackageUsage.write(true);
4594    }
4595
4596    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4597             boolean forceDex, boolean defer, HashSet<String> done) {
4598        for (int i=0; i<libs.size(); i++) {
4599            PackageParser.Package libPkg;
4600            String libName;
4601            synchronized (mPackages) {
4602                libName = libs.get(i);
4603                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4604                if (lib != null && lib.apk != null) {
4605                    libPkg = mPackages.get(lib.apk);
4606                } else {
4607                    libPkg = null;
4608                }
4609            }
4610            if (libPkg != null && !done.contains(libName)) {
4611                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4612            }
4613        }
4614    }
4615
4616    static final int DEX_OPT_SKIPPED = 0;
4617    static final int DEX_OPT_PERFORMED = 1;
4618    static final int DEX_OPT_DEFERRED = 2;
4619    static final int DEX_OPT_FAILED = -1;
4620
4621    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4622            boolean forceDex, boolean defer, HashSet<String> done) {
4623        final String[] instructionSets = targetInstructionSets != null ?
4624                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4625
4626        if (done != null) {
4627            done.add(pkg.packageName);
4628            if (pkg.usesLibraries != null) {
4629                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4630            }
4631            if (pkg.usesOptionalLibraries != null) {
4632                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4633            }
4634        }
4635
4636        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4637            return DEX_OPT_SKIPPED;
4638        }
4639
4640        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4641        boolean performedDexOpt = false;
4642        // There are three basic cases here:
4643        // 1.) we need to dexopt, either because we are forced or it is needed
4644        // 2.) we are defering a needed dexopt
4645        // 3.) we are skipping an unneeded dexopt
4646        for (String path : paths) {
4647            for (String instructionSet : instructionSets) {
4648                try {
4649                    final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4650                            pkg.packageName, instructionSet, defer);
4651                    if (forceDex || (!defer && isDexOptNeeded)) {
4652                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4653                                + pkg.applicationInfo.packageName + " isa=" + instructionSet);
4654                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4655                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4656                                pkg.packageName, instructionSet);
4657
4658                        if (ret < 0) {
4659                            // Don't bother running dexopt again if we failed, it will probably
4660                            // just result in an error again. Also, don't bother dexopting for other
4661                            // paths & ISAs.
4662                            pkg.mDexOptNeeded = false;
4663                            return DEX_OPT_FAILED;
4664                        } else {
4665                            performedDexOpt = true;
4666                        }
4667                    }
4668
4669                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4670                    // paths and instruction sets. We'll deal with them all together when we process
4671                    // our list of deferred dexopts.
4672                    if (defer && isDexOptNeeded) {
4673                        if (mDeferredDexOpt == null) {
4674                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4675                        }
4676                        mDeferredDexOpt.add(pkg);
4677                        return DEX_OPT_DEFERRED;
4678                    }
4679                } catch (FileNotFoundException e) {
4680                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4681                    return DEX_OPT_FAILED;
4682                } catch (IOException e) {
4683                    Slog.w(TAG, "IOException reading apk: " + path, e);
4684                    return DEX_OPT_FAILED;
4685                } catch (StaleDexCacheError e) {
4686                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4687                    return DEX_OPT_FAILED;
4688                } catch (Exception e) {
4689                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4690                    return DEX_OPT_FAILED;
4691                }
4692            }
4693        }
4694
4695        // If we've gotten here, we're sure that no error occurred and that we haven't
4696        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4697        // we've skipped all of them because they are up to date. In both cases this
4698        // package doesn't need dexopt any longer.
4699        pkg.mDexOptNeeded = false;
4700        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4701    }
4702
4703    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4704        if (info.primaryCpuAbi != null) {
4705            if (info.secondaryCpuAbi != null) {
4706                return new String[] {
4707                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4708                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4709            } else {
4710                return new String[] {
4711                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4712            }
4713        }
4714
4715        return new String[] { getPreferredInstructionSet() };
4716    }
4717
4718    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4719        if (ps.primaryCpuAbiString != null) {
4720            if (ps.secondaryCpuAbiString != null) {
4721                return new String[] {
4722                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4723                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4724            } else {
4725                return new String[] {
4726                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4727            }
4728        }
4729
4730        return new String[] { getPreferredInstructionSet() };
4731    }
4732
4733    private static String getPreferredInstructionSet() {
4734        if (sPreferredInstructionSet == null) {
4735            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4736        }
4737
4738        return sPreferredInstructionSet;
4739    }
4740
4741    private static List<String> getAllInstructionSets() {
4742        final String[] allAbis = Build.SUPPORTED_ABIS;
4743        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4744
4745        for (String abi : allAbis) {
4746            final String instructionSet = VMRuntime.getInstructionSet(abi);
4747            if (!allInstructionSets.contains(instructionSet)) {
4748                allInstructionSets.add(instructionSet);
4749            }
4750        }
4751
4752        return allInstructionSets;
4753    }
4754
4755    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4756            boolean inclDependencies) {
4757        HashSet<String> done;
4758        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4759            done = new HashSet<String>();
4760            done.add(pkg.packageName);
4761        } else {
4762            done = null;
4763        }
4764        return performDexOptLI(pkg, null /* target instruction sets */,  forceDex, defer, done);
4765    }
4766
4767    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4768        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4769            Slog.w(TAG, "Unable to update from " + oldPkg.name
4770                    + " to " + newPkg.packageName
4771                    + ": old package not in system partition");
4772            return false;
4773        } else if (mPackages.get(oldPkg.name) != null) {
4774            Slog.w(TAG, "Unable to update from " + oldPkg.name
4775                    + " to " + newPkg.packageName
4776                    + ": old package still exists");
4777            return false;
4778        }
4779        return true;
4780    }
4781
4782    File getDataPathForUser(int userId) {
4783        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4784    }
4785
4786    private File getDataPathForPackage(String packageName, int userId) {
4787        /*
4788         * Until we fully support multiple users, return the directory we
4789         * previously would have. The PackageManagerTests will need to be
4790         * revised when this is changed back..
4791         */
4792        if (userId == 0) {
4793            return new File(mAppDataDir, packageName);
4794        } else {
4795            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4796                + File.separator + packageName);
4797        }
4798    }
4799
4800    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4801        int[] users = sUserManager.getUserIds();
4802        int res = mInstaller.install(packageName, uid, uid, seinfo);
4803        if (res < 0) {
4804            return res;
4805        }
4806        for (int user : users) {
4807            if (user != 0) {
4808                res = mInstaller.createUserData(packageName,
4809                        UserHandle.getUid(user, uid), user, seinfo);
4810                if (res < 0) {
4811                    return res;
4812                }
4813            }
4814        }
4815        return res;
4816    }
4817
4818    private int removeDataDirsLI(String packageName) {
4819        int[] users = sUserManager.getUserIds();
4820        int res = 0;
4821        for (int user : users) {
4822            int resInner = mInstaller.remove(packageName, user);
4823            if (resInner < 0) {
4824                res = resInner;
4825            }
4826        }
4827
4828        return res;
4829    }
4830
4831    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4832            PackageParser.Package changingLib) {
4833        if (file.path != null) {
4834            usesLibraryFiles.add(file.path);
4835            return;
4836        }
4837        PackageParser.Package p = mPackages.get(file.apk);
4838        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4839            // If we are doing this while in the middle of updating a library apk,
4840            // then we need to make sure to use that new apk for determining the
4841            // dependencies here.  (We haven't yet finished committing the new apk
4842            // to the package manager state.)
4843            if (p == null || p.packageName.equals(changingLib.packageName)) {
4844                p = changingLib;
4845            }
4846        }
4847        if (p != null) {
4848            usesLibraryFiles.addAll(p.getAllCodePaths());
4849        }
4850    }
4851
4852    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4853            PackageParser.Package changingLib) throws PackageManagerException {
4854        // We might be upgrading from a version of the platform that did not
4855        // provide per-package native library directories for system apps.
4856        // Fix that up here.
4857        if (isSystemApp(pkg)) {
4858            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4859            if (!isUpdatedSystemApp(pkg)) {
4860                setBundledAppAbisAndRoots(pkg, ps);
4861            }
4862        }
4863
4864        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4865            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4866            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4867            for (int i=0; i<N; i++) {
4868                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4869                if (file == null) {
4870                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4871                            "Package " + pkg.packageName + " requires unavailable shared library "
4872                            + pkg.usesLibraries.get(i) + "; failing!");
4873                }
4874                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4875            }
4876            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4877            for (int i=0; i<N; i++) {
4878                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4879                if (file == null) {
4880                    Slog.w(TAG, "Package " + pkg.packageName
4881                            + " desires unavailable shared library "
4882                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4883                } else {
4884                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4885                }
4886            }
4887            N = usesLibraryFiles.size();
4888            if (N > 0) {
4889                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4890            } else {
4891                pkg.usesLibraryFiles = null;
4892            }
4893        }
4894    }
4895
4896    private static boolean hasString(List<String> list, List<String> which) {
4897        if (list == null) {
4898            return false;
4899        }
4900        for (int i=list.size()-1; i>=0; i--) {
4901            for (int j=which.size()-1; j>=0; j--) {
4902                if (which.get(j).equals(list.get(i))) {
4903                    return true;
4904                }
4905            }
4906        }
4907        return false;
4908    }
4909
4910    private void updateAllSharedLibrariesLPw() {
4911        for (PackageParser.Package pkg : mPackages.values()) {
4912            try {
4913                updateSharedLibrariesLPw(pkg, null);
4914            } catch (PackageManagerException e) {
4915                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4916            }
4917        }
4918    }
4919
4920    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4921            PackageParser.Package changingPkg) {
4922        ArrayList<PackageParser.Package> res = null;
4923        for (PackageParser.Package pkg : mPackages.values()) {
4924            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4925                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4926                if (res == null) {
4927                    res = new ArrayList<PackageParser.Package>();
4928                }
4929                res.add(pkg);
4930                try {
4931                    updateSharedLibrariesLPw(pkg, changingPkg);
4932                } catch (PackageManagerException e) {
4933                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4934                }
4935            }
4936        }
4937        return res;
4938    }
4939
4940    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4941            int scanMode, long currentTime, UserHandle user, String abiOverride)
4942            throws PackageManagerException {
4943        final File scanFile = new File(pkg.codePath);
4944        if (pkg.applicationInfo.getCodePath() == null ||
4945                pkg.applicationInfo.getResourcePath() == null) {
4946            // Bail out. The resource and code paths haven't been set.
4947            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4948                    "Code and resource paths haven't been set correctly");
4949        }
4950
4951        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4952            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4953        }
4954
4955        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4956            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4957        }
4958
4959        if (mCustomResolverComponentName != null &&
4960                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4961            setUpCustomResolverActivity(pkg);
4962        }
4963
4964        if (pkg.packageName.equals("android")) {
4965            synchronized (mPackages) {
4966                if (mAndroidApplication != null) {
4967                    Slog.w(TAG, "*************************************************");
4968                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4969                    Slog.w(TAG, " file=" + scanFile);
4970                    Slog.w(TAG, "*************************************************");
4971                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
4972                            "Core android package being redefined.  Skipping.");
4973                }
4974
4975                // Set up information for our fall-back user intent resolution activity.
4976                mPlatformPackage = pkg;
4977                pkg.mVersionCode = mSdkVersion;
4978                mAndroidApplication = pkg.applicationInfo;
4979
4980                if (!mResolverReplaced) {
4981                    mResolveActivity.applicationInfo = mAndroidApplication;
4982                    mResolveActivity.name = ResolverActivity.class.getName();
4983                    mResolveActivity.packageName = mAndroidApplication.packageName;
4984                    mResolveActivity.processName = "system:ui";
4985                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4986                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4987                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4988                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4989                    mResolveActivity.exported = true;
4990                    mResolveActivity.enabled = true;
4991                    mResolveInfo.activityInfo = mResolveActivity;
4992                    mResolveInfo.priority = 0;
4993                    mResolveInfo.preferredOrder = 0;
4994                    mResolveInfo.match = 0;
4995                    mResolveComponentName = new ComponentName(
4996                            mAndroidApplication.packageName, mResolveActivity.name);
4997                }
4998            }
4999        }
5000
5001        if (DEBUG_PACKAGE_SCANNING) {
5002            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5003                Log.d(TAG, "Scanning package " + pkg.packageName);
5004        }
5005
5006        if (mPackages.containsKey(pkg.packageName)
5007                || mSharedLibraries.containsKey(pkg.packageName)) {
5008            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5009                    "Application package " + pkg.packageName
5010                    + " already installed.  Skipping duplicate.");
5011        }
5012
5013        // Initialize package source and resource directories
5014        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5015        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5016
5017        SharedUserSetting suid = null;
5018        PackageSetting pkgSetting = null;
5019
5020        if (!isSystemApp(pkg)) {
5021            // Only system apps can use these features.
5022            pkg.mOriginalPackages = null;
5023            pkg.mRealPackage = null;
5024            pkg.mAdoptPermissions = null;
5025        }
5026
5027        // writer
5028        synchronized (mPackages) {
5029            if (pkg.mSharedUserId != null) {
5030                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5031                if (suid == null) {
5032                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5033                            "Creating application package " + pkg.packageName
5034                            + " for shared user failed");
5035                }
5036                if (DEBUG_PACKAGE_SCANNING) {
5037                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5038                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5039                                + "): packages=" + suid.packages);
5040                }
5041            }
5042
5043            // Check if we are renaming from an original package name.
5044            PackageSetting origPackage = null;
5045            String realName = null;
5046            if (pkg.mOriginalPackages != null) {
5047                // This package may need to be renamed to a previously
5048                // installed name.  Let's check on that...
5049                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5050                if (pkg.mOriginalPackages.contains(renamed)) {
5051                    // This package had originally been installed as the
5052                    // original name, and we have already taken care of
5053                    // transitioning to the new one.  Just update the new
5054                    // one to continue using the old name.
5055                    realName = pkg.mRealPackage;
5056                    if (!pkg.packageName.equals(renamed)) {
5057                        // Callers into this function may have already taken
5058                        // care of renaming the package; only do it here if
5059                        // it is not already done.
5060                        pkg.setPackageName(renamed);
5061                    }
5062
5063                } else {
5064                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5065                        if ((origPackage = mSettings.peekPackageLPr(
5066                                pkg.mOriginalPackages.get(i))) != null) {
5067                            // We do have the package already installed under its
5068                            // original name...  should we use it?
5069                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5070                                // New package is not compatible with original.
5071                                origPackage = null;
5072                                continue;
5073                            } else if (origPackage.sharedUser != null) {
5074                                // Make sure uid is compatible between packages.
5075                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5076                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5077                                            + " to " + pkg.packageName + ": old uid "
5078                                            + origPackage.sharedUser.name
5079                                            + " differs from " + pkg.mSharedUserId);
5080                                    origPackage = null;
5081                                    continue;
5082                                }
5083                            } else {
5084                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5085                                        + pkg.packageName + " to old name " + origPackage.name);
5086                            }
5087                            break;
5088                        }
5089                    }
5090                }
5091            }
5092
5093            if (mTransferedPackages.contains(pkg.packageName)) {
5094                Slog.w(TAG, "Package " + pkg.packageName
5095                        + " was transferred to another, but its .apk remains");
5096            }
5097
5098            // Just create the setting, don't add it yet. For already existing packages
5099            // the PkgSetting exists already and doesn't have to be created.
5100            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5101                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5102                    pkg.applicationInfo.primaryCpuAbi,
5103                    pkg.applicationInfo.secondaryCpuAbi,
5104                    pkg.applicationInfo.flags, user, false);
5105            if (pkgSetting == null) {
5106                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5107                        "Creating application package " + pkg.packageName + " failed");
5108            }
5109
5110            if (pkgSetting.origPackage != null) {
5111                // If we are first transitioning from an original package,
5112                // fix up the new package's name now.  We need to do this after
5113                // looking up the package under its new name, so getPackageLP
5114                // can take care of fiddling things correctly.
5115                pkg.setPackageName(origPackage.name);
5116
5117                // File a report about this.
5118                String msg = "New package " + pkgSetting.realName
5119                        + " renamed to replace old package " + pkgSetting.name;
5120                reportSettingsProblem(Log.WARN, msg);
5121
5122                // Make a note of it.
5123                mTransferedPackages.add(origPackage.name);
5124
5125                // No longer need to retain this.
5126                pkgSetting.origPackage = null;
5127            }
5128
5129            if (realName != null) {
5130                // Make a note of it.
5131                mTransferedPackages.add(pkg.packageName);
5132            }
5133
5134            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5135                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5136            }
5137
5138            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5139                // Check all shared libraries and map to their actual file path.
5140                // We only do this here for apps not on a system dir, because those
5141                // are the only ones that can fail an install due to this.  We
5142                // will take care of the system apps by updating all of their
5143                // library paths after the scan is done.
5144                updateSharedLibrariesLPw(pkg, null);
5145            }
5146
5147            if (mFoundPolicyFile) {
5148                SELinuxMMAC.assignSeinfoValue(pkg);
5149            }
5150
5151            pkg.applicationInfo.uid = pkgSetting.appId;
5152            pkg.mExtras = pkgSetting;
5153            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5154                try {
5155                    verifySignaturesLP(pkgSetting, pkg);
5156                } catch (PackageManagerException e) {
5157                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5158                        throw e;
5159                    }
5160                    // The signature has changed, but this package is in the system
5161                    // image...  let's recover!
5162                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5163                    // However...  if this package is part of a shared user, but it
5164                    // doesn't match the signature of the shared user, let's fail.
5165                    // What this means is that you can't change the signatures
5166                    // associated with an overall shared user, which doesn't seem all
5167                    // that unreasonable.
5168                    if (pkgSetting.sharedUser != null) {
5169                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5170                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5171                            throw new PackageManagerException(
5172                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5173                                            "Signature mismatch for shared user : "
5174                                            + pkgSetting.sharedUser);
5175                        }
5176                    }
5177                    // File a report about this.
5178                    String msg = "System package " + pkg.packageName
5179                        + " signature changed; retaining data.";
5180                    reportSettingsProblem(Log.WARN, msg);
5181                }
5182            } else {
5183                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5184                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5185                            + pkg.packageName + " upgrade keys do not match the "
5186                            + "previously installed version");
5187                } else {
5188                    // signatures may have changed as result of upgrade
5189                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5190                }
5191            }
5192            // Verify that this new package doesn't have any content providers
5193            // that conflict with existing packages.  Only do this if the
5194            // package isn't already installed, since we don't want to break
5195            // things that are installed.
5196            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5197                final int N = pkg.providers.size();
5198                int i;
5199                for (i=0; i<N; i++) {
5200                    PackageParser.Provider p = pkg.providers.get(i);
5201                    if (p.info.authority != null) {
5202                        String names[] = p.info.authority.split(";");
5203                        for (int j = 0; j < names.length; j++) {
5204                            if (mProvidersByAuthority.containsKey(names[j])) {
5205                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5206                                final String otherPackageName =
5207                                        ((other != null && other.getComponentName() != null) ?
5208                                                other.getComponentName().getPackageName() : "?");
5209                                throw new PackageManagerException(
5210                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5211                                                "Can't install because provider name " + names[j]
5212                                                + " (in package " + pkg.applicationInfo.packageName
5213                                                + ") is already used by " + otherPackageName);
5214                            }
5215                        }
5216                    }
5217                }
5218            }
5219
5220            if (pkg.mAdoptPermissions != null) {
5221                // This package wants to adopt ownership of permissions from
5222                // another package.
5223                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5224                    final String origName = pkg.mAdoptPermissions.get(i);
5225                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5226                    if (orig != null) {
5227                        if (verifyPackageUpdateLPr(orig, pkg)) {
5228                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5229                                    + pkg.packageName);
5230                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5231                        }
5232                    }
5233                }
5234            }
5235        }
5236
5237        final String pkgName = pkg.packageName;
5238
5239        final long scanFileTime = scanFile.lastModified();
5240        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5241        pkg.applicationInfo.processName = fixProcessName(
5242                pkg.applicationInfo.packageName,
5243                pkg.applicationInfo.processName,
5244                pkg.applicationInfo.uid);
5245
5246        File dataPath;
5247        if (mPlatformPackage == pkg) {
5248            // The system package is special.
5249            dataPath = new File (Environment.getDataDirectory(), "system");
5250            pkg.applicationInfo.dataDir = dataPath.getPath();
5251        } else {
5252            // This is a normal package, need to make its data directory.
5253            dataPath = getDataPathForPackage(pkg.packageName, 0);
5254
5255            boolean uidError = false;
5256
5257            if (dataPath.exists()) {
5258                int currentUid = 0;
5259                try {
5260                    StructStat stat = Os.stat(dataPath.getPath());
5261                    currentUid = stat.st_uid;
5262                } catch (ErrnoException e) {
5263                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5264                }
5265
5266                // If we have mismatched owners for the data path, we have a problem.
5267                if (currentUid != pkg.applicationInfo.uid) {
5268                    boolean recovered = false;
5269                    if (currentUid == 0) {
5270                        // The directory somehow became owned by root.  Wow.
5271                        // This is probably because the system was stopped while
5272                        // installd was in the middle of messing with its libs
5273                        // directory.  Ask installd to fix that.
5274                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5275                                pkg.applicationInfo.uid);
5276                        if (ret >= 0) {
5277                            recovered = true;
5278                            String msg = "Package " + pkg.packageName
5279                                    + " unexpectedly changed to uid 0; recovered to " +
5280                                    + pkg.applicationInfo.uid;
5281                            reportSettingsProblem(Log.WARN, msg);
5282                        }
5283                    }
5284                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5285                            || (scanMode&SCAN_BOOTING) != 0)) {
5286                        // If this is a system app, we can at least delete its
5287                        // current data so the application will still work.
5288                        int ret = removeDataDirsLI(pkgName);
5289                        if (ret >= 0) {
5290                            // TODO: Kill the processes first
5291                            // Old data gone!
5292                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5293                                    ? "System package " : "Third party package ";
5294                            String msg = prefix + pkg.packageName
5295                                    + " has changed from uid: "
5296                                    + currentUid + " to "
5297                                    + pkg.applicationInfo.uid + "; old data erased";
5298                            reportSettingsProblem(Log.WARN, msg);
5299                            recovered = true;
5300
5301                            // And now re-install the app.
5302                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5303                                                   pkg.applicationInfo.seinfo);
5304                            if (ret == -1) {
5305                                // Ack should not happen!
5306                                msg = prefix + pkg.packageName
5307                                        + " could not have data directory re-created after delete.";
5308                                reportSettingsProblem(Log.WARN, msg);
5309                                throw new PackageManagerException(
5310                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5311                            }
5312                        }
5313                        if (!recovered) {
5314                            mHasSystemUidErrors = true;
5315                        }
5316                    } else if (!recovered) {
5317                        // If we allow this install to proceed, we will be broken.
5318                        // Abort, abort!
5319                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5320                                "scanPackageLI");
5321                    }
5322                    if (!recovered) {
5323                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5324                            + pkg.applicationInfo.uid + "/fs_"
5325                            + currentUid;
5326                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5327                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5328                        String msg = "Package " + pkg.packageName
5329                                + " has mismatched uid: "
5330                                + currentUid + " on disk, "
5331                                + pkg.applicationInfo.uid + " in settings";
5332                        // writer
5333                        synchronized (mPackages) {
5334                            mSettings.mReadMessages.append(msg);
5335                            mSettings.mReadMessages.append('\n');
5336                            uidError = true;
5337                            if (!pkgSetting.uidError) {
5338                                reportSettingsProblem(Log.ERROR, msg);
5339                            }
5340                        }
5341                    }
5342                }
5343                pkg.applicationInfo.dataDir = dataPath.getPath();
5344                if (mShouldRestoreconData) {
5345                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5346                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5347                                pkg.applicationInfo.uid);
5348                }
5349            } else {
5350                if (DEBUG_PACKAGE_SCANNING) {
5351                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5352                        Log.v(TAG, "Want this data dir: " + dataPath);
5353                }
5354                //invoke installer to do the actual installation
5355                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5356                                           pkg.applicationInfo.seinfo);
5357                if (ret < 0) {
5358                    // Error from installer
5359                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5360                            "Unable to create data dirs [errorCode=" + ret + "]");
5361                }
5362
5363                if (dataPath.exists()) {
5364                    pkg.applicationInfo.dataDir = dataPath.getPath();
5365                } else {
5366                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5367                    pkg.applicationInfo.dataDir = null;
5368                }
5369            }
5370
5371            pkgSetting.uidError = uidError;
5372        }
5373
5374        final String path = scanFile.getPath();
5375        final String codePath = pkg.applicationInfo.getCodePath();
5376        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5377            // For the case where we had previously uninstalled an update, get rid
5378            // of any native binaries we might have unpackaged. Note that this assumes
5379            // that system app updates were not installed via ASEC.
5380            //
5381            // TODO(multiArch): Is this cleanup really necessary ?
5382            NativeLibraryHelper.removeNativeBinariesFromDirLI(
5383                    new File(codePath, LIB_DIR_NAME), false /* delete dirs */);
5384            setBundledAppAbisAndRoots(pkg, pkgSetting);
5385            setNativeLibraryPaths(pkg);
5386        } else {
5387            // TODO: We can probably be smarter about this stuff. For installed apps,
5388            // we can calculate this information at install time once and for all. For
5389            // system apps, we can probably assume that this information doesn't change
5390            // after the first boot scan. As things stand, we do lots of unnecessary work.
5391
5392            // Give ourselves some initial paths; we'll come back for another
5393            // pass once we've determined ABI below.
5394            setNativeLibraryPaths(pkg);
5395
5396            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5397            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5398            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5399
5400            NativeLibraryHelper.Handle handle = null;
5401            try {
5402                handle = NativeLibraryHelper.Handle.create(scanFile);
5403                // TODO(multiArch): This can be null for apps that didn't go through the
5404                // usual installation process. We can calculate it again, like we
5405                // do during install time.
5406                //
5407                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5408                // unnecessary.
5409                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5410
5411                // Null out the abis so that they can be recalculated.
5412                pkg.applicationInfo.primaryCpuAbi = null;
5413                pkg.applicationInfo.secondaryCpuAbi = null;
5414                if (isMultiArch(pkg.applicationInfo)) {
5415                    // Warn if we've set an abiOverride for multi-lib packages..
5416                    // By definition, we need to copy both 32 and 64 bit libraries for
5417                    // such packages.
5418                    if (abiOverride != null) {
5419                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5420                    }
5421
5422                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5423                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5424                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5425                        if (isAsec) {
5426                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5427                        } else {
5428                            abi32 = copyNativeLibrariesForInternalApp(handle,
5429                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs);
5430                        }
5431                    }
5432
5433                    maybeThrowExceptionForMultiArchCopy(
5434                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5435
5436                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5437                        if (isAsec) {
5438                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5439                        } else {
5440                            abi64 = copyNativeLibrariesForInternalApp(handle,
5441                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs);
5442                        }
5443                    }
5444
5445                    maybeThrowExceptionForMultiArchCopy(
5446                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5447
5448                    if (abi64 >= 0) {
5449                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5450                    }
5451
5452                    if (abi32 >= 0) {
5453                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5454                        if (abi64 >= 0) {
5455                            pkg.applicationInfo.secondaryCpuAbi = abi;
5456                        } else {
5457                            pkg.applicationInfo.primaryCpuAbi = abi;
5458                        }
5459                    }
5460                } else {
5461                    String[] abiList = (abiOverride != null) ?
5462                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
5463
5464                    // Enable gross and lame hacks for apps that are built with old
5465                    // SDK tools. We must scan their APKs for renderscript bitcode and
5466                    // not launch them if it's present. Don't bother checking on devices
5467                    // that don't have 64 bit support.
5468                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
5469                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5470                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5471                    }
5472
5473                    final int copyRet;
5474                    if (isAsec) {
5475                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5476                    } else {
5477                        copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList,
5478                                useIsaSpecificSubdirs);
5479                    }
5480
5481                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5482                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5483                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5484                    }
5485
5486                    if (copyRet >= 0) {
5487                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5488                    }
5489                }
5490            } catch (IOException ioe) {
5491                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5492            } finally {
5493                IoUtils.closeQuietly(handle);
5494            }
5495
5496            // Now that we've calculated the ABIs and determined if it's an internal app,
5497            // we will go ahead and populate the nativeLibraryPath.
5498            setNativeLibraryPaths(pkg);
5499
5500            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5501            final int[] userIds = sUserManager.getUserIds();
5502            synchronized (mInstallLock) {
5503                // Create a native library symlink only if we have native libraries
5504                // and if the native libraries are 32 bit libraries. We do not provide
5505                // this symlink for 64 bit libraries.
5506                if (pkg.applicationInfo.primaryCpuAbi != null &&
5507                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5508                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5509                    for (int userId : userIds) {
5510                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5511                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5512                                    "Failed linking native library dir (user=" + userId + ")");
5513                        }
5514                    }
5515                }
5516            }
5517
5518            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5519            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5520        }
5521
5522        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5523                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5524                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5525
5526        // Push the derived path down into PackageSettings so we know what to
5527        // clean up at uninstall time.
5528        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5529
5530        if (DEBUG_ABI_SELECTION) {
5531            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5532                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5533                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5534        }
5535
5536        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5537            // We don't do this here during boot because we can do it all
5538            // at once after scanning all existing packages.
5539            //
5540            // We also do this *before* we perform dexopt on this package, so that
5541            // we can avoid redundant dexopts, and also to make sure we've got the
5542            // code and package path correct.
5543            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5544                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5545        }
5546
5547        if ((scanMode&SCAN_NO_DEX) == 0) {
5548            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5549                    == DEX_OPT_FAILED) {
5550                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5551                    removeDataDirsLI(pkg.packageName);
5552                }
5553
5554                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5555            }
5556        }
5557
5558        if (mFactoryTest && pkg.requestedPermissions.contains(
5559                android.Manifest.permission.FACTORY_TEST)) {
5560            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5561        }
5562
5563        ArrayList<PackageParser.Package> clientLibPkgs = null;
5564
5565        // writer
5566        synchronized (mPackages) {
5567            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5568                // Only system apps can add new shared libraries.
5569                if (pkg.libraryNames != null) {
5570                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5571                        String name = pkg.libraryNames.get(i);
5572                        boolean allowed = false;
5573                        if (isUpdatedSystemApp(pkg)) {
5574                            // New library entries can only be added through the
5575                            // system image.  This is important to get rid of a lot
5576                            // of nasty edge cases: for example if we allowed a non-
5577                            // system update of the app to add a library, then uninstalling
5578                            // the update would make the library go away, and assumptions
5579                            // we made such as through app install filtering would now
5580                            // have allowed apps on the device which aren't compatible
5581                            // with it.  Better to just have the restriction here, be
5582                            // conservative, and create many fewer cases that can negatively
5583                            // impact the user experience.
5584                            final PackageSetting sysPs = mSettings
5585                                    .getDisabledSystemPkgLPr(pkg.packageName);
5586                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5587                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5588                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5589                                        allowed = true;
5590                                        allowed = true;
5591                                        break;
5592                                    }
5593                                }
5594                            }
5595                        } else {
5596                            allowed = true;
5597                        }
5598                        if (allowed) {
5599                            if (!mSharedLibraries.containsKey(name)) {
5600                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5601                            } else if (!name.equals(pkg.packageName)) {
5602                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5603                                        + name + " already exists; skipping");
5604                            }
5605                        } else {
5606                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5607                                    + name + " that is not declared on system image; skipping");
5608                        }
5609                    }
5610                    if ((scanMode&SCAN_BOOTING) == 0) {
5611                        // If we are not booting, we need to update any applications
5612                        // that are clients of our shared library.  If we are booting,
5613                        // this will all be done once the scan is complete.
5614                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5615                    }
5616                }
5617            }
5618        }
5619
5620        // We also need to dexopt any apps that are dependent on this library.  Note that
5621        // if these fail, we should abort the install since installing the library will
5622        // result in some apps being broken.
5623        if (clientLibPkgs != null) {
5624            if ((scanMode&SCAN_NO_DEX) == 0) {
5625                for (int i=0; i<clientLibPkgs.size(); i++) {
5626                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5627                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5628                            == DEX_OPT_FAILED) {
5629                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5630                            removeDataDirsLI(pkg.packageName);
5631                        }
5632
5633                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5634                                "scanPackageLI failed to dexopt clientLibPkgs");
5635                    }
5636                }
5637            }
5638        }
5639
5640        // Request the ActivityManager to kill the process(only for existing packages)
5641        // so that we do not end up in a confused state while the user is still using the older
5642        // version of the application while the new one gets installed.
5643        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5644            // If the package lives in an asec, tell everyone that the container is going
5645            // away so they can clean up any references to its resources (which would prevent
5646            // vold from being able to unmount the asec)
5647            if (isForwardLocked(pkg) || isExternal(pkg)) {
5648                if (DEBUG_INSTALL) {
5649                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5650                }
5651                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5652                final ArrayList<String> pkgList = new ArrayList<String>(1);
5653                pkgList.add(pkg.applicationInfo.packageName);
5654                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5655            }
5656
5657            // Post the request that it be killed now that the going-away broadcast is en route
5658            killApplication(pkg.applicationInfo.packageName,
5659                        pkg.applicationInfo.uid, "update pkg");
5660        }
5661
5662        // Also need to kill any apps that are dependent on the library.
5663        if (clientLibPkgs != null) {
5664            for (int i=0; i<clientLibPkgs.size(); i++) {
5665                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5666                killApplication(clientPkg.applicationInfo.packageName,
5667                        clientPkg.applicationInfo.uid, "update lib");
5668            }
5669        }
5670
5671        // writer
5672        synchronized (mPackages) {
5673            // We don't expect installation to fail beyond this point,
5674            if ((scanMode&SCAN_MONITOR) != 0) {
5675                mAppDirs.put(pkg.codePath, pkg);
5676            }
5677            // Add the new setting to mSettings
5678            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5679            // Add the new setting to mPackages
5680            mPackages.put(pkg.applicationInfo.packageName, pkg);
5681            // Make sure we don't accidentally delete its data.
5682            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5683            while (iter.hasNext()) {
5684                PackageCleanItem item = iter.next();
5685                if (pkgName.equals(item.packageName)) {
5686                    iter.remove();
5687                }
5688            }
5689
5690            // Take care of first install / last update times.
5691            if (currentTime != 0) {
5692                if (pkgSetting.firstInstallTime == 0) {
5693                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5694                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5695                    pkgSetting.lastUpdateTime = currentTime;
5696                }
5697            } else if (pkgSetting.firstInstallTime == 0) {
5698                // We need *something*.  Take time time stamp of the file.
5699                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5700            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5701                if (scanFileTime != pkgSetting.timeStamp) {
5702                    // A package on the system image has changed; consider this
5703                    // to be an update.
5704                    pkgSetting.lastUpdateTime = scanFileTime;
5705                }
5706            }
5707
5708            // Add the package's KeySets to the global KeySetManagerService
5709            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5710            try {
5711                // Old KeySetData no longer valid.
5712                ksms.removeAppKeySetDataLPw(pkg.packageName);
5713                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5714                if (pkg.mKeySetMapping != null) {
5715                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5716                            pkg.mKeySetMapping.entrySet()) {
5717                        if (entry.getValue() != null) {
5718                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5719                                                          entry.getValue(), entry.getKey());
5720                        }
5721                    }
5722                    if (pkg.mUpgradeKeySets != null) {
5723                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5724                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5725                        }
5726                    }
5727                }
5728            } catch (NullPointerException e) {
5729                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5730            } catch (IllegalArgumentException e) {
5731                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5732            }
5733
5734            int N = pkg.providers.size();
5735            StringBuilder r = null;
5736            int i;
5737            for (i=0; i<N; i++) {
5738                PackageParser.Provider p = pkg.providers.get(i);
5739                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5740                        p.info.processName, pkg.applicationInfo.uid);
5741                mProviders.addProvider(p);
5742                p.syncable = p.info.isSyncable;
5743                if (p.info.authority != null) {
5744                    String names[] = p.info.authority.split(";");
5745                    p.info.authority = null;
5746                    for (int j = 0; j < names.length; j++) {
5747                        if (j == 1 && p.syncable) {
5748                            // We only want the first authority for a provider to possibly be
5749                            // syncable, so if we already added this provider using a different
5750                            // authority clear the syncable flag. We copy the provider before
5751                            // changing it because the mProviders object contains a reference
5752                            // to a provider that we don't want to change.
5753                            // Only do this for the second authority since the resulting provider
5754                            // object can be the same for all future authorities for this provider.
5755                            p = new PackageParser.Provider(p);
5756                            p.syncable = false;
5757                        }
5758                        if (!mProvidersByAuthority.containsKey(names[j])) {
5759                            mProvidersByAuthority.put(names[j], p);
5760                            if (p.info.authority == null) {
5761                                p.info.authority = names[j];
5762                            } else {
5763                                p.info.authority = p.info.authority + ";" + names[j];
5764                            }
5765                            if (DEBUG_PACKAGE_SCANNING) {
5766                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5767                                    Log.d(TAG, "Registered content provider: " + names[j]
5768                                            + ", className = " + p.info.name + ", isSyncable = "
5769                                            + p.info.isSyncable);
5770                            }
5771                        } else {
5772                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5773                            Slog.w(TAG, "Skipping provider name " + names[j] +
5774                                    " (in package " + pkg.applicationInfo.packageName +
5775                                    "): name already used by "
5776                                    + ((other != null && other.getComponentName() != null)
5777                                            ? other.getComponentName().getPackageName() : "?"));
5778                        }
5779                    }
5780                }
5781                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5782                    if (r == null) {
5783                        r = new StringBuilder(256);
5784                    } else {
5785                        r.append(' ');
5786                    }
5787                    r.append(p.info.name);
5788                }
5789            }
5790            if (r != null) {
5791                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5792            }
5793
5794            N = pkg.services.size();
5795            r = null;
5796            for (i=0; i<N; i++) {
5797                PackageParser.Service s = pkg.services.get(i);
5798                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5799                        s.info.processName, pkg.applicationInfo.uid);
5800                mServices.addService(s);
5801                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5802                    if (r == null) {
5803                        r = new StringBuilder(256);
5804                    } else {
5805                        r.append(' ');
5806                    }
5807                    r.append(s.info.name);
5808                }
5809            }
5810            if (r != null) {
5811                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5812            }
5813
5814            N = pkg.receivers.size();
5815            r = null;
5816            for (i=0; i<N; i++) {
5817                PackageParser.Activity a = pkg.receivers.get(i);
5818                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5819                        a.info.processName, pkg.applicationInfo.uid);
5820                mReceivers.addActivity(a, "receiver");
5821                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5822                    if (r == null) {
5823                        r = new StringBuilder(256);
5824                    } else {
5825                        r.append(' ');
5826                    }
5827                    r.append(a.info.name);
5828                }
5829            }
5830            if (r != null) {
5831                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5832            }
5833
5834            N = pkg.activities.size();
5835            r = null;
5836            for (i=0; i<N; i++) {
5837                PackageParser.Activity a = pkg.activities.get(i);
5838                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5839                        a.info.processName, pkg.applicationInfo.uid);
5840                mActivities.addActivity(a, "activity");
5841                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5842                    if (r == null) {
5843                        r = new StringBuilder(256);
5844                    } else {
5845                        r.append(' ');
5846                    }
5847                    r.append(a.info.name);
5848                }
5849            }
5850            if (r != null) {
5851                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5852            }
5853
5854            N = pkg.permissionGroups.size();
5855            r = null;
5856            for (i=0; i<N; i++) {
5857                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5858                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5859                if (cur == null) {
5860                    mPermissionGroups.put(pg.info.name, pg);
5861                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5862                        if (r == null) {
5863                            r = new StringBuilder(256);
5864                        } else {
5865                            r.append(' ');
5866                        }
5867                        r.append(pg.info.name);
5868                    }
5869                } else {
5870                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5871                            + pg.info.packageName + " ignored: original from "
5872                            + cur.info.packageName);
5873                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5874                        if (r == null) {
5875                            r = new StringBuilder(256);
5876                        } else {
5877                            r.append(' ');
5878                        }
5879                        r.append("DUP:");
5880                        r.append(pg.info.name);
5881                    }
5882                }
5883            }
5884            if (r != null) {
5885                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5886            }
5887
5888            N = pkg.permissions.size();
5889            r = null;
5890            for (i=0; i<N; i++) {
5891                PackageParser.Permission p = pkg.permissions.get(i);
5892                HashMap<String, BasePermission> permissionMap =
5893                        p.tree ? mSettings.mPermissionTrees
5894                        : mSettings.mPermissions;
5895                p.group = mPermissionGroups.get(p.info.group);
5896                if (p.info.group == null || p.group != null) {
5897                    BasePermission bp = permissionMap.get(p.info.name);
5898                    if (bp == null) {
5899                        bp = new BasePermission(p.info.name, p.info.packageName,
5900                                BasePermission.TYPE_NORMAL);
5901                        permissionMap.put(p.info.name, bp);
5902                    }
5903                    if (bp.perm == null) {
5904                        if (bp.sourcePackage != null
5905                                && !bp.sourcePackage.equals(p.info.packageName)) {
5906                            // If this is a permission that was formerly defined by a non-system
5907                            // app, but is now defined by a system app (following an upgrade),
5908                            // discard the previous declaration and consider the system's to be
5909                            // canonical.
5910                            if (isSystemApp(p.owner)) {
5911                                String msg = "New decl " + p.owner + " of permission  "
5912                                        + p.info.name + " is system";
5913                                reportSettingsProblem(Log.WARN, msg);
5914                                bp.sourcePackage = null;
5915                            }
5916                        }
5917                        if (bp.sourcePackage == null
5918                                || bp.sourcePackage.equals(p.info.packageName)) {
5919                            BasePermission tree = findPermissionTreeLP(p.info.name);
5920                            if (tree == null
5921                                    || tree.sourcePackage.equals(p.info.packageName)) {
5922                                bp.packageSetting = pkgSetting;
5923                                bp.perm = p;
5924                                bp.uid = pkg.applicationInfo.uid;
5925                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5926                                    if (r == null) {
5927                                        r = new StringBuilder(256);
5928                                    } else {
5929                                        r.append(' ');
5930                                    }
5931                                    r.append(p.info.name);
5932                                }
5933                            } else {
5934                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5935                                        + p.info.packageName + " ignored: base tree "
5936                                        + tree.name + " is from package "
5937                                        + tree.sourcePackage);
5938                            }
5939                        } else {
5940                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5941                                    + p.info.packageName + " ignored: original from "
5942                                    + bp.sourcePackage);
5943                        }
5944                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5945                        if (r == null) {
5946                            r = new StringBuilder(256);
5947                        } else {
5948                            r.append(' ');
5949                        }
5950                        r.append("DUP:");
5951                        r.append(p.info.name);
5952                    }
5953                    if (bp.perm == p) {
5954                        bp.protectionLevel = p.info.protectionLevel;
5955                    }
5956                } else {
5957                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5958                            + p.info.packageName + " ignored: no group "
5959                            + p.group);
5960                }
5961            }
5962            if (r != null) {
5963                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5964            }
5965
5966            N = pkg.instrumentation.size();
5967            r = null;
5968            for (i=0; i<N; i++) {
5969                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5970                a.info.packageName = pkg.applicationInfo.packageName;
5971                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5972                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5973                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
5974                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
5975                a.info.dataDir = pkg.applicationInfo.dataDir;
5976
5977                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
5978                // need other information about the application, like the ABI and what not ?
5979                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5980                mInstrumentation.put(a.getComponentName(), a);
5981                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5982                    if (r == null) {
5983                        r = new StringBuilder(256);
5984                    } else {
5985                        r.append(' ');
5986                    }
5987                    r.append(a.info.name);
5988                }
5989            }
5990            if (r != null) {
5991                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5992            }
5993
5994            if (pkg.protectedBroadcasts != null) {
5995                N = pkg.protectedBroadcasts.size();
5996                for (i=0; i<N; i++) {
5997                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5998                }
5999            }
6000
6001            pkgSetting.setTimeStamp(scanFileTime);
6002
6003            // Create idmap files for pairs of (packages, overlay packages).
6004            // Note: "android", ie framework-res.apk, is handled by native layers.
6005            if (pkg.mOverlayTarget != null) {
6006                // This is an overlay package.
6007                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6008                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6009                        mOverlays.put(pkg.mOverlayTarget,
6010                                new HashMap<String, PackageParser.Package>());
6011                    }
6012                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6013                    map.put(pkg.packageName, pkg);
6014                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6015                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6016                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6017                                "scanPackageLI failed to createIdmap");
6018                    }
6019                }
6020            } else if (mOverlays.containsKey(pkg.packageName) &&
6021                    !pkg.packageName.equals("android")) {
6022                // This is a regular package, with one or more known overlay packages.
6023                createIdmapsForPackageLI(pkg);
6024            }
6025        }
6026
6027        return pkg;
6028    }
6029
6030    /**
6031     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6032     * i.e, so that all packages can be run inside a single process if required.
6033     *
6034     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6035     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6036     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6037     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6038     * updating a package that belongs to a shared user.
6039     *
6040     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6041     * adds unnecessary complexity.
6042     */
6043    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6044            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6045        String requiredInstructionSet = null;
6046        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6047            requiredInstructionSet = VMRuntime.getInstructionSet(
6048                     scannedPackage.applicationInfo.primaryCpuAbi);
6049        }
6050
6051        PackageSetting requirer = null;
6052        for (PackageSetting ps : packagesForUser) {
6053            // If packagesForUser contains scannedPackage, we skip it. This will happen
6054            // when scannedPackage is an update of an existing package. Without this check,
6055            // we will never be able to change the ABI of any package belonging to a shared
6056            // user, even if it's compatible with other packages.
6057            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6058                if (ps.primaryCpuAbiString == null) {
6059                    continue;
6060                }
6061
6062                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6063                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6064                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6065                    // this but there's not much we can do.
6066                    String errorMessage = "Instruction set mismatch, "
6067                            + ((requirer == null) ? "[caller]" : requirer)
6068                            + " requires " + requiredInstructionSet + " whereas " + ps
6069                            + " requires " + instructionSet;
6070                    Slog.w(TAG, errorMessage);
6071                }
6072
6073                if (requiredInstructionSet == null) {
6074                    requiredInstructionSet = instructionSet;
6075                    requirer = ps;
6076                }
6077            }
6078        }
6079
6080        if (requiredInstructionSet != null) {
6081            String adjustedAbi;
6082            if (requirer != null) {
6083                // requirer != null implies that either scannedPackage was null or that scannedPackage
6084                // did not require an ABI, in which case we have to adjust scannedPackage to match
6085                // the ABI of the set (which is the same as requirer's ABI)
6086                adjustedAbi = requirer.primaryCpuAbiString;
6087                if (scannedPackage != null) {
6088                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6089                }
6090            } else {
6091                // requirer == null implies that we're updating all ABIs in the set to
6092                // match scannedPackage.
6093                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6094            }
6095
6096            for (PackageSetting ps : packagesForUser) {
6097                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6098                    if (ps.primaryCpuAbiString != null) {
6099                        continue;
6100                    }
6101
6102                    ps.primaryCpuAbiString = adjustedAbi;
6103                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6104                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6105                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6106
6107                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6108                            ps.primaryCpuAbiString = null;
6109                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6110                            return;
6111                        } else {
6112                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6113                        }
6114                    }
6115                }
6116            }
6117        }
6118    }
6119
6120    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6121        synchronized (mPackages) {
6122            mResolverReplaced = true;
6123            // Set up information for custom user intent resolution activity.
6124            mResolveActivity.applicationInfo = pkg.applicationInfo;
6125            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6126            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6127            mResolveActivity.processName = null;
6128            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6129            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6130                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6131            mResolveActivity.theme = 0;
6132            mResolveActivity.exported = true;
6133            mResolveActivity.enabled = true;
6134            mResolveInfo.activityInfo = mResolveActivity;
6135            mResolveInfo.priority = 0;
6136            mResolveInfo.preferredOrder = 0;
6137            mResolveInfo.match = 0;
6138            mResolveComponentName = mCustomResolverComponentName;
6139            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6140                    mResolveComponentName);
6141        }
6142    }
6143
6144    private static String calculateApkRoot(final String codePathString) {
6145        final File codePath = new File(codePathString);
6146        final File codeRoot;
6147        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6148            codeRoot = Environment.getRootDirectory();
6149        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6150            codeRoot = Environment.getOemDirectory();
6151        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6152            codeRoot = Environment.getVendorDirectory();
6153        } else {
6154            // Unrecognized code path; take its top real segment as the apk root:
6155            // e.g. /something/app/blah.apk => /something
6156            try {
6157                File f = codePath.getCanonicalFile();
6158                File parent = f.getParentFile();    // non-null because codePath is a file
6159                File tmp;
6160                while ((tmp = parent.getParentFile()) != null) {
6161                    f = parent;
6162                    parent = tmp;
6163                }
6164                codeRoot = f;
6165                Slog.w(TAG, "Unrecognized code path "
6166                        + codePath + " - using " + codeRoot);
6167            } catch (IOException e) {
6168                // Can't canonicalize the code path -- shenanigans?
6169                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6170                return Environment.getRootDirectory().getPath();
6171            }
6172        }
6173        return codeRoot.getPath();
6174    }
6175
6176    /**
6177     * Derive and set the location of native libraries for the given package,
6178     * which varies depending on where and how the package was installed.
6179     */
6180    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6181        final ApplicationInfo info = pkg.applicationInfo;
6182        final String codePath = pkg.codePath;
6183        final File codeFile = new File(codePath);
6184
6185        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6186        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6187
6188        info.nativeLibraryRootDir = null;
6189        info.nativeLibraryRootRequiresIsa = false;
6190        info.nativeLibraryDir = null;
6191
6192        if (bundledApp) {
6193            // Monolithic bundled install
6194            // TODO: support cluster bundled installs?
6195
6196            final boolean is64Bit = (info.primaryCpuAbi != null)
6197                    && VMRuntime.is64BitAbi(info.primaryCpuAbi);
6198
6199            // This is a bundled system app so choose the path based on the ABI.
6200            // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6201            // is just the default path.
6202            final String apkName = deriveCodePathName(codePath);
6203            final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6204            info.nativeLibraryRootDir = Environment.buildPath(new File(info.apkRoot), libDir,
6205                    apkName).getAbsolutePath();
6206            info.nativeLibraryRootRequiresIsa = false;
6207
6208        } else if (isApkFile(codeFile)) {
6209            // Monolithic install
6210            if (asecApp) {
6211                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6212                        .getAbsolutePath();
6213                info.nativeLibraryRootRequiresIsa = false;
6214            } else {
6215                final String apkName = deriveCodePathName(codePath);
6216                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6217                        .getAbsolutePath();
6218                info.nativeLibraryRootRequiresIsa = false;
6219            }
6220        } else {
6221            // Cluster install
6222            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6223            info.nativeLibraryRootRequiresIsa = true;
6224        }
6225
6226        if (info.nativeLibraryRootRequiresIsa) {
6227            if (info.primaryCpuAbi != null) {
6228                info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6229                        VMRuntime.getInstructionSet(info.primaryCpuAbi)).getAbsolutePath();
6230            }
6231        } else {
6232            info.nativeLibraryDir = info.nativeLibraryRootDir;
6233        }
6234    }
6235
6236    /**
6237     * Calculate the abis and roots for a bundled app. These can uniquely
6238     * be determined from the contents of the system partition, i.e whether
6239     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6240     * of this information, and instead assume that the system was built
6241     * sensibly.
6242     */
6243    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6244                                           PackageSetting pkgSetting) {
6245        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6246
6247        // If "/system/lib64/apkname" exists, assume that is the per-package
6248        // native library directory to use; otherwise use "/system/lib/apkname".
6249        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6250        pkg.applicationInfo.apkRoot = apkRoot;
6251        setBundledAppAbi(pkg, apkRoot, apkName);
6252        // pkgSetting might be null during rescan following uninstall of updates
6253        // to a bundled app, so accommodate that possibility.  The settings in
6254        // that case will be established later from the parsed package.
6255        //
6256        // If the settings aren't null, sync them up with what we've just derived.
6257        // note that apkRoot isn't stored in the package settings.
6258        if (pkgSetting != null) {
6259            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6260            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6261        }
6262    }
6263
6264    /**
6265     * Deduces the ABI of a bundled app and sets the relevant fields on the
6266     * parsed pkg object.
6267     *
6268     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6269     *        under which system libraries are installed.
6270     * @param apkName the name of the installed package.
6271     */
6272    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6273        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6274        // or similar.
6275        final boolean has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6276        final boolean has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6277
6278        if (has64BitLibs && !has32BitLibs) {
6279            // The package has 64 bit libs, but not 32 bit libs. Its primary
6280            // ABI should be 64 bit. We can safely assume here that the bundled
6281            // native libraries correspond to the most preferred ABI in the list.
6282
6283            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6284            pkg.applicationInfo.secondaryCpuAbi = null;
6285        } else if (has32BitLibs && !has64BitLibs) {
6286            // The package has 32 bit libs but not 64 bit libs. Its primary
6287            // ABI should be 32 bit.
6288
6289            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6290            pkg.applicationInfo.secondaryCpuAbi = null;
6291        } else if (has32BitLibs && has64BitLibs) {
6292            // The application has both 64 and 32 bit bundled libraries. We check
6293            // here that the app declares multiArch support, and warn if it doesn't.
6294            //
6295            // We will be lenient here and record both ABIs. The primary will be the
6296            // ABI that's higher on the list, i.e, a device that's configured to prefer
6297            // 64 bit apps will see a 64 bit primary ABI,
6298
6299            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6300                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6301            }
6302
6303            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6304                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6305                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6306            } else {
6307                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6308                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6309            }
6310        } else {
6311            pkg.applicationInfo.primaryCpuAbi = null;
6312            pkg.applicationInfo.secondaryCpuAbi = null;
6313        }
6314    }
6315
6316    private static void createNativeLibrarySubdir(File path) throws IOException {
6317        if (!path.isDirectory()) {
6318            path.delete();
6319
6320            if (!path.mkdir()) {
6321                throw new IOException("Cannot create " + path.getPath());
6322            }
6323
6324            try {
6325                Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6326            } catch (ErrnoException e) {
6327                throw new IOException("Cannot chmod native library directory "
6328                        + path.getPath(), e);
6329            }
6330        } else if (!SELinux.restorecon(path)) {
6331            throw new IOException("Cannot set SELinux context for " + path.getPath());
6332        }
6333    }
6334
6335    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6336            final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException {
6337        createNativeLibrarySubdir(nativeLibraryRoot);
6338
6339        /*
6340         * If this is an internal application or our nativeLibraryPath points to
6341         * the app-lib directory, unpack the libraries if necessary.
6342         */
6343        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6344        if (abi >= 0) {
6345            /*
6346             * If we have a matching instruction set, construct a subdir under the native
6347             * library root that corresponds to this instruction set.
6348             */
6349            final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]);
6350            final File subDir;
6351            if (useIsaSubdir) {
6352                final File isaSubdir = new File(nativeLibraryRoot, instructionSet);
6353                createNativeLibrarySubdir(isaSubdir);
6354                subDir = isaSubdir;
6355            } else {
6356                subDir = nativeLibraryRoot;
6357            }
6358
6359            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]);
6360            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6361                return copyRet;
6362            }
6363        }
6364
6365        return abi;
6366    }
6367
6368    private void killApplication(String pkgName, int appId, String reason) {
6369        // Request the ActivityManager to kill the process(only for existing packages)
6370        // so that we do not end up in a confused state while the user is still using the older
6371        // version of the application while the new one gets installed.
6372        IActivityManager am = ActivityManagerNative.getDefault();
6373        if (am != null) {
6374            try {
6375                am.killApplicationWithAppId(pkgName, appId, reason);
6376            } catch (RemoteException e) {
6377            }
6378        }
6379    }
6380
6381    void removePackageLI(PackageSetting ps, boolean chatty) {
6382        if (DEBUG_INSTALL) {
6383            if (chatty)
6384                Log.d(TAG, "Removing package " + ps.name);
6385        }
6386
6387        // writer
6388        synchronized (mPackages) {
6389            mPackages.remove(ps.name);
6390            if (ps.codePathString != null) {
6391                mAppDirs.remove(ps.codePathString);
6392            }
6393
6394            final PackageParser.Package pkg = ps.pkg;
6395            if (pkg != null) {
6396                cleanPackageDataStructuresLILPw(pkg, chatty);
6397            }
6398        }
6399    }
6400
6401    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6402        if (DEBUG_INSTALL) {
6403            if (chatty)
6404                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6405        }
6406
6407        // writer
6408        synchronized (mPackages) {
6409            mPackages.remove(pkg.applicationInfo.packageName);
6410            if (pkg.codePath != null) {
6411                mAppDirs.remove(pkg.codePath);
6412            }
6413            cleanPackageDataStructuresLILPw(pkg, chatty);
6414        }
6415    }
6416
6417    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6418        int N = pkg.providers.size();
6419        StringBuilder r = null;
6420        int i;
6421        for (i=0; i<N; i++) {
6422            PackageParser.Provider p = pkg.providers.get(i);
6423            mProviders.removeProvider(p);
6424            if (p.info.authority == null) {
6425
6426                /* There was another ContentProvider with this authority when
6427                 * this app was installed so this authority is null,
6428                 * Ignore it as we don't have to unregister the provider.
6429                 */
6430                continue;
6431            }
6432            String names[] = p.info.authority.split(";");
6433            for (int j = 0; j < names.length; j++) {
6434                if (mProvidersByAuthority.get(names[j]) == p) {
6435                    mProvidersByAuthority.remove(names[j]);
6436                    if (DEBUG_REMOVE) {
6437                        if (chatty)
6438                            Log.d(TAG, "Unregistered content provider: " + names[j]
6439                                    + ", className = " + p.info.name + ", isSyncable = "
6440                                    + p.info.isSyncable);
6441                    }
6442                }
6443            }
6444            if (DEBUG_REMOVE && chatty) {
6445                if (r == null) {
6446                    r = new StringBuilder(256);
6447                } else {
6448                    r.append(' ');
6449                }
6450                r.append(p.info.name);
6451            }
6452        }
6453        if (r != null) {
6454            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6455        }
6456
6457        N = pkg.services.size();
6458        r = null;
6459        for (i=0; i<N; i++) {
6460            PackageParser.Service s = pkg.services.get(i);
6461            mServices.removeService(s);
6462            if (chatty) {
6463                if (r == null) {
6464                    r = new StringBuilder(256);
6465                } else {
6466                    r.append(' ');
6467                }
6468                r.append(s.info.name);
6469            }
6470        }
6471        if (r != null) {
6472            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6473        }
6474
6475        N = pkg.receivers.size();
6476        r = null;
6477        for (i=0; i<N; i++) {
6478            PackageParser.Activity a = pkg.receivers.get(i);
6479            mReceivers.removeActivity(a, "receiver");
6480            if (DEBUG_REMOVE && chatty) {
6481                if (r == null) {
6482                    r = new StringBuilder(256);
6483                } else {
6484                    r.append(' ');
6485                }
6486                r.append(a.info.name);
6487            }
6488        }
6489        if (r != null) {
6490            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6491        }
6492
6493        N = pkg.activities.size();
6494        r = null;
6495        for (i=0; i<N; i++) {
6496            PackageParser.Activity a = pkg.activities.get(i);
6497            mActivities.removeActivity(a, "activity");
6498            if (DEBUG_REMOVE && chatty) {
6499                if (r == null) {
6500                    r = new StringBuilder(256);
6501                } else {
6502                    r.append(' ');
6503                }
6504                r.append(a.info.name);
6505            }
6506        }
6507        if (r != null) {
6508            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6509        }
6510
6511        N = pkg.permissions.size();
6512        r = null;
6513        for (i=0; i<N; i++) {
6514            PackageParser.Permission p = pkg.permissions.get(i);
6515            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6516            if (bp == null) {
6517                bp = mSettings.mPermissionTrees.get(p.info.name);
6518            }
6519            if (bp != null && bp.perm == p) {
6520                bp.perm = null;
6521                if (DEBUG_REMOVE && chatty) {
6522                    if (r == null) {
6523                        r = new StringBuilder(256);
6524                    } else {
6525                        r.append(' ');
6526                    }
6527                    r.append(p.info.name);
6528                }
6529            }
6530        }
6531        if (r != null) {
6532            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6533        }
6534
6535        N = pkg.instrumentation.size();
6536        r = null;
6537        for (i=0; i<N; i++) {
6538            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6539            mInstrumentation.remove(a.getComponentName());
6540            if (DEBUG_REMOVE && chatty) {
6541                if (r == null) {
6542                    r = new StringBuilder(256);
6543                } else {
6544                    r.append(' ');
6545                }
6546                r.append(a.info.name);
6547            }
6548        }
6549        if (r != null) {
6550            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6551        }
6552
6553        r = null;
6554        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6555            // Only system apps can hold shared libraries.
6556            if (pkg.libraryNames != null) {
6557                for (i=0; i<pkg.libraryNames.size(); i++) {
6558                    String name = pkg.libraryNames.get(i);
6559                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6560                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6561                        mSharedLibraries.remove(name);
6562                        if (DEBUG_REMOVE && chatty) {
6563                            if (r == null) {
6564                                r = new StringBuilder(256);
6565                            } else {
6566                                r.append(' ');
6567                            }
6568                            r.append(name);
6569                        }
6570                    }
6571                }
6572            }
6573        }
6574        if (r != null) {
6575            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6576        }
6577    }
6578
6579    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6580        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6581            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6582                return true;
6583            }
6584        }
6585        return false;
6586    }
6587
6588    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6589    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6590    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6591
6592    private void updatePermissionsLPw(String changingPkg,
6593            PackageParser.Package pkgInfo, int flags) {
6594        // Make sure there are no dangling permission trees.
6595        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6596        while (it.hasNext()) {
6597            final BasePermission bp = it.next();
6598            if (bp.packageSetting == null) {
6599                // We may not yet have parsed the package, so just see if
6600                // we still know about its settings.
6601                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6602            }
6603            if (bp.packageSetting == null) {
6604                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6605                        + " from package " + bp.sourcePackage);
6606                it.remove();
6607            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6608                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6609                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6610                            + " from package " + bp.sourcePackage);
6611                    flags |= UPDATE_PERMISSIONS_ALL;
6612                    it.remove();
6613                }
6614            }
6615        }
6616
6617        // Make sure all dynamic permissions have been assigned to a package,
6618        // and make sure there are no dangling permissions.
6619        it = mSettings.mPermissions.values().iterator();
6620        while (it.hasNext()) {
6621            final BasePermission bp = it.next();
6622            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6623                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6624                        + bp.name + " pkg=" + bp.sourcePackage
6625                        + " info=" + bp.pendingInfo);
6626                if (bp.packageSetting == null && bp.pendingInfo != null) {
6627                    final BasePermission tree = findPermissionTreeLP(bp.name);
6628                    if (tree != null && tree.perm != null) {
6629                        bp.packageSetting = tree.packageSetting;
6630                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6631                                new PermissionInfo(bp.pendingInfo));
6632                        bp.perm.info.packageName = tree.perm.info.packageName;
6633                        bp.perm.info.name = bp.name;
6634                        bp.uid = tree.uid;
6635                    }
6636                }
6637            }
6638            if (bp.packageSetting == null) {
6639                // We may not yet have parsed the package, so just see if
6640                // we still know about its settings.
6641                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6642            }
6643            if (bp.packageSetting == null) {
6644                Slog.w(TAG, "Removing dangling permission: " + bp.name
6645                        + " from package " + bp.sourcePackage);
6646                it.remove();
6647            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6648                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6649                    Slog.i(TAG, "Removing old permission: " + bp.name
6650                            + " from package " + bp.sourcePackage);
6651                    flags |= UPDATE_PERMISSIONS_ALL;
6652                    it.remove();
6653                }
6654            }
6655        }
6656
6657        // Now update the permissions for all packages, in particular
6658        // replace the granted permissions of the system packages.
6659        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6660            for (PackageParser.Package pkg : mPackages.values()) {
6661                if (pkg != pkgInfo) {
6662                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6663                }
6664            }
6665        }
6666
6667        if (pkgInfo != null) {
6668            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6669        }
6670    }
6671
6672    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6673        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6674        if (ps == null) {
6675            return;
6676        }
6677        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6678        HashSet<String> origPermissions = gp.grantedPermissions;
6679        boolean changedPermission = false;
6680
6681        if (replace) {
6682            ps.permissionsFixed = false;
6683            if (gp == ps) {
6684                origPermissions = new HashSet<String>(gp.grantedPermissions);
6685                gp.grantedPermissions.clear();
6686                gp.gids = mGlobalGids;
6687            }
6688        }
6689
6690        if (gp.gids == null) {
6691            gp.gids = mGlobalGids;
6692        }
6693
6694        final int N = pkg.requestedPermissions.size();
6695        for (int i=0; i<N; i++) {
6696            final String name = pkg.requestedPermissions.get(i);
6697            final boolean required = pkg.requestedPermissionsRequired.get(i);
6698            final BasePermission bp = mSettings.mPermissions.get(name);
6699            if (DEBUG_INSTALL) {
6700                if (gp != ps) {
6701                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6702                }
6703            }
6704
6705            if (bp == null || bp.packageSetting == null) {
6706                Slog.w(TAG, "Unknown permission " + name
6707                        + " in package " + pkg.packageName);
6708                continue;
6709            }
6710
6711            final String perm = bp.name;
6712            boolean allowed;
6713            boolean allowedSig = false;
6714            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6715            if (level == PermissionInfo.PROTECTION_NORMAL
6716                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6717                // We grant a normal or dangerous permission if any of the following
6718                // are true:
6719                // 1) The permission is required
6720                // 2) The permission is optional, but was granted in the past
6721                // 3) The permission is optional, but was requested by an
6722                //    app in /system (not /data)
6723                //
6724                // Otherwise, reject the permission.
6725                allowed = (required || origPermissions.contains(perm)
6726                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6727            } else if (bp.packageSetting == null) {
6728                // This permission is invalid; skip it.
6729                allowed = false;
6730            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6731                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6732                if (allowed) {
6733                    allowedSig = true;
6734                }
6735            } else {
6736                allowed = false;
6737            }
6738            if (DEBUG_INSTALL) {
6739                if (gp != ps) {
6740                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6741                }
6742            }
6743            if (allowed) {
6744                if (!isSystemApp(ps) && ps.permissionsFixed) {
6745                    // If this is an existing, non-system package, then
6746                    // we can't add any new permissions to it.
6747                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6748                        // Except...  if this is a permission that was added
6749                        // to the platform (note: need to only do this when
6750                        // updating the platform).
6751                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6752                    }
6753                }
6754                if (allowed) {
6755                    if (!gp.grantedPermissions.contains(perm)) {
6756                        changedPermission = true;
6757                        gp.grantedPermissions.add(perm);
6758                        gp.gids = appendInts(gp.gids, bp.gids);
6759                    } else if (!ps.haveGids) {
6760                        gp.gids = appendInts(gp.gids, bp.gids);
6761                    }
6762                } else {
6763                    Slog.w(TAG, "Not granting permission " + perm
6764                            + " to package " + pkg.packageName
6765                            + " because it was previously installed without");
6766                }
6767            } else {
6768                if (gp.grantedPermissions.remove(perm)) {
6769                    changedPermission = true;
6770                    gp.gids = removeInts(gp.gids, bp.gids);
6771                    Slog.i(TAG, "Un-granting permission " + perm
6772                            + " from package " + pkg.packageName
6773                            + " (protectionLevel=" + bp.protectionLevel
6774                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6775                            + ")");
6776                } else {
6777                    Slog.w(TAG, "Not granting permission " + perm
6778                            + " to package " + pkg.packageName
6779                            + " (protectionLevel=" + bp.protectionLevel
6780                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6781                            + ")");
6782                }
6783            }
6784        }
6785
6786        if ((changedPermission || replace) && !ps.permissionsFixed &&
6787                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6788            // This is the first that we have heard about this package, so the
6789            // permissions we have now selected are fixed until explicitly
6790            // changed.
6791            ps.permissionsFixed = true;
6792        }
6793        ps.haveGids = true;
6794    }
6795
6796    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6797        boolean allowed = false;
6798        final int NP = PackageParser.NEW_PERMISSIONS.length;
6799        for (int ip=0; ip<NP; ip++) {
6800            final PackageParser.NewPermissionInfo npi
6801                    = PackageParser.NEW_PERMISSIONS[ip];
6802            if (npi.name.equals(perm)
6803                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6804                allowed = true;
6805                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6806                        + pkg.packageName);
6807                break;
6808            }
6809        }
6810        return allowed;
6811    }
6812
6813    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6814                                          BasePermission bp, HashSet<String> origPermissions) {
6815        boolean allowed;
6816        allowed = (compareSignatures(
6817                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6818                        == PackageManager.SIGNATURE_MATCH)
6819                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6820                        == PackageManager.SIGNATURE_MATCH);
6821        if (!allowed && (bp.protectionLevel
6822                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6823            if (isSystemApp(pkg)) {
6824                // For updated system applications, a system permission
6825                // is granted only if it had been defined by the original application.
6826                if (isUpdatedSystemApp(pkg)) {
6827                    final PackageSetting sysPs = mSettings
6828                            .getDisabledSystemPkgLPr(pkg.packageName);
6829                    final GrantedPermissions origGp = sysPs.sharedUser != null
6830                            ? sysPs.sharedUser : sysPs;
6831
6832                    if (origGp.grantedPermissions.contains(perm)) {
6833                        // If the original was granted this permission, we take
6834                        // that grant decision as read and propagate it to the
6835                        // update.
6836                        allowed = true;
6837                    } else {
6838                        // The system apk may have been updated with an older
6839                        // version of the one on the data partition, but which
6840                        // granted a new system permission that it didn't have
6841                        // before.  In this case we do want to allow the app to
6842                        // now get the new permission if the ancestral apk is
6843                        // privileged to get it.
6844                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6845                            for (int j=0;
6846                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6847                                if (perm.equals(
6848                                        sysPs.pkg.requestedPermissions.get(j))) {
6849                                    allowed = true;
6850                                    break;
6851                                }
6852                            }
6853                        }
6854                    }
6855                } else {
6856                    allowed = isPrivilegedApp(pkg);
6857                }
6858            }
6859        }
6860        if (!allowed && (bp.protectionLevel
6861                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6862            // For development permissions, a development permission
6863            // is granted only if it was already granted.
6864            allowed = origPermissions.contains(perm);
6865        }
6866        return allowed;
6867    }
6868
6869    final class ActivityIntentResolver
6870            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6871        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6872                boolean defaultOnly, int userId) {
6873            if (!sUserManager.exists(userId)) return null;
6874            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6875            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6876        }
6877
6878        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6879                int userId) {
6880            if (!sUserManager.exists(userId)) return null;
6881            mFlags = flags;
6882            return super.queryIntent(intent, resolvedType,
6883                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6884        }
6885
6886        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6887                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6888            if (!sUserManager.exists(userId)) return null;
6889            if (packageActivities == null) {
6890                return null;
6891            }
6892            mFlags = flags;
6893            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6894            final int N = packageActivities.size();
6895            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6896                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6897
6898            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6899            for (int i = 0; i < N; ++i) {
6900                intentFilters = packageActivities.get(i).intents;
6901                if (intentFilters != null && intentFilters.size() > 0) {
6902                    PackageParser.ActivityIntentInfo[] array =
6903                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6904                    intentFilters.toArray(array);
6905                    listCut.add(array);
6906                }
6907            }
6908            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6909        }
6910
6911        public final void addActivity(PackageParser.Activity a, String type) {
6912            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6913            mActivities.put(a.getComponentName(), a);
6914            if (DEBUG_SHOW_INFO)
6915                Log.v(
6916                TAG, "  " + type + " " +
6917                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6918            if (DEBUG_SHOW_INFO)
6919                Log.v(TAG, "    Class=" + a.info.name);
6920            final int NI = a.intents.size();
6921            for (int j=0; j<NI; j++) {
6922                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6923                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6924                    intent.setPriority(0);
6925                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6926                            + a.className + " with priority > 0, forcing to 0");
6927                }
6928                if (DEBUG_SHOW_INFO) {
6929                    Log.v(TAG, "    IntentFilter:");
6930                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6931                }
6932                if (!intent.debugCheck()) {
6933                    Log.w(TAG, "==> For Activity " + a.info.name);
6934                }
6935                addFilter(intent);
6936            }
6937        }
6938
6939        public final void removeActivity(PackageParser.Activity a, String type) {
6940            mActivities.remove(a.getComponentName());
6941            if (DEBUG_SHOW_INFO) {
6942                Log.v(TAG, "  " + type + " "
6943                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6944                                : a.info.name) + ":");
6945                Log.v(TAG, "    Class=" + a.info.name);
6946            }
6947            final int NI = a.intents.size();
6948            for (int j=0; j<NI; j++) {
6949                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6950                if (DEBUG_SHOW_INFO) {
6951                    Log.v(TAG, "    IntentFilter:");
6952                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6953                }
6954                removeFilter(intent);
6955            }
6956        }
6957
6958        @Override
6959        protected boolean allowFilterResult(
6960                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6961            ActivityInfo filterAi = filter.activity.info;
6962            for (int i=dest.size()-1; i>=0; i--) {
6963                ActivityInfo destAi = dest.get(i).activityInfo;
6964                if (destAi.name == filterAi.name
6965                        && destAi.packageName == filterAi.packageName) {
6966                    return false;
6967                }
6968            }
6969            return true;
6970        }
6971
6972        @Override
6973        protected ActivityIntentInfo[] newArray(int size) {
6974            return new ActivityIntentInfo[size];
6975        }
6976
6977        @Override
6978        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6979            if (!sUserManager.exists(userId)) return true;
6980            PackageParser.Package p = filter.activity.owner;
6981            if (p != null) {
6982                PackageSetting ps = (PackageSetting)p.mExtras;
6983                if (ps != null) {
6984                    // System apps are never considered stopped for purposes of
6985                    // filtering, because there may be no way for the user to
6986                    // actually re-launch them.
6987                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6988                            && ps.getStopped(userId);
6989                }
6990            }
6991            return false;
6992        }
6993
6994        @Override
6995        protected boolean isPackageForFilter(String packageName,
6996                PackageParser.ActivityIntentInfo info) {
6997            return packageName.equals(info.activity.owner.packageName);
6998        }
6999
7000        @Override
7001        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7002                int match, int userId) {
7003            if (!sUserManager.exists(userId)) return null;
7004            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7005                return null;
7006            }
7007            final PackageParser.Activity activity = info.activity;
7008            if (mSafeMode && (activity.info.applicationInfo.flags
7009                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7010                return null;
7011            }
7012            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7013            if (ps == null) {
7014                return null;
7015            }
7016            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7017                    ps.readUserState(userId), userId);
7018            if (ai == null) {
7019                return null;
7020            }
7021            final ResolveInfo res = new ResolveInfo();
7022            res.activityInfo = ai;
7023            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7024                res.filter = info;
7025            }
7026            res.priority = info.getPriority();
7027            res.preferredOrder = activity.owner.mPreferredOrder;
7028            //System.out.println("Result: " + res.activityInfo.className +
7029            //                   " = " + res.priority);
7030            res.match = match;
7031            res.isDefault = info.hasDefault;
7032            res.labelRes = info.labelRes;
7033            res.nonLocalizedLabel = info.nonLocalizedLabel;
7034            if (userNeedsBadging(userId)) {
7035                res.noResourceId = true;
7036            } else {
7037                res.icon = info.icon;
7038            }
7039            res.system = isSystemApp(res.activityInfo.applicationInfo);
7040            return res;
7041        }
7042
7043        @Override
7044        protected void sortResults(List<ResolveInfo> results) {
7045            Collections.sort(results, mResolvePrioritySorter);
7046        }
7047
7048        @Override
7049        protected void dumpFilter(PrintWriter out, String prefix,
7050                PackageParser.ActivityIntentInfo filter) {
7051            out.print(prefix); out.print(
7052                    Integer.toHexString(System.identityHashCode(filter.activity)));
7053                    out.print(' ');
7054                    filter.activity.printComponentShortName(out);
7055                    out.print(" filter ");
7056                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7057        }
7058
7059//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7060//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7061//            final List<ResolveInfo> retList = Lists.newArrayList();
7062//            while (i.hasNext()) {
7063//                final ResolveInfo resolveInfo = i.next();
7064//                if (isEnabledLP(resolveInfo.activityInfo)) {
7065//                    retList.add(resolveInfo);
7066//                }
7067//            }
7068//            return retList;
7069//        }
7070
7071        // Keys are String (activity class name), values are Activity.
7072        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7073                = new HashMap<ComponentName, PackageParser.Activity>();
7074        private int mFlags;
7075    }
7076
7077    private final class ServiceIntentResolver
7078            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7079        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7080                boolean defaultOnly, int userId) {
7081            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7082            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7083        }
7084
7085        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7086                int userId) {
7087            if (!sUserManager.exists(userId)) return null;
7088            mFlags = flags;
7089            return super.queryIntent(intent, resolvedType,
7090                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7091        }
7092
7093        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7094                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7095            if (!sUserManager.exists(userId)) return null;
7096            if (packageServices == null) {
7097                return null;
7098            }
7099            mFlags = flags;
7100            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7101            final int N = packageServices.size();
7102            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7103                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7104
7105            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7106            for (int i = 0; i < N; ++i) {
7107                intentFilters = packageServices.get(i).intents;
7108                if (intentFilters != null && intentFilters.size() > 0) {
7109                    PackageParser.ServiceIntentInfo[] array =
7110                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7111                    intentFilters.toArray(array);
7112                    listCut.add(array);
7113                }
7114            }
7115            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7116        }
7117
7118        public final void addService(PackageParser.Service s) {
7119            mServices.put(s.getComponentName(), s);
7120            if (DEBUG_SHOW_INFO) {
7121                Log.v(TAG, "  "
7122                        + (s.info.nonLocalizedLabel != null
7123                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7124                Log.v(TAG, "    Class=" + s.info.name);
7125            }
7126            final int NI = s.intents.size();
7127            int j;
7128            for (j=0; j<NI; j++) {
7129                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7130                if (DEBUG_SHOW_INFO) {
7131                    Log.v(TAG, "    IntentFilter:");
7132                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7133                }
7134                if (!intent.debugCheck()) {
7135                    Log.w(TAG, "==> For Service " + s.info.name);
7136                }
7137                addFilter(intent);
7138            }
7139        }
7140
7141        public final void removeService(PackageParser.Service s) {
7142            mServices.remove(s.getComponentName());
7143            if (DEBUG_SHOW_INFO) {
7144                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7145                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7146                Log.v(TAG, "    Class=" + s.info.name);
7147            }
7148            final int NI = s.intents.size();
7149            int j;
7150            for (j=0; j<NI; j++) {
7151                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7152                if (DEBUG_SHOW_INFO) {
7153                    Log.v(TAG, "    IntentFilter:");
7154                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7155                }
7156                removeFilter(intent);
7157            }
7158        }
7159
7160        @Override
7161        protected boolean allowFilterResult(
7162                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7163            ServiceInfo filterSi = filter.service.info;
7164            for (int i=dest.size()-1; i>=0; i--) {
7165                ServiceInfo destAi = dest.get(i).serviceInfo;
7166                if (destAi.name == filterSi.name
7167                        && destAi.packageName == filterSi.packageName) {
7168                    return false;
7169                }
7170            }
7171            return true;
7172        }
7173
7174        @Override
7175        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7176            return new PackageParser.ServiceIntentInfo[size];
7177        }
7178
7179        @Override
7180        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7181            if (!sUserManager.exists(userId)) return true;
7182            PackageParser.Package p = filter.service.owner;
7183            if (p != null) {
7184                PackageSetting ps = (PackageSetting)p.mExtras;
7185                if (ps != null) {
7186                    // System apps are never considered stopped for purposes of
7187                    // filtering, because there may be no way for the user to
7188                    // actually re-launch them.
7189                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7190                            && ps.getStopped(userId);
7191                }
7192            }
7193            return false;
7194        }
7195
7196        @Override
7197        protected boolean isPackageForFilter(String packageName,
7198                PackageParser.ServiceIntentInfo info) {
7199            return packageName.equals(info.service.owner.packageName);
7200        }
7201
7202        @Override
7203        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7204                int match, int userId) {
7205            if (!sUserManager.exists(userId)) return null;
7206            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7207            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7208                return null;
7209            }
7210            final PackageParser.Service service = info.service;
7211            if (mSafeMode && (service.info.applicationInfo.flags
7212                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7213                return null;
7214            }
7215            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7216            if (ps == null) {
7217                return null;
7218            }
7219            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7220                    ps.readUserState(userId), userId);
7221            if (si == null) {
7222                return null;
7223            }
7224            final ResolveInfo res = new ResolveInfo();
7225            res.serviceInfo = si;
7226            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7227                res.filter = filter;
7228            }
7229            res.priority = info.getPriority();
7230            res.preferredOrder = service.owner.mPreferredOrder;
7231            //System.out.println("Result: " + res.activityInfo.className +
7232            //                   " = " + res.priority);
7233            res.match = match;
7234            res.isDefault = info.hasDefault;
7235            res.labelRes = info.labelRes;
7236            res.nonLocalizedLabel = info.nonLocalizedLabel;
7237            res.icon = info.icon;
7238            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7239            return res;
7240        }
7241
7242        @Override
7243        protected void sortResults(List<ResolveInfo> results) {
7244            Collections.sort(results, mResolvePrioritySorter);
7245        }
7246
7247        @Override
7248        protected void dumpFilter(PrintWriter out, String prefix,
7249                PackageParser.ServiceIntentInfo filter) {
7250            out.print(prefix); out.print(
7251                    Integer.toHexString(System.identityHashCode(filter.service)));
7252                    out.print(' ');
7253                    filter.service.printComponentShortName(out);
7254                    out.print(" filter ");
7255                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7256        }
7257
7258//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7259//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7260//            final List<ResolveInfo> retList = Lists.newArrayList();
7261//            while (i.hasNext()) {
7262//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7263//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7264//                    retList.add(resolveInfo);
7265//                }
7266//            }
7267//            return retList;
7268//        }
7269
7270        // Keys are String (activity class name), values are Activity.
7271        private final HashMap<ComponentName, PackageParser.Service> mServices
7272                = new HashMap<ComponentName, PackageParser.Service>();
7273        private int mFlags;
7274    };
7275
7276    private final class ProviderIntentResolver
7277            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7278        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7279                boolean defaultOnly, int userId) {
7280            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7281            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7282        }
7283
7284        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7285                int userId) {
7286            if (!sUserManager.exists(userId))
7287                return null;
7288            mFlags = flags;
7289            return super.queryIntent(intent, resolvedType,
7290                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7291        }
7292
7293        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7294                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7295            if (!sUserManager.exists(userId))
7296                return null;
7297            if (packageProviders == null) {
7298                return null;
7299            }
7300            mFlags = flags;
7301            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7302            final int N = packageProviders.size();
7303            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7304                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7305
7306            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7307            for (int i = 0; i < N; ++i) {
7308                intentFilters = packageProviders.get(i).intents;
7309                if (intentFilters != null && intentFilters.size() > 0) {
7310                    PackageParser.ProviderIntentInfo[] array =
7311                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7312                    intentFilters.toArray(array);
7313                    listCut.add(array);
7314                }
7315            }
7316            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7317        }
7318
7319        public final void addProvider(PackageParser.Provider p) {
7320            if (mProviders.containsKey(p.getComponentName())) {
7321                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7322                return;
7323            }
7324
7325            mProviders.put(p.getComponentName(), p);
7326            if (DEBUG_SHOW_INFO) {
7327                Log.v(TAG, "  "
7328                        + (p.info.nonLocalizedLabel != null
7329                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7330                Log.v(TAG, "    Class=" + p.info.name);
7331            }
7332            final int NI = p.intents.size();
7333            int j;
7334            for (j = 0; j < NI; j++) {
7335                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7336                if (DEBUG_SHOW_INFO) {
7337                    Log.v(TAG, "    IntentFilter:");
7338                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7339                }
7340                if (!intent.debugCheck()) {
7341                    Log.w(TAG, "==> For Provider " + p.info.name);
7342                }
7343                addFilter(intent);
7344            }
7345        }
7346
7347        public final void removeProvider(PackageParser.Provider p) {
7348            mProviders.remove(p.getComponentName());
7349            if (DEBUG_SHOW_INFO) {
7350                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7351                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7352                Log.v(TAG, "    Class=" + p.info.name);
7353            }
7354            final int NI = p.intents.size();
7355            int j;
7356            for (j = 0; j < NI; j++) {
7357                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7358                if (DEBUG_SHOW_INFO) {
7359                    Log.v(TAG, "    IntentFilter:");
7360                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7361                }
7362                removeFilter(intent);
7363            }
7364        }
7365
7366        @Override
7367        protected boolean allowFilterResult(
7368                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7369            ProviderInfo filterPi = filter.provider.info;
7370            for (int i = dest.size() - 1; i >= 0; i--) {
7371                ProviderInfo destPi = dest.get(i).providerInfo;
7372                if (destPi.name == filterPi.name
7373                        && destPi.packageName == filterPi.packageName) {
7374                    return false;
7375                }
7376            }
7377            return true;
7378        }
7379
7380        @Override
7381        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7382            return new PackageParser.ProviderIntentInfo[size];
7383        }
7384
7385        @Override
7386        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7387            if (!sUserManager.exists(userId))
7388                return true;
7389            PackageParser.Package p = filter.provider.owner;
7390            if (p != null) {
7391                PackageSetting ps = (PackageSetting) p.mExtras;
7392                if (ps != null) {
7393                    // System apps are never considered stopped for purposes of
7394                    // filtering, because there may be no way for the user to
7395                    // actually re-launch them.
7396                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7397                            && ps.getStopped(userId);
7398                }
7399            }
7400            return false;
7401        }
7402
7403        @Override
7404        protected boolean isPackageForFilter(String packageName,
7405                PackageParser.ProviderIntentInfo info) {
7406            return packageName.equals(info.provider.owner.packageName);
7407        }
7408
7409        @Override
7410        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7411                int match, int userId) {
7412            if (!sUserManager.exists(userId))
7413                return null;
7414            final PackageParser.ProviderIntentInfo info = filter;
7415            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7416                return null;
7417            }
7418            final PackageParser.Provider provider = info.provider;
7419            if (mSafeMode && (provider.info.applicationInfo.flags
7420                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7421                return null;
7422            }
7423            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7424            if (ps == null) {
7425                return null;
7426            }
7427            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7428                    ps.readUserState(userId), userId);
7429            if (pi == null) {
7430                return null;
7431            }
7432            final ResolveInfo res = new ResolveInfo();
7433            res.providerInfo = pi;
7434            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7435                res.filter = filter;
7436            }
7437            res.priority = info.getPriority();
7438            res.preferredOrder = provider.owner.mPreferredOrder;
7439            res.match = match;
7440            res.isDefault = info.hasDefault;
7441            res.labelRes = info.labelRes;
7442            res.nonLocalizedLabel = info.nonLocalizedLabel;
7443            res.icon = info.icon;
7444            res.system = isSystemApp(res.providerInfo.applicationInfo);
7445            return res;
7446        }
7447
7448        @Override
7449        protected void sortResults(List<ResolveInfo> results) {
7450            Collections.sort(results, mResolvePrioritySorter);
7451        }
7452
7453        @Override
7454        protected void dumpFilter(PrintWriter out, String prefix,
7455                PackageParser.ProviderIntentInfo filter) {
7456            out.print(prefix);
7457            out.print(
7458                    Integer.toHexString(System.identityHashCode(filter.provider)));
7459            out.print(' ');
7460            filter.provider.printComponentShortName(out);
7461            out.print(" filter ");
7462            out.println(Integer.toHexString(System.identityHashCode(filter)));
7463        }
7464
7465        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7466                = new HashMap<ComponentName, PackageParser.Provider>();
7467        private int mFlags;
7468    };
7469
7470    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7471            new Comparator<ResolveInfo>() {
7472        public int compare(ResolveInfo r1, ResolveInfo r2) {
7473            int v1 = r1.priority;
7474            int v2 = r2.priority;
7475            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7476            if (v1 != v2) {
7477                return (v1 > v2) ? -1 : 1;
7478            }
7479            v1 = r1.preferredOrder;
7480            v2 = r2.preferredOrder;
7481            if (v1 != v2) {
7482                return (v1 > v2) ? -1 : 1;
7483            }
7484            if (r1.isDefault != r2.isDefault) {
7485                return r1.isDefault ? -1 : 1;
7486            }
7487            v1 = r1.match;
7488            v2 = r2.match;
7489            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7490            if (v1 != v2) {
7491                return (v1 > v2) ? -1 : 1;
7492            }
7493            if (r1.system != r2.system) {
7494                return r1.system ? -1 : 1;
7495            }
7496            return 0;
7497        }
7498    };
7499
7500    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7501            new Comparator<ProviderInfo>() {
7502        public int compare(ProviderInfo p1, ProviderInfo p2) {
7503            final int v1 = p1.initOrder;
7504            final int v2 = p2.initOrder;
7505            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7506        }
7507    };
7508
7509    static final void sendPackageBroadcast(String action, String pkg,
7510            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7511            int[] userIds) {
7512        IActivityManager am = ActivityManagerNative.getDefault();
7513        if (am != null) {
7514            try {
7515                if (userIds == null) {
7516                    userIds = am.getRunningUserIds();
7517                }
7518                for (int id : userIds) {
7519                    final Intent intent = new Intent(action,
7520                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7521                    if (extras != null) {
7522                        intent.putExtras(extras);
7523                    }
7524                    if (targetPkg != null) {
7525                        intent.setPackage(targetPkg);
7526                    }
7527                    // Modify the UID when posting to other users
7528                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7529                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7530                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7531                        intent.putExtra(Intent.EXTRA_UID, uid);
7532                    }
7533                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7534                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7535                    if (DEBUG_BROADCASTS) {
7536                        RuntimeException here = new RuntimeException("here");
7537                        here.fillInStackTrace();
7538                        Slog.d(TAG, "Sending to user " + id + ": "
7539                                + intent.toShortString(false, true, false, false)
7540                                + " " + intent.getExtras(), here);
7541                    }
7542                    am.broadcastIntent(null, intent, null, finishedReceiver,
7543                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7544                            finishedReceiver != null, false, id);
7545                }
7546            } catch (RemoteException ex) {
7547            }
7548        }
7549    }
7550
7551    /**
7552     * Check if the external storage media is available. This is true if there
7553     * is a mounted external storage medium or if the external storage is
7554     * emulated.
7555     */
7556    private boolean isExternalMediaAvailable() {
7557        return mMediaMounted || Environment.isExternalStorageEmulated();
7558    }
7559
7560    @Override
7561    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7562        // writer
7563        synchronized (mPackages) {
7564            if (!isExternalMediaAvailable()) {
7565                // If the external storage is no longer mounted at this point,
7566                // the caller may not have been able to delete all of this
7567                // packages files and can not delete any more.  Bail.
7568                return null;
7569            }
7570            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7571            if (lastPackage != null) {
7572                pkgs.remove(lastPackage);
7573            }
7574            if (pkgs.size() > 0) {
7575                return pkgs.get(0);
7576            }
7577        }
7578        return null;
7579    }
7580
7581    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7582        if (false) {
7583            RuntimeException here = new RuntimeException("here");
7584            here.fillInStackTrace();
7585            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7586                    + " andCode=" + andCode, here);
7587        }
7588        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7589                userId, andCode ? 1 : 0, packageName));
7590    }
7591
7592    void startCleaningPackages() {
7593        // reader
7594        synchronized (mPackages) {
7595            if (!isExternalMediaAvailable()) {
7596                return;
7597            }
7598            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7599                return;
7600            }
7601        }
7602        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7603        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7604        IActivityManager am = ActivityManagerNative.getDefault();
7605        if (am != null) {
7606            try {
7607                am.startService(null, intent, null, UserHandle.USER_OWNER);
7608            } catch (RemoteException e) {
7609            }
7610        }
7611    }
7612
7613    private final class AppDirObserver extends FileObserver {
7614        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7615            super(path, mask);
7616            mRootDir = path;
7617            mIsRom = isrom;
7618            mIsPrivileged = isPrivileged;
7619        }
7620
7621        public void onEvent(int event, String path) {
7622            String removedPackage = null;
7623            int removedAppId = -1;
7624            int[] removedUsers = null;
7625            String addedPackage = null;
7626            int addedAppId = -1;
7627            int[] addedUsers = null;
7628
7629            // TODO post a message to the handler to obtain serial ordering
7630            synchronized (mInstallLock) {
7631                String fullPathStr = null;
7632                File fullPath = null;
7633                if (path != null) {
7634                    fullPath = new File(mRootDir, path);
7635                    fullPathStr = fullPath.getPath();
7636                }
7637
7638                if (DEBUG_APP_DIR_OBSERVER)
7639                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7640
7641                if (!isApkFile(fullPath)) {
7642                    if (DEBUG_APP_DIR_OBSERVER)
7643                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7644                    return;
7645                }
7646
7647                // Ignore packages that are being installed or
7648                // have just been installed.
7649                if (ignoreCodePath(fullPathStr)) {
7650                    return;
7651                }
7652                PackageParser.Package p = null;
7653                PackageSetting ps = null;
7654                // reader
7655                synchronized (mPackages) {
7656                    p = mAppDirs.get(fullPathStr);
7657                    if (p != null) {
7658                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7659                        if (ps != null) {
7660                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7661                        } else {
7662                            removedUsers = sUserManager.getUserIds();
7663                        }
7664                    }
7665                    addedUsers = sUserManager.getUserIds();
7666                }
7667                if ((event&REMOVE_EVENTS) != 0) {
7668                    if (ps != null) {
7669                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7670                        removePackageLI(ps, true);
7671                        removedPackage = ps.name;
7672                        removedAppId = ps.appId;
7673                    }
7674                }
7675
7676                if ((event&ADD_EVENTS) != 0) {
7677                    if (p == null) {
7678                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7679                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7680                        if (mIsRom) {
7681                            flags |= PackageParser.PARSE_IS_SYSTEM
7682                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7683                            if (mIsPrivileged) {
7684                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7685                            }
7686                        }
7687                        try {
7688                            p = scanPackageLI(fullPath, flags,
7689                                    SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7690                                    System.currentTimeMillis(), UserHandle.ALL, null);
7691                        } catch (PackageManagerException e) {
7692                            Slog.w(TAG, "Failed to scan " + fullPath + ": " + e.getMessage());
7693                            p = null;
7694                        }
7695                        if (p != null) {
7696                            /*
7697                             * TODO this seems dangerous as the package may have
7698                             * changed since we last acquired the mPackages
7699                             * lock.
7700                             */
7701                            // writer
7702                            synchronized (mPackages) {
7703                                updatePermissionsLPw(p.packageName, p,
7704                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7705                            }
7706                            addedPackage = p.applicationInfo.packageName;
7707                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7708                        }
7709                    }
7710                }
7711
7712                // reader
7713                synchronized (mPackages) {
7714                    mSettings.writeLPr();
7715                }
7716            }
7717
7718            if (removedPackage != null) {
7719                Bundle extras = new Bundle(1);
7720                extras.putInt(Intent.EXTRA_UID, removedAppId);
7721                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7722                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7723                        extras, null, null, removedUsers);
7724            }
7725            if (addedPackage != null) {
7726                Bundle extras = new Bundle(1);
7727                extras.putInt(Intent.EXTRA_UID, addedAppId);
7728                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7729                        extras, null, null, addedUsers);
7730            }
7731        }
7732
7733        private final String mRootDir;
7734        private final boolean mIsRom;
7735        private final boolean mIsPrivileged;
7736    }
7737
7738    @Override
7739    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7740            String installerPackageName, VerificationParams verificationParams,
7741            String packageAbiOverride) {
7742        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7743                null);
7744
7745        final File originFile = new File(originPath);
7746        final int uid = Binder.getCallingUid();
7747        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7748            try {
7749                if (observer != null) {
7750                    observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null);
7751                }
7752            } catch (RemoteException re) {
7753            }
7754            return;
7755        }
7756
7757        UserHandle user;
7758        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7759            user = UserHandle.ALL;
7760        } else {
7761            user = new UserHandle(UserHandle.getUserId(uid));
7762        }
7763
7764        final int filteredFlags;
7765        if (uid == Process.SHELL_UID || uid == 0) {
7766            if (DEBUG_INSTALL) {
7767                Slog.v(TAG, "Install from ADB");
7768            }
7769            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7770        } else {
7771            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7772        }
7773
7774        verificationParams.setInstallerUid(uid);
7775
7776        final Message msg = mHandler.obtainMessage(INIT_COPY);
7777        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7778                installerPackageName, verificationParams, user, packageAbiOverride);
7779        mHandler.sendMessage(msg);
7780    }
7781
7782    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7783            InstallSessionParams params, String installerPackageName, int installerUid,
7784            UserHandle user) {
7785        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7786                params.referrerUri, installerUid, null);
7787
7788        final Message msg = mHandler.obtainMessage(INIT_COPY);
7789        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7790                installerPackageName, verifParams, user, params.abiOverride);
7791        mHandler.sendMessage(msg);
7792    }
7793
7794    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7795        Bundle extras = new Bundle(1);
7796        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7797
7798        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7799                packageName, extras, null, null, new int[] {userId});
7800        try {
7801            IActivityManager am = ActivityManagerNative.getDefault();
7802            final boolean isSystem =
7803                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7804            if (isSystem && am.isUserRunning(userId, false)) {
7805                // The just-installed/enabled app is bundled on the system, so presumed
7806                // to be able to run automatically without needing an explicit launch.
7807                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7808                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7809                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7810                        .setPackage(packageName);
7811                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7812                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7813            }
7814        } catch (RemoteException e) {
7815            // shouldn't happen
7816            Slog.w(TAG, "Unable to bootstrap installed package", e);
7817        }
7818    }
7819
7820    @Override
7821    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7822            int userId) {
7823        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7824        PackageSetting pkgSetting;
7825        final int uid = Binder.getCallingUid();
7826        if (UserHandle.getUserId(uid) != userId) {
7827            mContext.enforceCallingOrSelfPermission(
7828                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7829                    "setApplicationBlockedSetting for user " + userId);
7830        }
7831
7832        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7833            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7834            return false;
7835        }
7836
7837        long callingId = Binder.clearCallingIdentity();
7838        try {
7839            boolean sendAdded = false;
7840            boolean sendRemoved = false;
7841            // writer
7842            synchronized (mPackages) {
7843                pkgSetting = mSettings.mPackages.get(packageName);
7844                if (pkgSetting == null) {
7845                    return false;
7846                }
7847                if (pkgSetting.getBlocked(userId) != blocked) {
7848                    pkgSetting.setBlocked(blocked, userId);
7849                    mSettings.writePackageRestrictionsLPr(userId);
7850                    if (blocked) {
7851                        sendRemoved = true;
7852                    } else {
7853                        sendAdded = true;
7854                    }
7855                }
7856            }
7857            if (sendAdded) {
7858                sendPackageAddedForUser(packageName, pkgSetting, userId);
7859                return true;
7860            }
7861            if (sendRemoved) {
7862                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7863                        "blocking pkg");
7864                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7865            }
7866        } finally {
7867            Binder.restoreCallingIdentity(callingId);
7868        }
7869        return false;
7870    }
7871
7872    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7873            int userId) {
7874        final PackageRemovedInfo info = new PackageRemovedInfo();
7875        info.removedPackage = packageName;
7876        info.removedUsers = new int[] {userId};
7877        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7878        info.sendBroadcast(false, false, false);
7879    }
7880
7881    /**
7882     * Returns true if application is not found or there was an error. Otherwise it returns
7883     * the blocked state of the package for the given user.
7884     */
7885    @Override
7886    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7887        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7888        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7889                "getApplicationBlocked for user " + userId);
7890        PackageSetting pkgSetting;
7891        long callingId = Binder.clearCallingIdentity();
7892        try {
7893            // writer
7894            synchronized (mPackages) {
7895                pkgSetting = mSettings.mPackages.get(packageName);
7896                if (pkgSetting == null) {
7897                    return true;
7898                }
7899                return pkgSetting.getBlocked(userId);
7900            }
7901        } finally {
7902            Binder.restoreCallingIdentity(callingId);
7903        }
7904    }
7905
7906    /**
7907     * @hide
7908     */
7909    @Override
7910    public int installExistingPackageAsUser(String packageName, int userId) {
7911        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7912                null);
7913        PackageSetting pkgSetting;
7914        final int uid = Binder.getCallingUid();
7915        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7916        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7917            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7918        }
7919
7920        long callingId = Binder.clearCallingIdentity();
7921        try {
7922            boolean sendAdded = false;
7923            Bundle extras = new Bundle(1);
7924
7925            // writer
7926            synchronized (mPackages) {
7927                pkgSetting = mSettings.mPackages.get(packageName);
7928                if (pkgSetting == null) {
7929                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7930                }
7931                if (!pkgSetting.getInstalled(userId)) {
7932                    pkgSetting.setInstalled(true, userId);
7933                    pkgSetting.setBlocked(false, userId);
7934                    mSettings.writePackageRestrictionsLPr(userId);
7935                    sendAdded = true;
7936                }
7937            }
7938
7939            if (sendAdded) {
7940                sendPackageAddedForUser(packageName, pkgSetting, userId);
7941            }
7942        } finally {
7943            Binder.restoreCallingIdentity(callingId);
7944        }
7945
7946        return PackageManager.INSTALL_SUCCEEDED;
7947    }
7948
7949    boolean isUserRestricted(int userId, String restrictionKey) {
7950        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7951        if (restrictions.getBoolean(restrictionKey, false)) {
7952            Log.w(TAG, "User is restricted: " + restrictionKey);
7953            return true;
7954        }
7955        return false;
7956    }
7957
7958    @Override
7959    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7960        mContext.enforceCallingOrSelfPermission(
7961                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7962                "Only package verification agents can verify applications");
7963
7964        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7965        final PackageVerificationResponse response = new PackageVerificationResponse(
7966                verificationCode, Binder.getCallingUid());
7967        msg.arg1 = id;
7968        msg.obj = response;
7969        mHandler.sendMessage(msg);
7970    }
7971
7972    @Override
7973    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7974            long millisecondsToDelay) {
7975        mContext.enforceCallingOrSelfPermission(
7976                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7977                "Only package verification agents can extend verification timeouts");
7978
7979        final PackageVerificationState state = mPendingVerification.get(id);
7980        final PackageVerificationResponse response = new PackageVerificationResponse(
7981                verificationCodeAtTimeout, Binder.getCallingUid());
7982
7983        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7984            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7985        }
7986        if (millisecondsToDelay < 0) {
7987            millisecondsToDelay = 0;
7988        }
7989        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7990                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7991            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7992        }
7993
7994        if ((state != null) && !state.timeoutExtended()) {
7995            state.extendTimeout();
7996
7997            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7998            msg.arg1 = id;
7999            msg.obj = response;
8000            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8001        }
8002    }
8003
8004    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8005            int verificationCode, UserHandle user) {
8006        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8007        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8008        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8009        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8010        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8011
8012        mContext.sendBroadcastAsUser(intent, user,
8013                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8014    }
8015
8016    private ComponentName matchComponentForVerifier(String packageName,
8017            List<ResolveInfo> receivers) {
8018        ActivityInfo targetReceiver = null;
8019
8020        final int NR = receivers.size();
8021        for (int i = 0; i < NR; i++) {
8022            final ResolveInfo info = receivers.get(i);
8023            if (info.activityInfo == null) {
8024                continue;
8025            }
8026
8027            if (packageName.equals(info.activityInfo.packageName)) {
8028                targetReceiver = info.activityInfo;
8029                break;
8030            }
8031        }
8032
8033        if (targetReceiver == null) {
8034            return null;
8035        }
8036
8037        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8038    }
8039
8040    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8041            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8042        if (pkgInfo.verifiers.length == 0) {
8043            return null;
8044        }
8045
8046        final int N = pkgInfo.verifiers.length;
8047        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8048        for (int i = 0; i < N; i++) {
8049            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8050
8051            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8052                    receivers);
8053            if (comp == null) {
8054                continue;
8055            }
8056
8057            final int verifierUid = getUidForVerifier(verifierInfo);
8058            if (verifierUid == -1) {
8059                continue;
8060            }
8061
8062            if (DEBUG_VERIFY) {
8063                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8064                        + " with the correct signature");
8065            }
8066            sufficientVerifiers.add(comp);
8067            verificationState.addSufficientVerifier(verifierUid);
8068        }
8069
8070        return sufficientVerifiers;
8071    }
8072
8073    private int getUidForVerifier(VerifierInfo verifierInfo) {
8074        synchronized (mPackages) {
8075            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8076            if (pkg == null) {
8077                return -1;
8078            } else if (pkg.mSignatures.length != 1) {
8079                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8080                        + " has more than one signature; ignoring");
8081                return -1;
8082            }
8083
8084            /*
8085             * If the public key of the package's signature does not match
8086             * our expected public key, then this is a different package and
8087             * we should skip.
8088             */
8089
8090            final byte[] expectedPublicKey;
8091            try {
8092                final Signature verifierSig = pkg.mSignatures[0];
8093                final PublicKey publicKey = verifierSig.getPublicKey();
8094                expectedPublicKey = publicKey.getEncoded();
8095            } catch (CertificateException e) {
8096                return -1;
8097            }
8098
8099            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8100
8101            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8102                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8103                        + " does not have the expected public key; ignoring");
8104                return -1;
8105            }
8106
8107            return pkg.applicationInfo.uid;
8108        }
8109    }
8110
8111    @Override
8112    public void finishPackageInstall(int token) {
8113        enforceSystemOrRoot("Only the system is allowed to finish installs");
8114
8115        if (DEBUG_INSTALL) {
8116            Slog.v(TAG, "BM finishing package install for " + token);
8117        }
8118
8119        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8120        mHandler.sendMessage(msg);
8121    }
8122
8123    /**
8124     * Get the verification agent timeout.
8125     *
8126     * @return verification timeout in milliseconds
8127     */
8128    private long getVerificationTimeout() {
8129        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8130                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8131                DEFAULT_VERIFICATION_TIMEOUT);
8132    }
8133
8134    /**
8135     * Get the default verification agent response code.
8136     *
8137     * @return default verification response code
8138     */
8139    private int getDefaultVerificationResponse() {
8140        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8141                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8142                DEFAULT_VERIFICATION_RESPONSE);
8143    }
8144
8145    /**
8146     * Check whether or not package verification has been enabled.
8147     *
8148     * @return true if verification should be performed
8149     */
8150    private boolean isVerificationEnabled(int userId, int flags) {
8151        if (!DEFAULT_VERIFY_ENABLE) {
8152            return false;
8153        }
8154
8155        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8156
8157        // Check if installing from ADB
8158        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8159            // Do not run verification in a test harness environment
8160            if (ActivityManager.isRunningInTestHarness()) {
8161                return false;
8162            }
8163            if (ensureVerifyAppsEnabled) {
8164                return true;
8165            }
8166            // Check if the developer does not want package verification for ADB installs
8167            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8168                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8169                return false;
8170            }
8171        }
8172
8173        if (ensureVerifyAppsEnabled) {
8174            return true;
8175        }
8176
8177        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8178                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8179    }
8180
8181    /**
8182     * Get the "allow unknown sources" setting.
8183     *
8184     * @return the current "allow unknown sources" setting
8185     */
8186    private int getUnknownSourcesSettings() {
8187        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8188                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8189                -1);
8190    }
8191
8192    @Override
8193    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8194        final int uid = Binder.getCallingUid();
8195        // writer
8196        synchronized (mPackages) {
8197            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8198            if (targetPackageSetting == null) {
8199                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8200            }
8201
8202            PackageSetting installerPackageSetting;
8203            if (installerPackageName != null) {
8204                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8205                if (installerPackageSetting == null) {
8206                    throw new IllegalArgumentException("Unknown installer package: "
8207                            + installerPackageName);
8208                }
8209            } else {
8210                installerPackageSetting = null;
8211            }
8212
8213            Signature[] callerSignature;
8214            Object obj = mSettings.getUserIdLPr(uid);
8215            if (obj != null) {
8216                if (obj instanceof SharedUserSetting) {
8217                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8218                } else if (obj instanceof PackageSetting) {
8219                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8220                } else {
8221                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8222                }
8223            } else {
8224                throw new SecurityException("Unknown calling uid " + uid);
8225            }
8226
8227            // Verify: can't set installerPackageName to a package that is
8228            // not signed with the same cert as the caller.
8229            if (installerPackageSetting != null) {
8230                if (compareSignatures(callerSignature,
8231                        installerPackageSetting.signatures.mSignatures)
8232                        != PackageManager.SIGNATURE_MATCH) {
8233                    throw new SecurityException(
8234                            "Caller does not have same cert as new installer package "
8235                            + installerPackageName);
8236                }
8237            }
8238
8239            // Verify: if target already has an installer package, it must
8240            // be signed with the same cert as the caller.
8241            if (targetPackageSetting.installerPackageName != null) {
8242                PackageSetting setting = mSettings.mPackages.get(
8243                        targetPackageSetting.installerPackageName);
8244                // If the currently set package isn't valid, then it's always
8245                // okay to change it.
8246                if (setting != null) {
8247                    if (compareSignatures(callerSignature,
8248                            setting.signatures.mSignatures)
8249                            != PackageManager.SIGNATURE_MATCH) {
8250                        throw new SecurityException(
8251                                "Caller does not have same cert as old installer package "
8252                                + targetPackageSetting.installerPackageName);
8253                    }
8254                }
8255            }
8256
8257            // Okay!
8258            targetPackageSetting.installerPackageName = installerPackageName;
8259            scheduleWriteSettingsLocked();
8260        }
8261    }
8262
8263    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8264        // Queue up an async operation since the package installation may take a little while.
8265        mHandler.post(new Runnable() {
8266            public void run() {
8267                mHandler.removeCallbacks(this);
8268                 // Result object to be returned
8269                PackageInstalledInfo res = new PackageInstalledInfo();
8270                res.returnCode = currentStatus;
8271                res.uid = -1;
8272                res.pkg = null;
8273                res.removedInfo = new PackageRemovedInfo();
8274                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8275                    args.doPreInstall(res.returnCode);
8276                    synchronized (mInstallLock) {
8277                        installPackageLI(args, true, res);
8278                    }
8279                    args.doPostInstall(res.returnCode, res.uid);
8280                }
8281
8282                // A restore should be performed at this point if (a) the install
8283                // succeeded, (b) the operation is not an update, and (c) the new
8284                // package has a backupAgent defined.
8285                final boolean update = res.removedInfo.removedPackage != null;
8286                boolean doRestore = (!update
8287                        && res.pkg != null
8288                        && res.pkg.applicationInfo.backupAgentName != null);
8289
8290                // Set up the post-install work request bookkeeping.  This will be used
8291                // and cleaned up by the post-install event handling regardless of whether
8292                // there's a restore pass performed.  Token values are >= 1.
8293                int token;
8294                if (mNextInstallToken < 0) mNextInstallToken = 1;
8295                token = mNextInstallToken++;
8296
8297                PostInstallData data = new PostInstallData(args, res);
8298                mRunningInstalls.put(token, data);
8299                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8300
8301                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8302                    // Pass responsibility to the Backup Manager.  It will perform a
8303                    // restore if appropriate, then pass responsibility back to the
8304                    // Package Manager to run the post-install observer callbacks
8305                    // and broadcasts.
8306                    IBackupManager bm = IBackupManager.Stub.asInterface(
8307                            ServiceManager.getService(Context.BACKUP_SERVICE));
8308                    if (bm != null) {
8309                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8310                                + " to BM for possible restore");
8311                        try {
8312                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8313                        } catch (RemoteException e) {
8314                            // can't happen; the backup manager is local
8315                        } catch (Exception e) {
8316                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8317                            doRestore = false;
8318                        }
8319                    } else {
8320                        Slog.e(TAG, "Backup Manager not found!");
8321                        doRestore = false;
8322                    }
8323                }
8324
8325                if (!doRestore) {
8326                    // No restore possible, or the Backup Manager was mysteriously not
8327                    // available -- just fire the post-install work request directly.
8328                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8329                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8330                    mHandler.sendMessage(msg);
8331                }
8332            }
8333        });
8334    }
8335
8336    private abstract class HandlerParams {
8337        private static final int MAX_RETRIES = 4;
8338
8339        /**
8340         * Number of times startCopy() has been attempted and had a non-fatal
8341         * error.
8342         */
8343        private int mRetries = 0;
8344
8345        /** User handle for the user requesting the information or installation. */
8346        private final UserHandle mUser;
8347
8348        HandlerParams(UserHandle user) {
8349            mUser = user;
8350        }
8351
8352        UserHandle getUser() {
8353            return mUser;
8354        }
8355
8356        final boolean startCopy() {
8357            boolean res;
8358            try {
8359                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8360
8361                if (++mRetries > MAX_RETRIES) {
8362                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8363                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8364                    handleServiceError();
8365                    return false;
8366                } else {
8367                    handleStartCopy();
8368                    res = true;
8369                }
8370            } catch (RemoteException e) {
8371                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8372                mHandler.sendEmptyMessage(MCS_RECONNECT);
8373                res = false;
8374            }
8375            handleReturnCode();
8376            return res;
8377        }
8378
8379        final void serviceError() {
8380            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8381            handleServiceError();
8382            handleReturnCode();
8383        }
8384
8385        abstract void handleStartCopy() throws RemoteException;
8386        abstract void handleServiceError();
8387        abstract void handleReturnCode();
8388    }
8389
8390    class MeasureParams extends HandlerParams {
8391        private final PackageStats mStats;
8392        private boolean mSuccess;
8393
8394        private final IPackageStatsObserver mObserver;
8395
8396        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8397            super(new UserHandle(stats.userHandle));
8398            mObserver = observer;
8399            mStats = stats;
8400        }
8401
8402        @Override
8403        public String toString() {
8404            return "MeasureParams{"
8405                + Integer.toHexString(System.identityHashCode(this))
8406                + " " + mStats.packageName + "}";
8407        }
8408
8409        @Override
8410        void handleStartCopy() throws RemoteException {
8411            synchronized (mInstallLock) {
8412                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8413            }
8414
8415            if (mSuccess) {
8416                final boolean mounted;
8417                if (Environment.isExternalStorageEmulated()) {
8418                    mounted = true;
8419                } else {
8420                    final String status = Environment.getExternalStorageState();
8421                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8422                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8423                }
8424
8425                if (mounted) {
8426                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8427
8428                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8429                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8430
8431                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8432                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8433
8434                    // Always subtract cache size, since it's a subdirectory
8435                    mStats.externalDataSize -= mStats.externalCacheSize;
8436
8437                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8438                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8439
8440                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8441                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8442                }
8443            }
8444        }
8445
8446        @Override
8447        void handleReturnCode() {
8448            if (mObserver != null) {
8449                try {
8450                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8451                } catch (RemoteException e) {
8452                    Slog.i(TAG, "Observer no longer exists.");
8453                }
8454            }
8455        }
8456
8457        @Override
8458        void handleServiceError() {
8459            Slog.e(TAG, "Could not measure application " + mStats.packageName
8460                            + " external storage");
8461        }
8462    }
8463
8464    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8465            throws RemoteException {
8466        long result = 0;
8467        for (File path : paths) {
8468            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8469        }
8470        return result;
8471    }
8472
8473    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8474        for (File path : paths) {
8475            try {
8476                mcs.clearDirectory(path.getAbsolutePath());
8477            } catch (RemoteException e) {
8478            }
8479        }
8480    }
8481
8482    class InstallParams extends HandlerParams {
8483        /**
8484         * Location where install is coming from, before it has been
8485         * copied/renamed into place. This could be a single monolithic APK
8486         * file, or a cluster directory. This location may be untrusted.
8487         */
8488        final File originFile;
8489
8490        /**
8491         * Flag indicating that {@link #originFile} has already been staged,
8492         * meaning downstream users don't need to defensively copy the contents.
8493         */
8494        boolean originStaged;
8495
8496        final IPackageInstallObserver2 observer;
8497        int flags;
8498        final String installerPackageName;
8499        final VerificationParams verificationParams;
8500        private InstallArgs mArgs;
8501        private int mRet;
8502        final String packageAbiOverride;
8503        boolean multiArch;
8504
8505        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8506                int flags, String installerPackageName, VerificationParams verificationParams,
8507                UserHandle user, String packageAbiOverride) {
8508            super(user);
8509            this.originFile = Preconditions.checkNotNull(originFile);
8510            this.originStaged = originStaged;
8511            this.observer = observer;
8512            this.flags = flags;
8513            this.installerPackageName = installerPackageName;
8514            this.verificationParams = verificationParams;
8515            this.packageAbiOverride = packageAbiOverride;
8516        }
8517
8518        @Override
8519        public String toString() {
8520            return "InstallParams{"
8521                + Integer.toHexString(System.identityHashCode(this))
8522                + " " + originFile + "}";
8523        }
8524
8525        public ManifestDigest getManifestDigest() {
8526            if (verificationParams == null) {
8527                return null;
8528            }
8529            return verificationParams.getManifestDigest();
8530        }
8531
8532        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8533            String packageName = pkgLite.packageName;
8534            int installLocation = pkgLite.installLocation;
8535            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8536            // reader
8537            synchronized (mPackages) {
8538                PackageParser.Package pkg = mPackages.get(packageName);
8539                if (pkg != null) {
8540                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8541                        // Check for downgrading.
8542                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8543                            if (pkgLite.versionCode < pkg.mVersionCode) {
8544                                Slog.w(TAG, "Can't install update of " + packageName
8545                                        + " update version " + pkgLite.versionCode
8546                                        + " is older than installed version "
8547                                        + pkg.mVersionCode);
8548                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8549                            }
8550                        }
8551                        // Check for updated system application.
8552                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8553                            if (onSd) {
8554                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8555                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8556                            }
8557                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8558                        } else {
8559                            if (onSd) {
8560                                // Install flag overrides everything.
8561                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8562                            }
8563                            // If current upgrade specifies particular preference
8564                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8565                                // Application explicitly specified internal.
8566                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8567                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8568                                // App explictly prefers external. Let policy decide
8569                            } else {
8570                                // Prefer previous location
8571                                if (isExternal(pkg)) {
8572                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8573                                }
8574                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8575                            }
8576                        }
8577                    } else {
8578                        // Invalid install. Return error code
8579                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8580                    }
8581                }
8582            }
8583            // All the special cases have been taken care of.
8584            // Return result based on recommended install location.
8585            if (onSd) {
8586                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8587            }
8588            return pkgLite.recommendedInstallLocation;
8589        }
8590
8591        private long getMemoryLowThreshold() {
8592            final DeviceStorageMonitorInternal
8593                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8594            if (dsm == null) {
8595                return 0L;
8596            }
8597            return dsm.getMemoryLowThreshold();
8598        }
8599
8600        /*
8601         * Invoke remote method to get package information and install
8602         * location values. Override install location based on default
8603         * policy if needed and then create install arguments based
8604         * on the install location.
8605         */
8606        public void handleStartCopy() throws RemoteException {
8607            int ret = PackageManager.INSTALL_SUCCEEDED;
8608            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8609            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8610            PackageInfoLite pkgLite = null;
8611
8612            if (onInt && onSd) {
8613                // Check if both bits are set.
8614                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8615                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8616            } else {
8617                final long lowThreshold = getMemoryLowThreshold();
8618                if (lowThreshold == 0L) {
8619                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8620                }
8621
8622                // Remote call to find out default install location
8623                final String originPath = originFile.getAbsolutePath();
8624                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8625                        packageAbiOverride);
8626                // Keep track of whether this package is a multiArch package until
8627                // we perform a full scan of it. We need to do this because we might
8628                // end up extracting the package shared libraries before we perform
8629                // a full scan.
8630                multiArch = pkgLite.multiArch;
8631
8632                /*
8633                 * If we have too little free space, try to free cache
8634                 * before giving up.
8635                 */
8636                if (pkgLite.recommendedInstallLocation
8637                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8638                    final long size = mContainerService.calculateInstalledSize(
8639                            originPath, isForwardLocked(), packageAbiOverride);
8640                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8641                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8642                                lowThreshold, packageAbiOverride);
8643                    }
8644                    /*
8645                     * The cache free must have deleted the file we
8646                     * downloaded to install.
8647                     *
8648                     * TODO: fix the "freeCache" call to not delete
8649                     *       the file we care about.
8650                     */
8651                    if (pkgLite.recommendedInstallLocation
8652                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8653                        pkgLite.recommendedInstallLocation
8654                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8655                    }
8656                }
8657            }
8658
8659            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8660                int loc = pkgLite.recommendedInstallLocation;
8661                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8662                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8663                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8664                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8665                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8666                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8667                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8668                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8669                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8670                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8671                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8672                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8673                } else {
8674                    // Override with defaults if needed.
8675                    loc = installLocationPolicy(pkgLite, flags);
8676                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8677                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8678                    } else if (!onSd && !onInt) {
8679                        // Override install location with flags
8680                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8681                            // Set the flag to install on external media.
8682                            flags |= PackageManager.INSTALL_EXTERNAL;
8683                            flags &= ~PackageManager.INSTALL_INTERNAL;
8684                        } else {
8685                            // Make sure the flag for installing on external
8686                            // media is unset
8687                            flags |= PackageManager.INSTALL_INTERNAL;
8688                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8689                        }
8690                    }
8691                }
8692            }
8693
8694            final InstallArgs args = createInstallArgs(this);
8695            mArgs = args;
8696
8697            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8698                 /*
8699                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8700                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8701                 */
8702                int userIdentifier = getUser().getIdentifier();
8703                if (userIdentifier == UserHandle.USER_ALL
8704                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8705                    userIdentifier = UserHandle.USER_OWNER;
8706                }
8707
8708                /*
8709                 * Determine if we have any installed package verifiers. If we
8710                 * do, then we'll defer to them to verify the packages.
8711                 */
8712                final int requiredUid = mRequiredVerifierPackage == null ? -1
8713                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8714                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8715                    // TODO: send verifier the install session instead of uri
8716                    final Intent verification = new Intent(
8717                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8718                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8719                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8720
8721                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8722                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8723                            0 /* TODO: Which userId? */);
8724
8725                    if (DEBUG_VERIFY) {
8726                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8727                                + verification.toString() + " with " + pkgLite.verifiers.length
8728                                + " optional verifiers");
8729                    }
8730
8731                    final int verificationId = mPendingVerificationToken++;
8732
8733                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8734
8735                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8736                            installerPackageName);
8737
8738                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8739
8740                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8741                            pkgLite.packageName);
8742
8743                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8744                            pkgLite.versionCode);
8745
8746                    if (verificationParams != null) {
8747                        if (verificationParams.getVerificationURI() != null) {
8748                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8749                                 verificationParams.getVerificationURI());
8750                        }
8751                        if (verificationParams.getOriginatingURI() != null) {
8752                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8753                                  verificationParams.getOriginatingURI());
8754                        }
8755                        if (verificationParams.getReferrer() != null) {
8756                            verification.putExtra(Intent.EXTRA_REFERRER,
8757                                  verificationParams.getReferrer());
8758                        }
8759                        if (verificationParams.getOriginatingUid() >= 0) {
8760                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8761                                  verificationParams.getOriginatingUid());
8762                        }
8763                        if (verificationParams.getInstallerUid() >= 0) {
8764                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8765                                  verificationParams.getInstallerUid());
8766                        }
8767                    }
8768
8769                    final PackageVerificationState verificationState = new PackageVerificationState(
8770                            requiredUid, args);
8771
8772                    mPendingVerification.append(verificationId, verificationState);
8773
8774                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8775                            receivers, verificationState);
8776
8777                    /*
8778                     * If any sufficient verifiers were listed in the package
8779                     * manifest, attempt to ask them.
8780                     */
8781                    if (sufficientVerifiers != null) {
8782                        final int N = sufficientVerifiers.size();
8783                        if (N == 0) {
8784                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8785                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8786                        } else {
8787                            for (int i = 0; i < N; i++) {
8788                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8789
8790                                final Intent sufficientIntent = new Intent(verification);
8791                                sufficientIntent.setComponent(verifierComponent);
8792
8793                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8794                            }
8795                        }
8796                    }
8797
8798                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8799                            mRequiredVerifierPackage, receivers);
8800                    if (ret == PackageManager.INSTALL_SUCCEEDED
8801                            && mRequiredVerifierPackage != null) {
8802                        /*
8803                         * Send the intent to the required verification agent,
8804                         * but only start the verification timeout after the
8805                         * target BroadcastReceivers have run.
8806                         */
8807                        verification.setComponent(requiredVerifierComponent);
8808                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8809                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8810                                new BroadcastReceiver() {
8811                                    @Override
8812                                    public void onReceive(Context context, Intent intent) {
8813                                        final Message msg = mHandler
8814                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8815                                        msg.arg1 = verificationId;
8816                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8817                                    }
8818                                }, null, 0, null, null);
8819
8820                        /*
8821                         * We don't want the copy to proceed until verification
8822                         * succeeds, so null out this field.
8823                         */
8824                        mArgs = null;
8825                    }
8826                } else {
8827                    /*
8828                     * No package verification is enabled, so immediately start
8829                     * the remote call to initiate copy using temporary file.
8830                     */
8831                    ret = args.copyApk(mContainerService, true);
8832                }
8833            }
8834
8835            mRet = ret;
8836        }
8837
8838        @Override
8839        void handleReturnCode() {
8840            // If mArgs is null, then MCS couldn't be reached. When it
8841            // reconnects, it will try again to install. At that point, this
8842            // will succeed.
8843            if (mArgs != null) {
8844                processPendingInstall(mArgs, mRet);
8845            }
8846        }
8847
8848        @Override
8849        void handleServiceError() {
8850            mArgs = createInstallArgs(this);
8851            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8852        }
8853
8854        public boolean isForwardLocked() {
8855            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8856        }
8857    }
8858
8859    /*
8860     * Utility class used in movePackage api.
8861     * srcArgs and targetArgs are not set for invalid flags and make
8862     * sure to do null checks when invoking methods on them.
8863     * We probably want to return ErrorPrams for both failed installs
8864     * and moves.
8865     */
8866    class MoveParams extends HandlerParams {
8867        final IPackageMoveObserver observer;
8868        final int flags;
8869        final String packageName;
8870        final InstallArgs srcArgs;
8871        final InstallArgs targetArgs;
8872        int uid;
8873        int mRet;
8874
8875        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8876                String packageName, String[] instructionSets, int uid, UserHandle user,
8877                boolean isMultiArch) {
8878            super(user);
8879            this.srcArgs = srcArgs;
8880            this.observer = observer;
8881            this.flags = flags;
8882            this.packageName = packageName;
8883            this.uid = uid;
8884            if (srcArgs != null) {
8885                final String codePath = srcArgs.getCodePath();
8886                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8887                        instructionSets, isMultiArch);
8888            } else {
8889                targetArgs = null;
8890            }
8891        }
8892
8893        @Override
8894        public String toString() {
8895            return "MoveParams{"
8896                + Integer.toHexString(System.identityHashCode(this))
8897                + " " + packageName + "}";
8898        }
8899
8900        public void handleStartCopy() throws RemoteException {
8901            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8902            // Check for storage space on target medium
8903            if (!targetArgs.checkFreeStorage(mContainerService)) {
8904                Log.w(TAG, "Insufficient storage to install");
8905                return;
8906            }
8907
8908            mRet = srcArgs.doPreCopy();
8909            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8910                return;
8911            }
8912
8913            mRet = targetArgs.copyApk(mContainerService, false);
8914            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8915                srcArgs.doPostCopy(uid);
8916                return;
8917            }
8918
8919            mRet = srcArgs.doPostCopy(uid);
8920            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8921                return;
8922            }
8923
8924            mRet = targetArgs.doPreInstall(mRet);
8925            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8926                return;
8927            }
8928
8929            if (DEBUG_SD_INSTALL) {
8930                StringBuilder builder = new StringBuilder();
8931                if (srcArgs != null) {
8932                    builder.append("src: ");
8933                    builder.append(srcArgs.getCodePath());
8934                }
8935                if (targetArgs != null) {
8936                    builder.append(" target : ");
8937                    builder.append(targetArgs.getCodePath());
8938                }
8939                Log.i(TAG, builder.toString());
8940            }
8941        }
8942
8943        @Override
8944        void handleReturnCode() {
8945            targetArgs.doPostInstall(mRet, uid);
8946            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8947            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8948                currentStatus = PackageManager.MOVE_SUCCEEDED;
8949            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8950                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8951            }
8952            processPendingMove(this, currentStatus);
8953        }
8954
8955        @Override
8956        void handleServiceError() {
8957            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8958        }
8959    }
8960
8961    /**
8962     * Used during creation of InstallArgs
8963     *
8964     * @param flags package installation flags
8965     * @return true if should be installed on external storage
8966     */
8967    private static boolean installOnSd(int flags) {
8968        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8969            return false;
8970        }
8971        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8972            return true;
8973        }
8974        return false;
8975    }
8976
8977    /**
8978     * Used during creation of InstallArgs
8979     *
8980     * @param flags package installation flags
8981     * @return true if should be installed as forward locked
8982     */
8983    private static boolean installForwardLocked(int flags) {
8984        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8985    }
8986
8987    private InstallArgs createInstallArgs(InstallParams params) {
8988        // TODO: extend to support incoming zero-copy locations
8989
8990        if (installOnSd(params.flags) || params.isForwardLocked()) {
8991            return new AsecInstallArgs(params);
8992        } else {
8993            return new FileInstallArgs(params);
8994        }
8995    }
8996
8997    /**
8998     * Create args that describe an existing installed package. Typically used
8999     * when cleaning up old installs, or used as a move source.
9000     */
9001    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
9002            String resourcePath, String nativeLibraryRoot, String[] instructionSets,
9003            boolean isMultiArch) {
9004        final boolean isInAsec;
9005        if (installOnSd(flags)) {
9006            /* Apps on SD card are always in ASEC containers. */
9007            isInAsec = true;
9008        } else if (installForwardLocked(flags)
9009                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9010            /*
9011             * Forward-locked apps are only in ASEC containers if they're the
9012             * new style
9013             */
9014            isInAsec = true;
9015        } else {
9016            isInAsec = false;
9017        }
9018
9019        if (isInAsec) {
9020            return new AsecInstallArgs(codePath, instructionSets,
9021                    installOnSd(flags), installForwardLocked(flags), isMultiArch);
9022        } else {
9023            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9024                    instructionSets, isMultiArch);
9025        }
9026    }
9027
9028    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
9029            String[] instructionSets, boolean isMultiArch) {
9030        final File codeFile = new File(codePath);
9031        if (installOnSd(flags) || installForwardLocked(flags)) {
9032            String cid = getNextCodePath(codePath, pkgName, "/"
9033                    + AsecInstallArgs.RES_FILE_NAME);
9034            return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags),
9035                    installForwardLocked(flags), isMultiArch);
9036        } else {
9037            return new FileInstallArgs(codeFile, instructionSets, isMultiArch);
9038        }
9039    }
9040
9041    static abstract class InstallArgs {
9042        /** @see InstallParams#originFile */
9043        final File originFile;
9044        /** @see InstallParams#originStaged */
9045        final boolean originStaged;
9046
9047        // TODO: define inherit location
9048
9049        final IPackageInstallObserver2 observer;
9050        // Always refers to PackageManager flags only
9051        final int flags;
9052        final String installerPackageName;
9053        final ManifestDigest manifestDigest;
9054        final UserHandle user;
9055        final String abiOverride;
9056        final boolean multiArch;
9057
9058        // The list of instruction sets supported by this app. This is currently
9059        // only used during the rmdex() phase to clean up resources. We can get rid of this
9060        // if we move dex files under the common app path.
9061        /* nullable */ String[] instructionSets;
9062
9063        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
9064                    int flags, String installerPackageName, ManifestDigest manifestDigest,
9065                    UserHandle user, String[] instructionSets,
9066                    String abiOverride, boolean multiArch) {
9067            this.originFile = originFile;
9068            this.originStaged = originStaged;
9069            this.flags = flags;
9070            this.observer = observer;
9071            this.installerPackageName = installerPackageName;
9072            this.manifestDigest = manifestDigest;
9073            this.user = user;
9074            this.instructionSets = instructionSets;
9075            this.abiOverride = abiOverride;
9076            this.multiArch = multiArch;
9077        }
9078
9079        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9080        abstract int doPreInstall(int status);
9081
9082        /**
9083         * Rename package into final resting place. All paths on the given
9084         * scanned package should be updated to reflect the rename.
9085         */
9086        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9087        abstract int doPostInstall(int status, int uid);
9088
9089        /** @see PackageSettingBase#codePathString */
9090        abstract String getCodePath();
9091        /** @see PackageSettingBase#resourcePathString */
9092        abstract String getResourcePath();
9093        abstract String getLegacyNativeLibraryPath();
9094
9095        // Need installer lock especially for dex file removal.
9096        abstract void cleanUpResourcesLI();
9097        abstract boolean doPostDeleteLI(boolean delete);
9098        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9099
9100        /**
9101         * Called before the source arguments are copied. This is used mostly
9102         * for MoveParams when it needs to read the source file to put it in the
9103         * destination.
9104         */
9105        int doPreCopy() {
9106            return PackageManager.INSTALL_SUCCEEDED;
9107        }
9108
9109        /**
9110         * Called after the source arguments are copied. This is used mostly for
9111         * MoveParams when it needs to read the source file to put it in the
9112         * destination.
9113         *
9114         * @return
9115         */
9116        int doPostCopy(int uid) {
9117            return PackageManager.INSTALL_SUCCEEDED;
9118        }
9119
9120        protected boolean isFwdLocked() {
9121            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9122        }
9123
9124        UserHandle getUser() {
9125            return user;
9126        }
9127    }
9128
9129    /**
9130     * Logic to handle installation of non-ASEC applications, including copying
9131     * and renaming logic.
9132     */
9133    class FileInstallArgs extends InstallArgs {
9134        private File codeFile;
9135        private File resourceFile;
9136        private File legacyNativeLibraryPath;
9137
9138        // Example topology:
9139        // /data/app/com.example/base.apk
9140        // /data/app/com.example/split_foo.apk
9141        // /data/app/com.example/lib/arm/libfoo.so
9142        // /data/app/com.example/lib/arm64/libfoo.so
9143        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9144
9145        /** New install */
9146        FileInstallArgs(InstallParams params) {
9147            super(params.originFile, params.originStaged, params.observer, params.flags,
9148                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9149                    null /* instruction sets */, params.packageAbiOverride,
9150                    params.multiArch);
9151            if (isFwdLocked()) {
9152                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9153            }
9154        }
9155
9156        /** Existing install */
9157        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9158                String[] instructionSets, boolean isMultiArch) {
9159            super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch);
9160            this.codeFile = (codePath != null) ? new File(codePath) : null;
9161            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9162            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9163                    new File(legacyNativeLibraryPath) : null;
9164        }
9165
9166        /** New install from existing */
9167        FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) {
9168            super(originFile, false, null, 0, null, null, null, instructionSets, null,
9169                    isMultiArch);
9170        }
9171
9172        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9173            final long lowThreshold;
9174
9175            final DeviceStorageMonitorInternal
9176                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9177            if (dsm == null) {
9178                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9179                lowThreshold = 0L;
9180            } else {
9181                if (dsm.isMemoryLow()) {
9182                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9183                    return false;
9184                }
9185
9186                lowThreshold = dsm.getMemoryLowThreshold();
9187            }
9188
9189            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9190                    lowThreshold);
9191        }
9192
9193        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9194            int ret = PackageManager.INSTALL_SUCCEEDED;
9195
9196            if (originStaged) {
9197                Slog.d(TAG, originFile + " already staged; skipping copy");
9198                codeFile = originFile;
9199                resourceFile = originFile;
9200            } else {
9201                try {
9202                    final File tempDir = mInstallerService.allocateSessionDir();
9203                    codeFile = tempDir;
9204                    resourceFile = tempDir;
9205                } catch (IOException e) {
9206                    Slog.w(TAG, "Failed to create copy file: " + e);
9207                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9208                }
9209
9210                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9211                    @Override
9212                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9213                        if (!FileUtils.isValidExtFilename(name)) {
9214                            throw new IllegalArgumentException("Invalid filename: " + name);
9215                        }
9216                        try {
9217                            final File file = new File(codeFile, name);
9218                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9219                                    O_RDWR | O_CREAT, 0644);
9220                            Os.chmod(file.getAbsolutePath(), 0644);
9221                            return new ParcelFileDescriptor(fd);
9222                        } catch (ErrnoException e) {
9223                            throw new RemoteException("Failed to open: " + e.getMessage());
9224                        }
9225                    }
9226                };
9227
9228                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9229                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9230                    Slog.e(TAG, "Failed to copy package");
9231                    return ret;
9232                }
9233            }
9234
9235            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9236            NativeLibraryHelper.Handle handle = null;
9237            try {
9238                handle = NativeLibraryHelper.Handle.create(codeFile);
9239                if (multiArch) {
9240                    // Warn if we've set an abiOverride for multi-lib packages..
9241                    // By definition, we need to copy both 32 and 64 bit libraries for
9242                    // such packages.
9243                    if (abiOverride != null) {
9244                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9245                    }
9246
9247                    int copyRet = PackageManager.NO_NATIVE_LIBRARIES;
9248                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9249                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9250                                Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */);
9251                        maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet);
9252                    }
9253
9254                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9255                        copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot,
9256                                Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */);
9257                        maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet);
9258                    }
9259                } else {
9260                    String[] abiList = (abiOverride != null) ?
9261                            new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9262
9263                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null &&
9264                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9265                        abiList = Build.SUPPORTED_32_BIT_ABIS;
9266                    }
9267
9268                    int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList,
9269                            true /* use isa specific subdirs */);
9270                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9271                        Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]");
9272                        return copyRet;
9273                    }
9274                }
9275            } catch (IOException e) {
9276                Slog.e(TAG, "Copying native libraries failed", e);
9277                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9278            } catch (PackageManagerException pme) {
9279                Slog.e(TAG, "Copying native libraries failed", pme);
9280                ret = pme.error;
9281            } finally {
9282                IoUtils.closeQuietly(handle);
9283            }
9284
9285            return ret;
9286        }
9287
9288        int doPreInstall(int status) {
9289            if (status != PackageManager.INSTALL_SUCCEEDED) {
9290                cleanUp();
9291            }
9292            return status;
9293        }
9294
9295        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9296            if (status != PackageManager.INSTALL_SUCCEEDED) {
9297                cleanUp();
9298                return false;
9299            } else {
9300                final File beforeCodeFile = codeFile;
9301                final File afterCodeFile = getNextCodePath(pkg.packageName);
9302
9303                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9304                try {
9305                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9306                } catch (ErrnoException e) {
9307                    Slog.d(TAG, "Failed to rename", e);
9308                    return false;
9309                }
9310
9311                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9312                    Slog.d(TAG, "Failed to restorecon");
9313                    return false;
9314                }
9315
9316                // Reflect the rename internally
9317                codeFile = afterCodeFile;
9318                resourceFile = afterCodeFile;
9319
9320                // Reflect the rename in scanned details
9321                pkg.codePath = afterCodeFile.getAbsolutePath();
9322                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9323                        pkg.baseCodePath);
9324                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9325                        pkg.splitCodePaths);
9326
9327                // Reflect the rename in app info
9328                pkg.applicationInfo.setCodePath(pkg.codePath);
9329                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9330                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9331                pkg.applicationInfo.setResourcePath(pkg.codePath);
9332                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9333                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9334
9335                return true;
9336            }
9337        }
9338
9339        int doPostInstall(int status, int uid) {
9340            if (status != PackageManager.INSTALL_SUCCEEDED) {
9341                cleanUp();
9342            }
9343            return status;
9344        }
9345
9346        @Override
9347        String getCodePath() {
9348            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9349        }
9350
9351        @Override
9352        String getResourcePath() {
9353            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9354        }
9355
9356        @Override
9357        String getLegacyNativeLibraryPath() {
9358            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9359        }
9360
9361        private boolean cleanUp() {
9362            if (codeFile == null || !codeFile.exists()) {
9363                return false;
9364            }
9365
9366            if (codeFile.isDirectory()) {
9367                FileUtils.deleteContents(codeFile);
9368            }
9369            codeFile.delete();
9370
9371            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9372                resourceFile.delete();
9373            }
9374
9375            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9376                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9377                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9378                }
9379                legacyNativeLibraryPath.delete();
9380            }
9381
9382            return true;
9383        }
9384
9385        void cleanUpResourcesLI() {
9386            // Try enumerating all code paths before deleting
9387            List<String> allCodePaths = Collections.EMPTY_LIST;
9388            if (codeFile != null && codeFile.exists()) {
9389                try {
9390                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9391                    allCodePaths = pkg.getAllCodePaths();
9392                } catch (PackageParserException e) {
9393                    // Ignored; we tried our best
9394                }
9395            }
9396
9397            cleanUp();
9398
9399            if (!allCodePaths.isEmpty()) {
9400                if (instructionSets == null) {
9401                    throw new IllegalStateException("instructionSet == null");
9402                }
9403
9404                for (String codePath : allCodePaths) {
9405                    for (String instructionSet : instructionSets) {
9406                        int retCode = mInstaller.rmdex(codePath, instructionSet);
9407                        if (retCode < 0) {
9408                            Slog.w(TAG, "Couldn't remove dex file for package: "
9409                                    + " at location " + codePath + ", retcode=" + retCode);
9410                            // we don't consider this to be a failure of the core package deletion
9411                        }
9412                    }
9413                }
9414            }
9415        }
9416
9417        boolean doPostDeleteLI(boolean delete) {
9418            // XXX err, shouldn't we respect the delete flag?
9419            cleanUpResourcesLI();
9420            return true;
9421        }
9422    }
9423
9424    private boolean isAsecExternal(String cid) {
9425        final String asecPath = PackageHelper.getSdFilesystem(cid);
9426        return !asecPath.startsWith(mAsecInternalPath);
9427    }
9428
9429    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9430            PackageManagerException {
9431        if (copyRet < 0) {
9432            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9433                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9434                throw new PackageManagerException(copyRet, message);
9435            }
9436        }
9437    }
9438
9439    /**
9440     * Extract the MountService "container ID" from the full code path of an
9441     * .apk.
9442     */
9443    static String cidFromCodePath(String fullCodePath) {
9444        int eidx = fullCodePath.lastIndexOf("/");
9445        String subStr1 = fullCodePath.substring(0, eidx);
9446        int sidx = subStr1.lastIndexOf("/");
9447        return subStr1.substring(sidx+1, eidx);
9448    }
9449
9450    /**
9451     * Logic to handle installation of ASEC applications, including copying and
9452     * renaming logic.
9453     */
9454    class AsecInstallArgs extends InstallArgs {
9455        // TODO: teach about handling cluster directories
9456
9457        static final String RES_FILE_NAME = "pkg.apk";
9458        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9459
9460        String cid;
9461        String packagePath;
9462        String resourcePath;
9463        String legacyNativeLibraryDir;
9464
9465        /** New install */
9466        AsecInstallArgs(InstallParams params) {
9467            super(params.originFile, params.originStaged, params.observer, params.flags,
9468                    params.installerPackageName, params.getManifestDigest(),
9469                    params.getUser(), null /* instruction sets */,
9470                    params.packageAbiOverride, params.multiArch);
9471        }
9472
9473        /** Existing install */
9474        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9475                        boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9476            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9477                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9478                    instructionSets, null, isMultiArch);
9479            // Extract cid from fullCodePath
9480            int eidx = fullCodePath.lastIndexOf("/");
9481            String subStr1 = fullCodePath.substring(0, eidx);
9482            int sidx = subStr1.lastIndexOf("/");
9483            cid = subStr1.substring(sidx+1, eidx);
9484            setCachePath(subStr1);
9485        }
9486
9487        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked,
9488                        boolean isMultiArch) {
9489            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9490                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9491                    instructionSets, null, isMultiArch);
9492            this.cid = cid;
9493            setCachePath(PackageHelper.getSdDir(cid));
9494        }
9495
9496        /** New install from existing */
9497        AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets,
9498                boolean isExternal, boolean isForwardLocked, boolean isMultiArch) {
9499            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9500                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9501                    instructionSets, null, isMultiArch);
9502            this.cid = cid;
9503        }
9504
9505        void createCopyFile() {
9506            cid = getTempContainerId();
9507        }
9508
9509        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9510            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9511                    abiOverride);
9512        }
9513
9514        private final boolean isExternal() {
9515            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9516        }
9517
9518        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9519            if (temp) {
9520                createCopyFile();
9521            } else {
9522                /*
9523                 * Pre-emptively destroy the container since it's destroyed if
9524                 * copying fails due to it existing anyway.
9525                 */
9526                PackageHelper.destroySdDir(cid);
9527            }
9528
9529            final String newCachePath = imcs.copyPackageToContainer(
9530                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9531                    isFwdLocked(), abiOverride);
9532
9533            if (newCachePath != null) {
9534                setCachePath(newCachePath);
9535                return PackageManager.INSTALL_SUCCEEDED;
9536            } else {
9537                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9538            }
9539        }
9540
9541        @Override
9542        String getCodePath() {
9543            return packagePath;
9544        }
9545
9546        @Override
9547        String getResourcePath() {
9548            return resourcePath;
9549        }
9550
9551        @Override
9552        String getLegacyNativeLibraryPath() {
9553            return legacyNativeLibraryDir;
9554        }
9555
9556        int doPreInstall(int status) {
9557            if (status != PackageManager.INSTALL_SUCCEEDED) {
9558                // Destroy container
9559                PackageHelper.destroySdDir(cid);
9560            } else {
9561                boolean mounted = PackageHelper.isContainerMounted(cid);
9562                if (!mounted) {
9563                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9564                            Process.SYSTEM_UID);
9565                    if (newCachePath != null) {
9566                        setCachePath(newCachePath);
9567                    } else {
9568                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9569                    }
9570                }
9571            }
9572            return status;
9573        }
9574
9575        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9576            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9577            String newCachePath = null;
9578            if (PackageHelper.isContainerMounted(cid)) {
9579                // Unmount the container
9580                if (!PackageHelper.unMountSdDir(cid)) {
9581                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9582                    return false;
9583                }
9584            }
9585            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9586                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9587                        " which might be stale. Will try to clean up.");
9588                // Clean up the stale container and proceed to recreate.
9589                if (!PackageHelper.destroySdDir(newCacheId)) {
9590                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9591                    return false;
9592                }
9593                // Successfully cleaned up stale container. Try to rename again.
9594                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9595                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9596                            + " inspite of cleaning it up.");
9597                    return false;
9598                }
9599            }
9600            if (!PackageHelper.isContainerMounted(newCacheId)) {
9601                Slog.w(TAG, "Mounting container " + newCacheId);
9602                newCachePath = PackageHelper.mountSdDir(newCacheId,
9603                        getEncryptKey(), Process.SYSTEM_UID);
9604            } else {
9605                newCachePath = PackageHelper.getSdDir(newCacheId);
9606            }
9607            if (newCachePath == null) {
9608                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9609                return false;
9610            }
9611            Log.i(TAG, "Succesfully renamed " + cid +
9612                    " to " + newCacheId +
9613                    " at new path: " + newCachePath);
9614            cid = newCacheId;
9615            setCachePath(newCachePath);
9616
9617            // TODO: extend to support split APKs
9618            pkg.codePath = getCodePath();
9619            pkg.baseCodePath = getCodePath();
9620            pkg.splitCodePaths = null;
9621
9622            pkg.applicationInfo.setCodePath(getCodePath());
9623            pkg.applicationInfo.setBaseCodePath(getCodePath());
9624            pkg.applicationInfo.setSplitCodePaths(null);
9625            pkg.applicationInfo.setResourcePath(getResourcePath());
9626            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9627            pkg.applicationInfo.setSplitResourcePaths(null);
9628
9629            return true;
9630        }
9631
9632        private void setCachePath(String newCachePath) {
9633            File cachePath = new File(newCachePath);
9634            legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath();
9635            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9636
9637            if (isFwdLocked()) {
9638                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9639            } else {
9640                resourcePath = packagePath;
9641            }
9642        }
9643
9644        int doPostInstall(int status, int uid) {
9645            if (status != PackageManager.INSTALL_SUCCEEDED) {
9646                cleanUp();
9647            } else {
9648                final int groupOwner;
9649                final String protectedFile;
9650                if (isFwdLocked()) {
9651                    groupOwner = UserHandle.getSharedAppGid(uid);
9652                    protectedFile = RES_FILE_NAME;
9653                } else {
9654                    groupOwner = -1;
9655                    protectedFile = null;
9656                }
9657
9658                if (uid < Process.FIRST_APPLICATION_UID
9659                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9660                    Slog.e(TAG, "Failed to finalize " + cid);
9661                    PackageHelper.destroySdDir(cid);
9662                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9663                }
9664
9665                boolean mounted = PackageHelper.isContainerMounted(cid);
9666                if (!mounted) {
9667                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9668                }
9669            }
9670            return status;
9671        }
9672
9673        private void cleanUp() {
9674            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9675
9676            // Destroy secure container
9677            PackageHelper.destroySdDir(cid);
9678        }
9679
9680        void cleanUpResourcesLI() {
9681            String sourceFile = getCodePath();
9682            // Remove dex file
9683            if (instructionSets == null) {
9684                throw new IllegalStateException("instructionSet == null");
9685            }
9686            for (String instructionSet : instructionSets) {
9687                int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9688                if (retCode < 0) {
9689                    Slog.w(TAG, "Couldn't remove dex file for package: "
9690                            + " at location "
9691                            + sourceFile.toString() + ", retcode=" + retCode);
9692                    // we don't consider this to be a failure of the core package deletion
9693                }
9694            }
9695            cleanUp();
9696        }
9697
9698        boolean matchContainer(String app) {
9699            if (cid.startsWith(app)) {
9700                return true;
9701            }
9702            return false;
9703        }
9704
9705        String getPackageName() {
9706            return getAsecPackageName(cid);
9707        }
9708
9709        boolean doPostDeleteLI(boolean delete) {
9710            boolean ret = false;
9711            boolean mounted = PackageHelper.isContainerMounted(cid);
9712            if (mounted) {
9713                // Unmount first
9714                ret = PackageHelper.unMountSdDir(cid);
9715            }
9716            if (ret && delete) {
9717                cleanUpResourcesLI();
9718            }
9719            return ret;
9720        }
9721
9722        @Override
9723        int doPreCopy() {
9724            if (isFwdLocked()) {
9725                if (!PackageHelper.fixSdPermissions(cid,
9726                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9727                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9728                }
9729            }
9730
9731            return PackageManager.INSTALL_SUCCEEDED;
9732        }
9733
9734        @Override
9735        int doPostCopy(int uid) {
9736            if (isFwdLocked()) {
9737                if (uid < Process.FIRST_APPLICATION_UID
9738                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9739                                RES_FILE_NAME)) {
9740                    Slog.e(TAG, "Failed to finalize " + cid);
9741                    PackageHelper.destroySdDir(cid);
9742                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9743                }
9744            }
9745
9746            return PackageManager.INSTALL_SUCCEEDED;
9747        }
9748    }
9749
9750    static String getAsecPackageName(String packageCid) {
9751        int idx = packageCid.lastIndexOf("-");
9752        if (idx == -1) {
9753            return packageCid;
9754        }
9755        return packageCid.substring(0, idx);
9756    }
9757
9758    // Utility method used to create code paths based on package name and available index.
9759    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9760        String idxStr = "";
9761        int idx = 1;
9762        // Fall back to default value of idx=1 if prefix is not
9763        // part of oldCodePath
9764        if (oldCodePath != null) {
9765            String subStr = oldCodePath;
9766            // Drop the suffix right away
9767            if (suffix != null && subStr.endsWith(suffix)) {
9768                subStr = subStr.substring(0, subStr.length() - suffix.length());
9769            }
9770            // If oldCodePath already contains prefix find out the
9771            // ending index to either increment or decrement.
9772            int sidx = subStr.lastIndexOf(prefix);
9773            if (sidx != -1) {
9774                subStr = subStr.substring(sidx + prefix.length());
9775                if (subStr != null) {
9776                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9777                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9778                    }
9779                    try {
9780                        idx = Integer.parseInt(subStr);
9781                        if (idx <= 1) {
9782                            idx++;
9783                        } else {
9784                            idx--;
9785                        }
9786                    } catch(NumberFormatException e) {
9787                    }
9788                }
9789            }
9790        }
9791        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9792        return prefix + idxStr;
9793    }
9794
9795    private File getNextCodePath(String packageName) {
9796        int suffix = 1;
9797        File result;
9798        do {
9799            result = new File(mAppInstallDir, packageName + "-" + suffix);
9800            suffix++;
9801        } while (result.exists());
9802        return result;
9803    }
9804
9805    // Utility method used to ignore ADD/REMOVE events
9806    // by directory observer.
9807    private static boolean ignoreCodePath(String fullPathStr) {
9808        String apkName = deriveCodePathName(fullPathStr);
9809        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9810        if (idx != -1 && ((idx+1) < apkName.length())) {
9811            // Make sure the package ends with a numeral
9812            String version = apkName.substring(idx+1);
9813            try {
9814                Integer.parseInt(version);
9815                return true;
9816            } catch (NumberFormatException e) {}
9817        }
9818        return false;
9819    }
9820
9821    // Utility method that returns the relative package path with respect
9822    // to the installation directory. Like say for /data/data/com.test-1.apk
9823    // string com.test-1 is returned.
9824    static String deriveCodePathName(String codePath) {
9825        if (codePath == null) {
9826            return null;
9827        }
9828        final File codeFile = new File(codePath);
9829        final String name = codeFile.getName();
9830        if (codeFile.isDirectory()) {
9831            return name;
9832        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9833            final int lastDot = name.lastIndexOf('.');
9834            return name.substring(0, lastDot);
9835        } else {
9836            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9837            return null;
9838        }
9839    }
9840
9841    class PackageInstalledInfo {
9842        String name;
9843        int uid;
9844        // The set of users that originally had this package installed.
9845        int[] origUsers;
9846        // The set of users that now have this package installed.
9847        int[] newUsers;
9848        PackageParser.Package pkg;
9849        int returnCode;
9850        String returnMsg;
9851        PackageRemovedInfo removedInfo;
9852
9853        public void setError(int code, String msg) {
9854            returnCode = code;
9855            returnMsg = msg;
9856            Slog.w(TAG, msg);
9857        }
9858
9859        public void setError(String msg, PackageParserException e) {
9860            returnCode = e.error;
9861            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9862            Slog.w(TAG, msg, e);
9863        }
9864
9865        public void setError(String msg, PackageManagerException e) {
9866            returnCode = e.error;
9867            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9868            Slog.w(TAG, msg, e);
9869        }
9870
9871        // In some error cases we want to convey more info back to the observer
9872        String origPackage;
9873        String origPermission;
9874    }
9875
9876    /*
9877     * Install a non-existing package.
9878     */
9879    private void installNewPackageLI(PackageParser.Package pkg,
9880            int parseFlags, int scanMode, UserHandle user,
9881            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9882        // Remember this for later, in case we need to rollback this install
9883        String pkgName = pkg.packageName;
9884
9885        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9886        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9887        synchronized(mPackages) {
9888            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9889                // A package with the same name is already installed, though
9890                // it has been renamed to an older name.  The package we
9891                // are trying to install should be installed as an update to
9892                // the existing one, but that has not been requested, so bail.
9893                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9894                        + " without first uninstalling package running as "
9895                        + mSettings.mRenamedPackages.get(pkgName));
9896                return;
9897            }
9898            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9899                // Don't allow installation over an existing package with the same name.
9900                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9901                        + " without first uninstalling.");
9902                return;
9903            }
9904        }
9905
9906        try {
9907            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9908                    System.currentTimeMillis(), user, abiOverride);
9909
9910            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9911            // delete the partially installed application. the data directory will have to be
9912            // restored if it was already existing
9913            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9914                // remove package from internal structures.  Note that we want deletePackageX to
9915                // delete the package data and cache directories that it created in
9916                // scanPackageLocked, unless those directories existed before we even tried to
9917                // install.
9918                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9919                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9920                                res.removedInfo, true);
9921            }
9922
9923        } catch (PackageManagerException e) {
9924            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9925        }
9926    }
9927
9928    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9929        // Upgrade keysets are being used.  Determine if new package has a superset of the
9930        // required keys.
9931        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9932        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9933        for (int i = 0; i < upgradeKeySets.length; i++) {
9934            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9935            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9936                return true;
9937            }
9938        }
9939        return false;
9940    }
9941
9942    private void replacePackageLI(PackageParser.Package pkg,
9943            int parseFlags, int scanMode, UserHandle user,
9944            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9945        PackageParser.Package oldPackage;
9946        String pkgName = pkg.packageName;
9947        int[] allUsers;
9948        boolean[] perUserInstalled;
9949
9950        // First find the old package info and check signatures
9951        synchronized(mPackages) {
9952            oldPackage = mPackages.get(pkgName);
9953            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9954            PackageSetting ps = mSettings.mPackages.get(pkgName);
9955            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9956                // default to original signature matching
9957                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9958                    != PackageManager.SIGNATURE_MATCH) {
9959                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9960                            "New package has a different signature: " + pkgName);
9961                    return;
9962                }
9963            } else {
9964                if(!checkUpgradeKeySetLP(ps, pkg)) {
9965                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9966                            "New package not signed by keys specified by upgrade-keysets: "
9967                            + pkgName);
9968                    return;
9969                }
9970            }
9971
9972            // In case of rollback, remember per-user/profile install state
9973            allUsers = sUserManager.getUserIds();
9974            perUserInstalled = new boolean[allUsers.length];
9975            for (int i = 0; i < allUsers.length; i++) {
9976                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9977            }
9978        }
9979        boolean sysPkg = (isSystemApp(oldPackage));
9980        if (sysPkg) {
9981            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9982                    user, allUsers, perUserInstalled, installerPackageName, res,
9983                    abiOverride);
9984        } else {
9985            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9986                    user, allUsers, perUserInstalled, installerPackageName, res,
9987                    abiOverride);
9988        }
9989    }
9990
9991    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9992            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9993            int[] allUsers, boolean[] perUserInstalled,
9994            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9995        String pkgName = deletedPackage.packageName;
9996        boolean deletedPkg = true;
9997        boolean updatedSettings = false;
9998
9999        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10000                + deletedPackage);
10001        long origUpdateTime;
10002        if (pkg.mExtras != null) {
10003            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10004        } else {
10005            origUpdateTime = 0;
10006        }
10007
10008        // First delete the existing package while retaining the data directory
10009        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10010                res.removedInfo, true)) {
10011            // If the existing package wasn't successfully deleted
10012            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10013            deletedPkg = false;
10014        } else {
10015            // Successfully deleted the old package. Now proceed with re-installation
10016            try {
10017                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10018                        scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride);
10019                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10020                updatedSettings = true;
10021            } catch (PackageManagerException e) {
10022                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10023            }
10024        }
10025
10026        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10027            // remove package from internal structures.  Note that we want deletePackageX to
10028            // delete the package data and cache directories that it created in
10029            // scanPackageLocked, unless those directories existed before we even tried to
10030            // install.
10031            if(updatedSettings) {
10032                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10033                deletePackageLI(
10034                        pkgName, null, true, allUsers, perUserInstalled,
10035                        PackageManager.DELETE_KEEP_DATA,
10036                                res.removedInfo, true);
10037            }
10038            // Since we failed to install the new package we need to restore the old
10039            // package that we deleted.
10040            if (deletedPkg) {
10041                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10042                File restoreFile = new File(deletedPackage.codePath);
10043                // Parse old package
10044                boolean oldOnSd = isExternal(deletedPackage);
10045                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10046                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10047                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10048                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
10049                        | SCAN_UPDATE_TIME;
10050                try {
10051                    scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null,
10052                            null);
10053                } catch (PackageManagerException e) {
10054                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10055                            + e.getMessage());
10056                    return;
10057                }
10058                // Restore of old package succeeded. Update permissions.
10059                // writer
10060                synchronized (mPackages) {
10061                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10062                            UPDATE_PERMISSIONS_ALL);
10063                    // can downgrade to reader
10064                    mSettings.writeLPr();
10065                }
10066                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10067            }
10068        }
10069    }
10070
10071    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10072            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10073            int[] allUsers, boolean[] perUserInstalled,
10074            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10075        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10076                + ", old=" + deletedPackage);
10077        boolean updatedSettings = false;
10078        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10079                PackageParser.PARSE_IS_SYSTEM;
10080        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10081            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10082        }
10083        String packageName = deletedPackage.packageName;
10084        if (packageName == null) {
10085            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10086                    "Attempt to delete null packageName.");
10087            return;
10088        }
10089        PackageParser.Package oldPkg;
10090        PackageSetting oldPkgSetting;
10091        // reader
10092        synchronized (mPackages) {
10093            oldPkg = mPackages.get(packageName);
10094            oldPkgSetting = mSettings.mPackages.get(packageName);
10095            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10096                    (oldPkgSetting == null)) {
10097                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10098                        "Couldn't find package:" + packageName + " information");
10099                return;
10100            }
10101        }
10102
10103        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10104
10105        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10106        res.removedInfo.removedPackage = packageName;
10107        // Remove existing system package
10108        removePackageLI(oldPkgSetting, true);
10109        // writer
10110        synchronized (mPackages) {
10111            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10112                // We didn't need to disable the .apk as a current system package,
10113                // which means we are replacing another update that is already
10114                // installed.  We need to make sure to delete the older one's .apk.
10115                res.removedInfo.args = createInstallArgsForExisting(0,
10116                        deletedPackage.applicationInfo.getCodePath(),
10117                        deletedPackage.applicationInfo.getResourcePath(),
10118                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10119                        getAppDexInstructionSets(deletedPackage.applicationInfo),
10120                        isMultiArch(deletedPackage.applicationInfo));
10121            } else {
10122                res.removedInfo.args = null;
10123            }
10124        }
10125
10126        // Successfully disabled the old package. Now proceed with re-installation
10127        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10128        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10129
10130        PackageParser.Package newPackage = null;
10131        try {
10132            newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10133            if (newPackage.mExtras != null) {
10134                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10135                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10136                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10137
10138                // is the update attempting to change shared user? that isn't going to work...
10139                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10140                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10141                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10142                            + " to " + newPkgSetting.sharedUser);
10143                    updatedSettings = true;
10144                }
10145            }
10146
10147            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10148                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10149                updatedSettings = true;
10150            }
10151
10152        } catch (PackageManagerException e) {
10153            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10154        }
10155
10156        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10157            // Re installation failed. Restore old information
10158            // Remove new pkg information
10159            if (newPackage != null) {
10160                removeInstalledPackageLI(newPackage, true);
10161            }
10162            // Add back the old system package
10163            try {
10164                scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user,
10165                        null);
10166            } catch (PackageManagerException e) {
10167                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10168            }
10169            // Restore the old system information in Settings
10170            synchronized(mPackages) {
10171                if (updatedSettings) {
10172                    mSettings.enableSystemPackageLPw(packageName);
10173                    mSettings.setInstallerPackageName(packageName,
10174                            oldPkgSetting.installerPackageName);
10175                }
10176                mSettings.writeLPr();
10177            }
10178        }
10179    }
10180
10181    // Utility method used to move dex files during install.
10182    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10183        // TODO: extend to move split APK dex files
10184        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10185            final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo);
10186            for (String instructionSet : instructionSets) {
10187                int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
10188                        instructionSet);
10189                if (retCode != 0) {
10190                /*
10191                 * Programs may be lazily run through dexopt, so the
10192                 * source may not exist. However, something seems to
10193                 * have gone wrong, so note that dexopt needs to be
10194                 * run again and remove the source file. In addition,
10195                 * remove the target to make sure there isn't a stale
10196                 * file from a previous version of the package.
10197                 */
10198                    newPackage.mDexOptNeeded = true;
10199                    mInstaller.rmdex(oldCodePath, instructionSet);
10200                    mInstaller.rmdex(newPackage.baseCodePath, instructionSet);
10201                }
10202            }
10203        }
10204        return PackageManager.INSTALL_SUCCEEDED;
10205    }
10206
10207    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10208            int[] allUsers, boolean[] perUserInstalled,
10209            PackageInstalledInfo res) {
10210        String pkgName = newPackage.packageName;
10211        synchronized (mPackages) {
10212            //write settings. the installStatus will be incomplete at this stage.
10213            //note that the new package setting would have already been
10214            //added to mPackages. It hasn't been persisted yet.
10215            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10216            mSettings.writeLPr();
10217        }
10218
10219        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10220
10221        synchronized (mPackages) {
10222            updatePermissionsLPw(newPackage.packageName, newPackage,
10223                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10224                            ? UPDATE_PERMISSIONS_ALL : 0));
10225            // For system-bundled packages, we assume that installing an upgraded version
10226            // of the package implies that the user actually wants to run that new code,
10227            // so we enable the package.
10228            if (isSystemApp(newPackage)) {
10229                // NB: implicit assumption that system package upgrades apply to all users
10230                if (DEBUG_INSTALL) {
10231                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10232                }
10233                PackageSetting ps = mSettings.mPackages.get(pkgName);
10234                if (ps != null) {
10235                    if (res.origUsers != null) {
10236                        for (int userHandle : res.origUsers) {
10237                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10238                                    userHandle, installerPackageName);
10239                        }
10240                    }
10241                    // Also convey the prior install/uninstall state
10242                    if (allUsers != null && perUserInstalled != null) {
10243                        for (int i = 0; i < allUsers.length; i++) {
10244                            if (DEBUG_INSTALL) {
10245                                Slog.d(TAG, "    user " + allUsers[i]
10246                                        + " => " + perUserInstalled[i]);
10247                            }
10248                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10249                        }
10250                        // these install state changes will be persisted in the
10251                        // upcoming call to mSettings.writeLPr().
10252                    }
10253                }
10254            }
10255            res.name = pkgName;
10256            res.uid = newPackage.applicationInfo.uid;
10257            res.pkg = newPackage;
10258            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10259            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10260            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10261            //to update install status
10262            mSettings.writeLPr();
10263        }
10264    }
10265
10266    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10267        int pFlags = args.flags;
10268        String installerPackageName = args.installerPackageName;
10269        File tmpPackageFile = new File(args.getCodePath());
10270        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10271        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10272        boolean replace = false;
10273        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10274                | (newInstall ? SCAN_NEW_INSTALL : 0);
10275        // Result object to be returned
10276        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10277
10278        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10279        // Retrieve PackageSettings and parse package
10280        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10281                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10282                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10283        PackageParser pp = new PackageParser();
10284        pp.setSeparateProcesses(mSeparateProcesses);
10285        pp.setDisplayMetrics(mMetrics);
10286
10287        final PackageParser.Package pkg;
10288        try {
10289            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10290        } catch (PackageParserException e) {
10291            res.setError("Failed parse during installPackageLI", e);
10292            return;
10293        }
10294
10295        String pkgName = res.name = pkg.packageName;
10296        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10297            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10298                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10299                return;
10300            }
10301        }
10302
10303        try {
10304            pp.collectCertificates(pkg, parseFlags);
10305            pp.collectManifestDigest(pkg);
10306        } catch (PackageParserException e) {
10307            res.setError("Failed collect during installPackageLI", e);
10308            return;
10309        }
10310
10311        /* If the installer passed in a manifest digest, compare it now. */
10312        if (args.manifestDigest != null) {
10313            if (DEBUG_INSTALL) {
10314                final String parsedManifest = pkg.manifestDigest == null ? "null"
10315                        : pkg.manifestDigest.toString();
10316                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10317                        + parsedManifest);
10318            }
10319
10320            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10321                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10322                return;
10323            }
10324        } else if (DEBUG_INSTALL) {
10325            final String parsedManifest = pkg.manifestDigest == null
10326                    ? "null" : pkg.manifestDigest.toString();
10327            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10328        }
10329
10330        // Get rid of all references to package scan path via parser.
10331        pp = null;
10332        String oldCodePath = null;
10333        boolean systemApp = false;
10334        synchronized (mPackages) {
10335            // Check whether the newly-scanned package wants to define an already-defined perm
10336            int N = pkg.permissions.size();
10337            for (int i = N-1; i >= 0; i--) {
10338                PackageParser.Permission perm = pkg.permissions.get(i);
10339                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10340                if (bp != null) {
10341                    // If the defining package is signed with our cert, it's okay.  This
10342                    // also includes the "updating the same package" case, of course.
10343                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10344                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10345                        // If the owning package is the system itself, we log but allow
10346                        // install to proceed; we fail the install on all other permission
10347                        // redefinitions.
10348                        if (!bp.sourcePackage.equals("android")) {
10349                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10350                                    + pkg.packageName + " attempting to redeclare permission "
10351                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10352                            res.origPermission = perm.info.name;
10353                            res.origPackage = bp.sourcePackage;
10354                            return;
10355                        } else {
10356                            Slog.w(TAG, "Package " + pkg.packageName
10357                                    + " attempting to redeclare system permission "
10358                                    + perm.info.name + "; ignoring new declaration");
10359                            pkg.permissions.remove(i);
10360                        }
10361                    }
10362                }
10363            }
10364
10365            // Check if installing already existing package
10366            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10367                String oldName = mSettings.mRenamedPackages.get(pkgName);
10368                if (pkg.mOriginalPackages != null
10369                        && pkg.mOriginalPackages.contains(oldName)
10370                        && mPackages.containsKey(oldName)) {
10371                    // This package is derived from an original package,
10372                    // and this device has been updating from that original
10373                    // name.  We must continue using the original name, so
10374                    // rename the new package here.
10375                    pkg.setPackageName(oldName);
10376                    pkgName = pkg.packageName;
10377                    replace = true;
10378                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10379                            + oldName + " pkgName=" + pkgName);
10380                } else if (mPackages.containsKey(pkgName)) {
10381                    // This package, under its official name, already exists
10382                    // on the device; we should replace it.
10383                    replace = true;
10384                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10385                }
10386            }
10387            PackageSetting ps = mSettings.mPackages.get(pkgName);
10388            if (ps != null) {
10389                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10390                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10391                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10392                    systemApp = (ps.pkg.applicationInfo.flags &
10393                            ApplicationInfo.FLAG_SYSTEM) != 0;
10394                }
10395                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10396            }
10397        }
10398
10399        if (systemApp && onSd) {
10400            // Disable updates to system apps on sdcard
10401            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10402                    "Cannot install updates to system apps on sdcard");
10403            return;
10404        }
10405
10406        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10407            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10408            return;
10409        }
10410
10411        if (replace) {
10412            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10413                    installerPackageName, res, args.abiOverride);
10414        } else {
10415            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10416                    installerPackageName, res, args.abiOverride);
10417        }
10418        synchronized (mPackages) {
10419            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10420            if (ps != null) {
10421                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10422            }
10423        }
10424    }
10425
10426    private static boolean isForwardLocked(PackageParser.Package pkg) {
10427        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10428    }
10429
10430    private static boolean isForwardLocked(ApplicationInfo info) {
10431        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10432    }
10433
10434    private boolean isForwardLocked(PackageSetting ps) {
10435        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10436    }
10437
10438    private static boolean isMultiArch(PackageSetting ps) {
10439        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10440    }
10441
10442    private static boolean isMultiArch(ApplicationInfo info) {
10443        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10444    }
10445
10446    private static boolean isExternal(PackageParser.Package pkg) {
10447        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10448    }
10449
10450    private static boolean isExternal(PackageSetting ps) {
10451        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10452    }
10453
10454    private static boolean isExternal(ApplicationInfo info) {
10455        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10456    }
10457
10458    private static boolean isSystemApp(PackageParser.Package pkg) {
10459        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10460    }
10461
10462    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10463        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10464    }
10465
10466    private static boolean isSystemApp(ApplicationInfo info) {
10467        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10468    }
10469
10470    private static boolean isSystemApp(PackageSetting ps) {
10471        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10472    }
10473
10474    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10475        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10476    }
10477
10478    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10479        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10480    }
10481
10482    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10483        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10484    }
10485
10486    private int packageFlagsToInstallFlags(PackageSetting ps) {
10487        int installFlags = 0;
10488        if (isExternal(ps)) {
10489            installFlags |= PackageManager.INSTALL_EXTERNAL;
10490        }
10491        if (isForwardLocked(ps)) {
10492            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10493        }
10494        return installFlags;
10495    }
10496
10497    private void deleteTempPackageFiles() {
10498        final FilenameFilter filter = new FilenameFilter() {
10499            public boolean accept(File dir, String name) {
10500                return name.startsWith("vmdl") && name.endsWith(".tmp");
10501            }
10502        };
10503        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10504            file.delete();
10505        }
10506    }
10507
10508    @Override
10509    public void deletePackageAsUser(final String packageName,
10510                                    final IPackageDeleteObserver observer,
10511                                    final int userId, final int flags) {
10512        mContext.enforceCallingOrSelfPermission(
10513                android.Manifest.permission.DELETE_PACKAGES, null);
10514        final int uid = Binder.getCallingUid();
10515        if (UserHandle.getUserId(uid) != userId) {
10516            mContext.enforceCallingPermission(
10517                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10518                    "deletePackage for user " + userId);
10519        }
10520        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10521            try {
10522                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10523            } catch (RemoteException re) {
10524            }
10525            return;
10526        }
10527
10528        boolean blocked = false;
10529        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10530            int[] users = sUserManager.getUserIds();
10531            for (int i = 0; i < users.length; ++i) {
10532                if (getBlockUninstallForUser(packageName, users[i])) {
10533                    blocked = true;
10534                    break;
10535                }
10536            }
10537        } else {
10538            blocked = getBlockUninstallForUser(packageName, userId);
10539        }
10540        if (blocked) {
10541            try {
10542                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED);
10543            } catch (RemoteException re) {
10544            }
10545            return;
10546        }
10547
10548        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10549        // Queue up an async operation since the package deletion may take a little while.
10550        mHandler.post(new Runnable() {
10551            public void run() {
10552                mHandler.removeCallbacks(this);
10553                final int returnCode = deletePackageX(packageName, userId, flags);
10554                if (observer != null) {
10555                    try {
10556                        observer.packageDeleted(packageName, returnCode);
10557                    } catch (RemoteException e) {
10558                        Log.i(TAG, "Observer no longer exists.");
10559                    } //end catch
10560                } //end if
10561            } //end run
10562        });
10563    }
10564
10565    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10566        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10567                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10568        try {
10569            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10570                    || dpm.isDeviceOwner(packageName))) {
10571                return true;
10572            }
10573        } catch (RemoteException e) {
10574        }
10575        return false;
10576    }
10577
10578    /**
10579     *  This method is an internal method that could be get invoked either
10580     *  to delete an installed package or to clean up a failed installation.
10581     *  After deleting an installed package, a broadcast is sent to notify any
10582     *  listeners that the package has been installed. For cleaning up a failed
10583     *  installation, the broadcast is not necessary since the package's
10584     *  installation wouldn't have sent the initial broadcast either
10585     *  The key steps in deleting a package are
10586     *  deleting the package information in internal structures like mPackages,
10587     *  deleting the packages base directories through installd
10588     *  updating mSettings to reflect current status
10589     *  persisting settings for later use
10590     *  sending a broadcast if necessary
10591     */
10592    private int deletePackageX(String packageName, int userId, int flags) {
10593        final PackageRemovedInfo info = new PackageRemovedInfo();
10594        final boolean res;
10595
10596        if (isPackageDeviceAdmin(packageName, userId)) {
10597            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10598            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10599        }
10600
10601        boolean removedForAllUsers = false;
10602        boolean systemUpdate = false;
10603
10604        // for the uninstall-updates case and restricted profiles, remember the per-
10605        // userhandle installed state
10606        int[] allUsers;
10607        boolean[] perUserInstalled;
10608        synchronized (mPackages) {
10609            PackageSetting ps = mSettings.mPackages.get(packageName);
10610            allUsers = sUserManager.getUserIds();
10611            perUserInstalled = new boolean[allUsers.length];
10612            for (int i = 0; i < allUsers.length; i++) {
10613                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10614            }
10615        }
10616
10617        synchronized (mInstallLock) {
10618            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10619            res = deletePackageLI(packageName,
10620                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10621                            ? UserHandle.ALL : new UserHandle(userId),
10622                    true, allUsers, perUserInstalled,
10623                    flags | REMOVE_CHATTY, info, true);
10624            systemUpdate = info.isRemovedPackageSystemUpdate;
10625            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10626                removedForAllUsers = true;
10627            }
10628            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10629                    + " removedForAllUsers=" + removedForAllUsers);
10630        }
10631
10632        if (res) {
10633            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10634
10635            // If the removed package was a system update, the old system package
10636            // was re-enabled; we need to broadcast this information
10637            if (systemUpdate) {
10638                Bundle extras = new Bundle(1);
10639                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10640                        ? info.removedAppId : info.uid);
10641                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10642
10643                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10644                        extras, null, null, null);
10645                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10646                        extras, null, null, null);
10647                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10648                        null, packageName, null, null);
10649            }
10650        }
10651        // Force a gc here.
10652        Runtime.getRuntime().gc();
10653        // Delete the resources here after sending the broadcast to let
10654        // other processes clean up before deleting resources.
10655        if (info.args != null) {
10656            synchronized (mInstallLock) {
10657                info.args.doPostDeleteLI(true);
10658            }
10659        }
10660
10661        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10662    }
10663
10664    static class PackageRemovedInfo {
10665        String removedPackage;
10666        int uid = -1;
10667        int removedAppId = -1;
10668        int[] removedUsers = null;
10669        boolean isRemovedPackageSystemUpdate = false;
10670        // Clean up resources deleted packages.
10671        InstallArgs args = null;
10672
10673        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10674            Bundle extras = new Bundle(1);
10675            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10676            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10677            if (replacing) {
10678                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10679            }
10680            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10681            if (removedPackage != null) {
10682                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10683                        extras, null, null, removedUsers);
10684                if (fullRemove && !replacing) {
10685                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10686                            extras, null, null, removedUsers);
10687                }
10688            }
10689            if (removedAppId >= 0) {
10690                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10691                        removedUsers);
10692            }
10693        }
10694    }
10695
10696    /*
10697     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10698     * flag is not set, the data directory is removed as well.
10699     * make sure this flag is set for partially installed apps. If not its meaningless to
10700     * delete a partially installed application.
10701     */
10702    private void removePackageDataLI(PackageSetting ps,
10703            int[] allUserHandles, boolean[] perUserInstalled,
10704            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10705        String packageName = ps.name;
10706        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10707        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10708        // Retrieve object to delete permissions for shared user later on
10709        final PackageSetting deletedPs;
10710        // reader
10711        synchronized (mPackages) {
10712            deletedPs = mSettings.mPackages.get(packageName);
10713            if (outInfo != null) {
10714                outInfo.removedPackage = packageName;
10715                outInfo.removedUsers = deletedPs != null
10716                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10717                        : null;
10718            }
10719        }
10720        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10721            removeDataDirsLI(packageName);
10722            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10723        }
10724        // writer
10725        synchronized (mPackages) {
10726            if (deletedPs != null) {
10727                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10728                    if (outInfo != null) {
10729                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10730                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10731                    }
10732                    if (deletedPs != null) {
10733                        updatePermissionsLPw(deletedPs.name, null, 0);
10734                        if (deletedPs.sharedUser != null) {
10735                            // remove permissions associated with package
10736                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10737                        }
10738                    }
10739                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10740                }
10741                // make sure to preserve per-user disabled state if this removal was just
10742                // a downgrade of a system app to the factory package
10743                if (allUserHandles != null && perUserInstalled != null) {
10744                    if (DEBUG_REMOVE) {
10745                        Slog.d(TAG, "Propagating install state across downgrade");
10746                    }
10747                    for (int i = 0; i < allUserHandles.length; i++) {
10748                        if (DEBUG_REMOVE) {
10749                            Slog.d(TAG, "    user " + allUserHandles[i]
10750                                    + " => " + perUserInstalled[i]);
10751                        }
10752                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10753                    }
10754                }
10755            }
10756            // can downgrade to reader
10757            if (writeSettings) {
10758                // Save settings now
10759                mSettings.writeLPr();
10760            }
10761        }
10762        if (outInfo != null) {
10763            // A user ID was deleted here. Go through all users and remove it
10764            // from KeyStore.
10765            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10766        }
10767    }
10768
10769    static boolean locationIsPrivileged(File path) {
10770        try {
10771            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10772                    .getCanonicalPath();
10773            return path.getCanonicalPath().startsWith(privilegedAppDir);
10774        } catch (IOException e) {
10775            Slog.e(TAG, "Unable to access code path " + path);
10776        }
10777        return false;
10778    }
10779
10780    /*
10781     * Tries to delete system package.
10782     */
10783    private boolean deleteSystemPackageLI(PackageSetting newPs,
10784            int[] allUserHandles, boolean[] perUserInstalled,
10785            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10786        final boolean applyUserRestrictions
10787                = (allUserHandles != null) && (perUserInstalled != null);
10788        PackageSetting disabledPs = null;
10789        // Confirm if the system package has been updated
10790        // An updated system app can be deleted. This will also have to restore
10791        // the system pkg from system partition
10792        // reader
10793        synchronized (mPackages) {
10794            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10795        }
10796        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10797                + " disabledPs=" + disabledPs);
10798        if (disabledPs == null) {
10799            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10800            return false;
10801        } else if (DEBUG_REMOVE) {
10802            Slog.d(TAG, "Deleting system pkg from data partition");
10803        }
10804        if (DEBUG_REMOVE) {
10805            if (applyUserRestrictions) {
10806                Slog.d(TAG, "Remembering install states:");
10807                for (int i = 0; i < allUserHandles.length; i++) {
10808                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10809                }
10810            }
10811        }
10812        // Delete the updated package
10813        outInfo.isRemovedPackageSystemUpdate = true;
10814        if (disabledPs.versionCode < newPs.versionCode) {
10815            // Delete data for downgrades
10816            flags &= ~PackageManager.DELETE_KEEP_DATA;
10817        } else {
10818            // Preserve data by setting flag
10819            flags |= PackageManager.DELETE_KEEP_DATA;
10820        }
10821        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10822                allUserHandles, perUserInstalled, outInfo, writeSettings);
10823        if (!ret) {
10824            return false;
10825        }
10826        // writer
10827        synchronized (mPackages) {
10828            // Reinstate the old system package
10829            mSettings.enableSystemPackageLPw(newPs.name);
10830            // Remove any native libraries from the upgraded package.
10831            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10832        }
10833        // Install the system package
10834        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10835        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10836        if (locationIsPrivileged(disabledPs.codePath)) {
10837            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10838        }
10839
10840        final PackageParser.Package newPkg;
10841        try {
10842            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0,
10843                    null, null);
10844        } catch (PackageManagerException e) {
10845            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10846            return false;
10847        }
10848
10849        // writer
10850        synchronized (mPackages) {
10851            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10852            setBundledAppAbisAndRoots(newPkg, ps);
10853            updatePermissionsLPw(newPkg.packageName, newPkg,
10854                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10855            if (applyUserRestrictions) {
10856                if (DEBUG_REMOVE) {
10857                    Slog.d(TAG, "Propagating install state across reinstall");
10858                }
10859                for (int i = 0; i < allUserHandles.length; i++) {
10860                    if (DEBUG_REMOVE) {
10861                        Slog.d(TAG, "    user " + allUserHandles[i]
10862                                + " => " + perUserInstalled[i]);
10863                    }
10864                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10865                }
10866                // Regardless of writeSettings we need to ensure that this restriction
10867                // state propagation is persisted
10868                mSettings.writeAllUsersPackageRestrictionsLPr();
10869            }
10870            // can downgrade to reader here
10871            if (writeSettings) {
10872                mSettings.writeLPr();
10873            }
10874        }
10875        return true;
10876    }
10877
10878    private boolean deleteInstalledPackageLI(PackageSetting ps,
10879            boolean deleteCodeAndResources, int flags,
10880            int[] allUserHandles, boolean[] perUserInstalled,
10881            PackageRemovedInfo outInfo, boolean writeSettings) {
10882        if (outInfo != null) {
10883            outInfo.uid = ps.appId;
10884        }
10885
10886        // Delete package data from internal structures and also remove data if flag is set
10887        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10888
10889        // Delete application code and resources
10890        if (deleteCodeAndResources && (outInfo != null)) {
10891            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10892                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10893                    getAppDexInstructionSets(ps), isMultiArch(ps));
10894        }
10895        return true;
10896    }
10897
10898    @Override
10899    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10900            int userId) {
10901        mContext.enforceCallingOrSelfPermission(
10902                android.Manifest.permission.DELETE_PACKAGES, null);
10903        synchronized (mPackages) {
10904            PackageSetting ps = mSettings.mPackages.get(packageName);
10905            if (ps == null) {
10906                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10907                return false;
10908            }
10909            if (!ps.getInstalled(userId)) {
10910                // Can't block uninstall for an app that is not installed or enabled.
10911                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10912                return false;
10913            }
10914            ps.setBlockUninstall(blockUninstall, userId);
10915            mSettings.writePackageRestrictionsLPr(userId);
10916        }
10917        return true;
10918    }
10919
10920    @Override
10921    public boolean getBlockUninstallForUser(String packageName, int userId) {
10922        synchronized (mPackages) {
10923            PackageSetting ps = mSettings.mPackages.get(packageName);
10924            if (ps == null) {
10925                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10926                return false;
10927            }
10928            return ps.getBlockUninstall(userId);
10929        }
10930    }
10931
10932    /*
10933     * This method handles package deletion in general
10934     */
10935    private boolean deletePackageLI(String packageName, UserHandle user,
10936            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10937            int flags, PackageRemovedInfo outInfo,
10938            boolean writeSettings) {
10939        if (packageName == null) {
10940            Slog.w(TAG, "Attempt to delete null packageName.");
10941            return false;
10942        }
10943        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10944        PackageSetting ps;
10945        boolean dataOnly = false;
10946        int removeUser = -1;
10947        int appId = -1;
10948        synchronized (mPackages) {
10949            ps = mSettings.mPackages.get(packageName);
10950            if (ps == null) {
10951                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10952                return false;
10953            }
10954            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10955                    && user.getIdentifier() != UserHandle.USER_ALL) {
10956                // The caller is asking that the package only be deleted for a single
10957                // user.  To do this, we just mark its uninstalled state and delete
10958                // its data.  If this is a system app, we only allow this to happen if
10959                // they have set the special DELETE_SYSTEM_APP which requests different
10960                // semantics than normal for uninstalling system apps.
10961                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10962                ps.setUserState(user.getIdentifier(),
10963                        COMPONENT_ENABLED_STATE_DEFAULT,
10964                        false, //installed
10965                        true,  //stopped
10966                        true,  //notLaunched
10967                        false, //blocked
10968                        null, null, null,
10969                        false // blockUninstall
10970                        );
10971                if (!isSystemApp(ps)) {
10972                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10973                        // Other user still have this package installed, so all
10974                        // we need to do is clear this user's data and save that
10975                        // it is uninstalled.
10976                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10977                        removeUser = user.getIdentifier();
10978                        appId = ps.appId;
10979                        mSettings.writePackageRestrictionsLPr(removeUser);
10980                    } else {
10981                        // We need to set it back to 'installed' so the uninstall
10982                        // broadcasts will be sent correctly.
10983                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10984                        ps.setInstalled(true, user.getIdentifier());
10985                    }
10986                } else {
10987                    // This is a system app, so we assume that the
10988                    // other users still have this package installed, so all
10989                    // we need to do is clear this user's data and save that
10990                    // it is uninstalled.
10991                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10992                    removeUser = user.getIdentifier();
10993                    appId = ps.appId;
10994                    mSettings.writePackageRestrictionsLPr(removeUser);
10995                }
10996            }
10997        }
10998
10999        if (removeUser >= 0) {
11000            // From above, we determined that we are deleting this only
11001            // for a single user.  Continue the work here.
11002            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11003            if (outInfo != null) {
11004                outInfo.removedPackage = packageName;
11005                outInfo.removedAppId = appId;
11006                outInfo.removedUsers = new int[] {removeUser};
11007            }
11008            mInstaller.clearUserData(packageName, removeUser);
11009            removeKeystoreDataIfNeeded(removeUser, appId);
11010            schedulePackageCleaning(packageName, removeUser, false);
11011            return true;
11012        }
11013
11014        if (dataOnly) {
11015            // Delete application data first
11016            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11017            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11018            return true;
11019        }
11020
11021        boolean ret = false;
11022        if (isSystemApp(ps)) {
11023            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11024            // When an updated system application is deleted we delete the existing resources as well and
11025            // fall back to existing code in system partition
11026            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11027                    flags, outInfo, writeSettings);
11028        } else {
11029            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11030            // Kill application pre-emptively especially for apps on sd.
11031            killApplication(packageName, ps.appId, "uninstall pkg");
11032            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11033                    allUserHandles, perUserInstalled,
11034                    outInfo, writeSettings);
11035        }
11036
11037        return ret;
11038    }
11039
11040    private final class ClearStorageConnection implements ServiceConnection {
11041        IMediaContainerService mContainerService;
11042
11043        @Override
11044        public void onServiceConnected(ComponentName name, IBinder service) {
11045            synchronized (this) {
11046                mContainerService = IMediaContainerService.Stub.asInterface(service);
11047                notifyAll();
11048            }
11049        }
11050
11051        @Override
11052        public void onServiceDisconnected(ComponentName name) {
11053        }
11054    }
11055
11056    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11057        final boolean mounted;
11058        if (Environment.isExternalStorageEmulated()) {
11059            mounted = true;
11060        } else {
11061            final String status = Environment.getExternalStorageState();
11062
11063            mounted = status.equals(Environment.MEDIA_MOUNTED)
11064                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11065        }
11066
11067        if (!mounted) {
11068            return;
11069        }
11070
11071        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11072        int[] users;
11073        if (userId == UserHandle.USER_ALL) {
11074            users = sUserManager.getUserIds();
11075        } else {
11076            users = new int[] { userId };
11077        }
11078        final ClearStorageConnection conn = new ClearStorageConnection();
11079        if (mContext.bindServiceAsUser(
11080                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11081            try {
11082                for (int curUser : users) {
11083                    long timeout = SystemClock.uptimeMillis() + 5000;
11084                    synchronized (conn) {
11085                        long now = SystemClock.uptimeMillis();
11086                        while (conn.mContainerService == null && now < timeout) {
11087                            try {
11088                                conn.wait(timeout - now);
11089                            } catch (InterruptedException e) {
11090                            }
11091                        }
11092                    }
11093                    if (conn.mContainerService == null) {
11094                        return;
11095                    }
11096
11097                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11098                    clearDirectory(conn.mContainerService,
11099                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11100                    if (allData) {
11101                        clearDirectory(conn.mContainerService,
11102                                userEnv.buildExternalStorageAppDataDirs(packageName));
11103                        clearDirectory(conn.mContainerService,
11104                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11105                    }
11106                }
11107            } finally {
11108                mContext.unbindService(conn);
11109            }
11110        }
11111    }
11112
11113    @Override
11114    public void clearApplicationUserData(final String packageName,
11115            final IPackageDataObserver observer, final int userId) {
11116        mContext.enforceCallingOrSelfPermission(
11117                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11118        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11119        // Queue up an async operation since the package deletion may take a little while.
11120        mHandler.post(new Runnable() {
11121            public void run() {
11122                mHandler.removeCallbacks(this);
11123                final boolean succeeded;
11124                synchronized (mInstallLock) {
11125                    succeeded = clearApplicationUserDataLI(packageName, userId);
11126                }
11127                clearExternalStorageDataSync(packageName, userId, true);
11128                if (succeeded) {
11129                    // invoke DeviceStorageMonitor's update method to clear any notifications
11130                    DeviceStorageMonitorInternal
11131                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11132                    if (dsm != null) {
11133                        dsm.checkMemory();
11134                    }
11135                }
11136                if(observer != null) {
11137                    try {
11138                        observer.onRemoveCompleted(packageName, succeeded);
11139                    } catch (RemoteException e) {
11140                        Log.i(TAG, "Observer no longer exists.");
11141                    }
11142                } //end if observer
11143            } //end run
11144        });
11145    }
11146
11147    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11148        if (packageName == null) {
11149            Slog.w(TAG, "Attempt to delete null packageName.");
11150            return false;
11151        }
11152        PackageParser.Package p;
11153        boolean dataOnly = false;
11154        final int appId;
11155        synchronized (mPackages) {
11156            p = mPackages.get(packageName);
11157            if (p == null) {
11158                dataOnly = true;
11159                PackageSetting ps = mSettings.mPackages.get(packageName);
11160                if ((ps == null) || (ps.pkg == null)) {
11161                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11162                    return false;
11163                }
11164                p = ps.pkg;
11165            }
11166            if (!dataOnly) {
11167                // need to check this only for fully installed applications
11168                if (p == null) {
11169                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11170                    return false;
11171                }
11172                final ApplicationInfo applicationInfo = p.applicationInfo;
11173                if (applicationInfo == null) {
11174                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11175                    return false;
11176                }
11177            }
11178            if (p != null && p.applicationInfo != null) {
11179                appId = p.applicationInfo.uid;
11180            } else {
11181                appId = -1;
11182            }
11183        }
11184        int retCode = mInstaller.clearUserData(packageName, userId);
11185        if (retCode < 0) {
11186            Slog.w(TAG, "Couldn't remove cache files for package: "
11187                    + packageName);
11188            return false;
11189        }
11190        removeKeystoreDataIfNeeded(userId, appId);
11191        return true;
11192    }
11193
11194    /**
11195     * Remove entries from the keystore daemon. Will only remove it if the
11196     * {@code appId} is valid.
11197     */
11198    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11199        if (appId < 0) {
11200            return;
11201        }
11202
11203        final KeyStore keyStore = KeyStore.getInstance();
11204        if (keyStore != null) {
11205            if (userId == UserHandle.USER_ALL) {
11206                for (final int individual : sUserManager.getUserIds()) {
11207                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11208                }
11209            } else {
11210                keyStore.clearUid(UserHandle.getUid(userId, appId));
11211            }
11212        } else {
11213            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11214        }
11215    }
11216
11217    @Override
11218    public void deleteApplicationCacheFiles(final String packageName,
11219            final IPackageDataObserver observer) {
11220        mContext.enforceCallingOrSelfPermission(
11221                android.Manifest.permission.DELETE_CACHE_FILES, null);
11222        // Queue up an async operation since the package deletion may take a little while.
11223        final int userId = UserHandle.getCallingUserId();
11224        mHandler.post(new Runnable() {
11225            public void run() {
11226                mHandler.removeCallbacks(this);
11227                final boolean succeded;
11228                synchronized (mInstallLock) {
11229                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11230                }
11231                clearExternalStorageDataSync(packageName, userId, false);
11232                if(observer != null) {
11233                    try {
11234                        observer.onRemoveCompleted(packageName, succeded);
11235                    } catch (RemoteException e) {
11236                        Log.i(TAG, "Observer no longer exists.");
11237                    }
11238                } //end if observer
11239            } //end run
11240        });
11241    }
11242
11243    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11244        if (packageName == null) {
11245            Slog.w(TAG, "Attempt to delete null packageName.");
11246            return false;
11247        }
11248        PackageParser.Package p;
11249        synchronized (mPackages) {
11250            p = mPackages.get(packageName);
11251        }
11252        if (p == null) {
11253            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11254            return false;
11255        }
11256        final ApplicationInfo applicationInfo = p.applicationInfo;
11257        if (applicationInfo == null) {
11258            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11259            return false;
11260        }
11261        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11262        if (retCode < 0) {
11263            Slog.w(TAG, "Couldn't remove cache files for package: "
11264                       + packageName + " u" + userId);
11265            return false;
11266        }
11267        return true;
11268    }
11269
11270    @Override
11271    public void getPackageSizeInfo(final String packageName, int userHandle,
11272            final IPackageStatsObserver observer) {
11273        mContext.enforceCallingOrSelfPermission(
11274                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11275        if (packageName == null) {
11276            throw new IllegalArgumentException("Attempt to get size of null packageName");
11277        }
11278
11279        PackageStats stats = new PackageStats(packageName, userHandle);
11280
11281        /*
11282         * Queue up an async operation since the package measurement may take a
11283         * little while.
11284         */
11285        Message msg = mHandler.obtainMessage(INIT_COPY);
11286        msg.obj = new MeasureParams(stats, observer);
11287        mHandler.sendMessage(msg);
11288    }
11289
11290    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11291            PackageStats pStats) {
11292        if (packageName == null) {
11293            Slog.w(TAG, "Attempt to get size of null packageName.");
11294            return false;
11295        }
11296        PackageParser.Package p;
11297        boolean dataOnly = false;
11298        String libDirRoot = null;
11299        String asecPath = null;
11300        PackageSetting ps = null;
11301        synchronized (mPackages) {
11302            p = mPackages.get(packageName);
11303            ps = mSettings.mPackages.get(packageName);
11304            if(p == null) {
11305                dataOnly = true;
11306                if((ps == null) || (ps.pkg == null)) {
11307                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11308                    return false;
11309                }
11310                p = ps.pkg;
11311            }
11312            if (ps != null) {
11313                libDirRoot = ps.legacyNativeLibraryPathString;
11314            }
11315            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11316                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11317                if (secureContainerId != null) {
11318                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11319                }
11320            }
11321        }
11322        String publicSrcDir = null;
11323        if(!dataOnly) {
11324            final ApplicationInfo applicationInfo = p.applicationInfo;
11325            if (applicationInfo == null) {
11326                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11327                return false;
11328            }
11329            if (isForwardLocked(p)) {
11330                publicSrcDir = applicationInfo.getBaseResourcePath();
11331            }
11332        }
11333        // TODO: extend to measure size of split APKs
11334        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11335        // not just the first level.
11336        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11337        // just the primary.
11338        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11339                publicSrcDir, asecPath, getAppDexInstructionSets(ps),
11340                pStats);
11341        if (res < 0) {
11342            return false;
11343        }
11344
11345        // Fix-up for forward-locked applications in ASEC containers.
11346        if (!isExternal(p)) {
11347            pStats.codeSize += pStats.externalCodeSize;
11348            pStats.externalCodeSize = 0L;
11349        }
11350
11351        return true;
11352    }
11353
11354
11355    @Override
11356    public void addPackageToPreferred(String packageName) {
11357        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11358    }
11359
11360    @Override
11361    public void removePackageFromPreferred(String packageName) {
11362        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11363    }
11364
11365    @Override
11366    public List<PackageInfo> getPreferredPackages(int flags) {
11367        return new ArrayList<PackageInfo>();
11368    }
11369
11370    private int getUidTargetSdkVersionLockedLPr(int uid) {
11371        Object obj = mSettings.getUserIdLPr(uid);
11372        if (obj instanceof SharedUserSetting) {
11373            final SharedUserSetting sus = (SharedUserSetting) obj;
11374            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11375            final Iterator<PackageSetting> it = sus.packages.iterator();
11376            while (it.hasNext()) {
11377                final PackageSetting ps = it.next();
11378                if (ps.pkg != null) {
11379                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11380                    if (v < vers) vers = v;
11381                }
11382            }
11383            return vers;
11384        } else if (obj instanceof PackageSetting) {
11385            final PackageSetting ps = (PackageSetting) obj;
11386            if (ps.pkg != null) {
11387                return ps.pkg.applicationInfo.targetSdkVersion;
11388            }
11389        }
11390        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11391    }
11392
11393    @Override
11394    public void addPreferredActivity(IntentFilter filter, int match,
11395            ComponentName[] set, ComponentName activity, int userId) {
11396        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11397    }
11398
11399    private void addPreferredActivityInternal(IntentFilter filter, int match,
11400            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11401        // writer
11402        int callingUid = Binder.getCallingUid();
11403        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11404        if (filter.countActions() == 0) {
11405            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11406            return;
11407        }
11408        synchronized (mPackages) {
11409            if (mContext.checkCallingOrSelfPermission(
11410                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11411                    != PackageManager.PERMISSION_GRANTED) {
11412                if (getUidTargetSdkVersionLockedLPr(callingUid)
11413                        < Build.VERSION_CODES.FROYO) {
11414                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11415                            + callingUid);
11416                    return;
11417                }
11418                mContext.enforceCallingOrSelfPermission(
11419                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11420            }
11421
11422            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11423            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11424            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11425                    new PreferredActivity(filter, match, set, activity, always));
11426            mSettings.writePackageRestrictionsLPr(userId);
11427        }
11428    }
11429
11430    @Override
11431    public void replacePreferredActivity(IntentFilter filter, int match,
11432            ComponentName[] set, ComponentName activity) {
11433        if (filter.countActions() != 1) {
11434            throw new IllegalArgumentException(
11435                    "replacePreferredActivity expects filter to have only 1 action.");
11436        }
11437        if (filter.countDataAuthorities() != 0
11438                || filter.countDataPaths() != 0
11439                || filter.countDataSchemes() > 1
11440                || filter.countDataTypes() != 0) {
11441            throw new IllegalArgumentException(
11442                    "replacePreferredActivity expects filter to have no data authorities, " +
11443                    "paths, or types; and at most one scheme.");
11444        }
11445        synchronized (mPackages) {
11446            if (mContext.checkCallingOrSelfPermission(
11447                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11448                    != PackageManager.PERMISSION_GRANTED) {
11449                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11450                        < Build.VERSION_CODES.FROYO) {
11451                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11452                            + Binder.getCallingUid());
11453                    return;
11454                }
11455                mContext.enforceCallingOrSelfPermission(
11456                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11457            }
11458
11459            final int callingUserId = UserHandle.getCallingUserId();
11460            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11461            if (pir != null) {
11462                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11463                if (filter.countDataSchemes() == 1) {
11464                    Uri.Builder builder = new Uri.Builder();
11465                    builder.scheme(filter.getDataScheme(0));
11466                    intent.setData(builder.build());
11467                }
11468                List<PreferredActivity> matches = pir.queryIntent(
11469                        intent, null, true, callingUserId);
11470                if (DEBUG_PREFERRED) {
11471                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11472                }
11473                for (int i = 0; i < matches.size(); i++) {
11474                    PreferredActivity pa = matches.get(i);
11475                    if (DEBUG_PREFERRED) {
11476                        Slog.i(TAG, "Removing preferred activity "
11477                                + pa.mPref.mComponent + ":");
11478                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11479                    }
11480                    pir.removeFilter(pa);
11481                }
11482            }
11483            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11484        }
11485    }
11486
11487    @Override
11488    public void clearPackagePreferredActivities(String packageName) {
11489        final int uid = Binder.getCallingUid();
11490        // writer
11491        synchronized (mPackages) {
11492            PackageParser.Package pkg = mPackages.get(packageName);
11493            if (pkg == null || pkg.applicationInfo.uid != uid) {
11494                if (mContext.checkCallingOrSelfPermission(
11495                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11496                        != PackageManager.PERMISSION_GRANTED) {
11497                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11498                            < Build.VERSION_CODES.FROYO) {
11499                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11500                                + Binder.getCallingUid());
11501                        return;
11502                    }
11503                    mContext.enforceCallingOrSelfPermission(
11504                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11505                }
11506            }
11507
11508            int user = UserHandle.getCallingUserId();
11509            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11510                mSettings.writePackageRestrictionsLPr(user);
11511                scheduleWriteSettingsLocked();
11512            }
11513        }
11514    }
11515
11516    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11517    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11518        ArrayList<PreferredActivity> removed = null;
11519        boolean changed = false;
11520        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11521            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11522            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11523            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11524                continue;
11525            }
11526            Iterator<PreferredActivity> it = pir.filterIterator();
11527            while (it.hasNext()) {
11528                PreferredActivity pa = it.next();
11529                // Mark entry for removal only if it matches the package name
11530                // and the entry is of type "always".
11531                if (packageName == null ||
11532                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11533                                && pa.mPref.mAlways)) {
11534                    if (removed == null) {
11535                        removed = new ArrayList<PreferredActivity>();
11536                    }
11537                    removed.add(pa);
11538                }
11539            }
11540            if (removed != null) {
11541                for (int j=0; j<removed.size(); j++) {
11542                    PreferredActivity pa = removed.get(j);
11543                    pir.removeFilter(pa);
11544                }
11545                changed = true;
11546            }
11547        }
11548        return changed;
11549    }
11550
11551    @Override
11552    public void resetPreferredActivities(int userId) {
11553        mContext.enforceCallingOrSelfPermission(
11554                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11555        // writer
11556        synchronized (mPackages) {
11557            int user = UserHandle.getCallingUserId();
11558            clearPackagePreferredActivitiesLPw(null, user);
11559            mSettings.readDefaultPreferredAppsLPw(this, user);
11560            mSettings.writePackageRestrictionsLPr(user);
11561            scheduleWriteSettingsLocked();
11562        }
11563    }
11564
11565    @Override
11566    public int getPreferredActivities(List<IntentFilter> outFilters,
11567            List<ComponentName> outActivities, String packageName) {
11568
11569        int num = 0;
11570        final int userId = UserHandle.getCallingUserId();
11571        // reader
11572        synchronized (mPackages) {
11573            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11574            if (pir != null) {
11575                final Iterator<PreferredActivity> it = pir.filterIterator();
11576                while (it.hasNext()) {
11577                    final PreferredActivity pa = it.next();
11578                    if (packageName == null
11579                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11580                                    && pa.mPref.mAlways)) {
11581                        if (outFilters != null) {
11582                            outFilters.add(new IntentFilter(pa));
11583                        }
11584                        if (outActivities != null) {
11585                            outActivities.add(pa.mPref.mComponent);
11586                        }
11587                    }
11588                }
11589            }
11590        }
11591
11592        return num;
11593    }
11594
11595    @Override
11596    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11597            int userId) {
11598        int callingUid = Binder.getCallingUid();
11599        if (callingUid != Process.SYSTEM_UID) {
11600            throw new SecurityException(
11601                    "addPersistentPreferredActivity can only be run by the system");
11602        }
11603        if (filter.countActions() == 0) {
11604            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11605            return;
11606        }
11607        synchronized (mPackages) {
11608            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11609                    " :");
11610            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11611            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11612                    new PersistentPreferredActivity(filter, activity));
11613            mSettings.writePackageRestrictionsLPr(userId);
11614        }
11615    }
11616
11617    @Override
11618    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11619        int callingUid = Binder.getCallingUid();
11620        if (callingUid != Process.SYSTEM_UID) {
11621            throw new SecurityException(
11622                    "clearPackagePersistentPreferredActivities can only be run by the system");
11623        }
11624        ArrayList<PersistentPreferredActivity> removed = null;
11625        boolean changed = false;
11626        synchronized (mPackages) {
11627            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11628                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11629                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11630                        .valueAt(i);
11631                if (userId != thisUserId) {
11632                    continue;
11633                }
11634                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11635                while (it.hasNext()) {
11636                    PersistentPreferredActivity ppa = it.next();
11637                    // Mark entry for removal only if it matches the package name.
11638                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11639                        if (removed == null) {
11640                            removed = new ArrayList<PersistentPreferredActivity>();
11641                        }
11642                        removed.add(ppa);
11643                    }
11644                }
11645                if (removed != null) {
11646                    for (int j=0; j<removed.size(); j++) {
11647                        PersistentPreferredActivity ppa = removed.get(j);
11648                        ppir.removeFilter(ppa);
11649                    }
11650                    changed = true;
11651                }
11652            }
11653
11654            if (changed) {
11655                mSettings.writePackageRestrictionsLPr(userId);
11656            }
11657        }
11658    }
11659
11660    @Override
11661    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11662            int targetUserId, int flags) {
11663        mContext.enforceCallingOrSelfPermission(
11664                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11665        if (intentFilter.countActions() == 0) {
11666            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11667            return;
11668        }
11669        synchronized (mPackages) {
11670            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11671                    targetUserId, flags);
11672            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11673            mSettings.writePackageRestrictionsLPr(sourceUserId);
11674        }
11675    }
11676
11677    public void addCrossProfileIntentsForPackage(String packageName,
11678            int sourceUserId, int targetUserId) {
11679        mContext.enforceCallingOrSelfPermission(
11680                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11681        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11682        mSettings.writePackageRestrictionsLPr(sourceUserId);
11683    }
11684
11685    public void removeCrossProfileIntentsForPackage(String packageName,
11686            int sourceUserId, int targetUserId) {
11687        mContext.enforceCallingOrSelfPermission(
11688                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11689        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11690        mSettings.writePackageRestrictionsLPr(sourceUserId);
11691    }
11692
11693    @Override
11694    public void clearCrossProfileIntentFilters(int sourceUserId) {
11695        mContext.enforceCallingOrSelfPermission(
11696                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11697        synchronized (mPackages) {
11698            CrossProfileIntentResolver resolver =
11699                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11700            HashSet<CrossProfileIntentFilter> set =
11701                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11702            for (CrossProfileIntentFilter filter : set) {
11703                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11704                    resolver.removeFilter(filter);
11705                }
11706            }
11707            mSettings.writePackageRestrictionsLPr(sourceUserId);
11708        }
11709    }
11710
11711    @Override
11712    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11713        Intent intent = new Intent(Intent.ACTION_MAIN);
11714        intent.addCategory(Intent.CATEGORY_HOME);
11715
11716        final int callingUserId = UserHandle.getCallingUserId();
11717        List<ResolveInfo> list = queryIntentActivities(intent, null,
11718                PackageManager.GET_META_DATA, callingUserId);
11719        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11720                true, false, false, callingUserId);
11721
11722        allHomeCandidates.clear();
11723        if (list != null) {
11724            for (ResolveInfo ri : list) {
11725                allHomeCandidates.add(ri);
11726            }
11727        }
11728        return (preferred == null || preferred.activityInfo == null)
11729                ? null
11730                : new ComponentName(preferred.activityInfo.packageName,
11731                        preferred.activityInfo.name);
11732    }
11733
11734    @Override
11735    public void setApplicationEnabledSetting(String appPackageName,
11736            int newState, int flags, int userId, String callingPackage) {
11737        if (!sUserManager.exists(userId)) return;
11738        if (callingPackage == null) {
11739            callingPackage = Integer.toString(Binder.getCallingUid());
11740        }
11741        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11742    }
11743
11744    @Override
11745    public void setComponentEnabledSetting(ComponentName componentName,
11746            int newState, int flags, int userId) {
11747        if (!sUserManager.exists(userId)) return;
11748        setEnabledSetting(componentName.getPackageName(),
11749                componentName.getClassName(), newState, flags, userId, null);
11750    }
11751
11752    private void setEnabledSetting(final String packageName, String className, int newState,
11753            final int flags, int userId, String callingPackage) {
11754        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11755              || newState == COMPONENT_ENABLED_STATE_ENABLED
11756              || newState == COMPONENT_ENABLED_STATE_DISABLED
11757              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11758              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11759            throw new IllegalArgumentException("Invalid new component state: "
11760                    + newState);
11761        }
11762        PackageSetting pkgSetting;
11763        final int uid = Binder.getCallingUid();
11764        final int permission = mContext.checkCallingOrSelfPermission(
11765                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11766        enforceCrossUserPermission(uid, userId, false, "set enabled");
11767        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11768        boolean sendNow = false;
11769        boolean isApp = (className == null);
11770        String componentName = isApp ? packageName : className;
11771        int packageUid = -1;
11772        ArrayList<String> components;
11773
11774        // writer
11775        synchronized (mPackages) {
11776            pkgSetting = mSettings.mPackages.get(packageName);
11777            if (pkgSetting == null) {
11778                if (className == null) {
11779                    throw new IllegalArgumentException(
11780                            "Unknown package: " + packageName);
11781                }
11782                throw new IllegalArgumentException(
11783                        "Unknown component: " + packageName
11784                        + "/" + className);
11785            }
11786            // Allow root and verify that userId is not being specified by a different user
11787            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11788                throw new SecurityException(
11789                        "Permission Denial: attempt to change component state from pid="
11790                        + Binder.getCallingPid()
11791                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11792            }
11793            if (className == null) {
11794                // We're dealing with an application/package level state change
11795                if (pkgSetting.getEnabled(userId) == newState) {
11796                    // Nothing to do
11797                    return;
11798                }
11799                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11800                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11801                    // Don't care about who enables an app.
11802                    callingPackage = null;
11803                }
11804                pkgSetting.setEnabled(newState, userId, callingPackage);
11805                // pkgSetting.pkg.mSetEnabled = newState;
11806            } else {
11807                // We're dealing with a component level state change
11808                // First, verify that this is a valid class name.
11809                PackageParser.Package pkg = pkgSetting.pkg;
11810                if (pkg == null || !pkg.hasComponentClassName(className)) {
11811                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11812                        throw new IllegalArgumentException("Component class " + className
11813                                + " does not exist in " + packageName);
11814                    } else {
11815                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11816                                + className + " does not exist in " + packageName);
11817                    }
11818                }
11819                switch (newState) {
11820                case COMPONENT_ENABLED_STATE_ENABLED:
11821                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11822                        return;
11823                    }
11824                    break;
11825                case COMPONENT_ENABLED_STATE_DISABLED:
11826                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11827                        return;
11828                    }
11829                    break;
11830                case COMPONENT_ENABLED_STATE_DEFAULT:
11831                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11832                        return;
11833                    }
11834                    break;
11835                default:
11836                    Slog.e(TAG, "Invalid new component state: " + newState);
11837                    return;
11838                }
11839            }
11840            mSettings.writePackageRestrictionsLPr(userId);
11841            components = mPendingBroadcasts.get(userId, packageName);
11842            final boolean newPackage = components == null;
11843            if (newPackage) {
11844                components = new ArrayList<String>();
11845            }
11846            if (!components.contains(componentName)) {
11847                components.add(componentName);
11848            }
11849            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11850                sendNow = true;
11851                // Purge entry from pending broadcast list if another one exists already
11852                // since we are sending one right away.
11853                mPendingBroadcasts.remove(userId, packageName);
11854            } else {
11855                if (newPackage) {
11856                    mPendingBroadcasts.put(userId, packageName, components);
11857                }
11858                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11859                    // Schedule a message
11860                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11861                }
11862            }
11863        }
11864
11865        long callingId = Binder.clearCallingIdentity();
11866        try {
11867            if (sendNow) {
11868                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11869                sendPackageChangedBroadcast(packageName,
11870                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11871            }
11872        } finally {
11873            Binder.restoreCallingIdentity(callingId);
11874        }
11875    }
11876
11877    private void sendPackageChangedBroadcast(String packageName,
11878            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11879        if (DEBUG_INSTALL)
11880            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11881                    + componentNames);
11882        Bundle extras = new Bundle(4);
11883        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11884        String nameList[] = new String[componentNames.size()];
11885        componentNames.toArray(nameList);
11886        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11887        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11888        extras.putInt(Intent.EXTRA_UID, packageUid);
11889        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11890                new int[] {UserHandle.getUserId(packageUid)});
11891    }
11892
11893    @Override
11894    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11895        if (!sUserManager.exists(userId)) return;
11896        final int uid = Binder.getCallingUid();
11897        final int permission = mContext.checkCallingOrSelfPermission(
11898                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11899        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11900        enforceCrossUserPermission(uid, userId, true, "stop package");
11901        // writer
11902        synchronized (mPackages) {
11903            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11904                    uid, userId)) {
11905                scheduleWritePackageRestrictionsLocked(userId);
11906            }
11907        }
11908    }
11909
11910    @Override
11911    public String getInstallerPackageName(String packageName) {
11912        // reader
11913        synchronized (mPackages) {
11914            return mSettings.getInstallerPackageNameLPr(packageName);
11915        }
11916    }
11917
11918    @Override
11919    public int getApplicationEnabledSetting(String packageName, int userId) {
11920        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11921        int uid = Binder.getCallingUid();
11922        enforceCrossUserPermission(uid, userId, false, "get enabled");
11923        // reader
11924        synchronized (mPackages) {
11925            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11926        }
11927    }
11928
11929    @Override
11930    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11931        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11932        int uid = Binder.getCallingUid();
11933        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11934        // reader
11935        synchronized (mPackages) {
11936            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11937        }
11938    }
11939
11940    @Override
11941    public void enterSafeMode() {
11942        enforceSystemOrRoot("Only the system can request entering safe mode");
11943
11944        if (!mSystemReady) {
11945            mSafeMode = true;
11946        }
11947    }
11948
11949    @Override
11950    public void systemReady() {
11951        mSystemReady = true;
11952
11953        // Read the compatibilty setting when the system is ready.
11954        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11955                mContext.getContentResolver(),
11956                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11957        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11958        if (DEBUG_SETTINGS) {
11959            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11960        }
11961
11962        synchronized (mPackages) {
11963            // Verify that all of the preferred activity components actually
11964            // exist.  It is possible for applications to be updated and at
11965            // that point remove a previously declared activity component that
11966            // had been set as a preferred activity.  We try to clean this up
11967            // the next time we encounter that preferred activity, but it is
11968            // possible for the user flow to never be able to return to that
11969            // situation so here we do a sanity check to make sure we haven't
11970            // left any junk around.
11971            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11972            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11973                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11974                removed.clear();
11975                for (PreferredActivity pa : pir.filterSet()) {
11976                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11977                        removed.add(pa);
11978                    }
11979                }
11980                if (removed.size() > 0) {
11981                    for (int r=0; r<removed.size(); r++) {
11982                        PreferredActivity pa = removed.get(r);
11983                        Slog.w(TAG, "Removing dangling preferred activity: "
11984                                + pa.mPref.mComponent);
11985                        pir.removeFilter(pa);
11986                    }
11987                    mSettings.writePackageRestrictionsLPr(
11988                            mSettings.mPreferredActivities.keyAt(i));
11989                }
11990            }
11991        }
11992        sUserManager.systemReady();
11993    }
11994
11995    @Override
11996    public boolean isSafeMode() {
11997        return mSafeMode;
11998    }
11999
12000    @Override
12001    public boolean hasSystemUidErrors() {
12002        return mHasSystemUidErrors;
12003    }
12004
12005    static String arrayToString(int[] array) {
12006        StringBuffer buf = new StringBuffer(128);
12007        buf.append('[');
12008        if (array != null) {
12009            for (int i=0; i<array.length; i++) {
12010                if (i > 0) buf.append(", ");
12011                buf.append(array[i]);
12012            }
12013        }
12014        buf.append(']');
12015        return buf.toString();
12016    }
12017
12018    static class DumpState {
12019        public static final int DUMP_LIBS = 1 << 0;
12020        public static final int DUMP_FEATURES = 1 << 1;
12021        public static final int DUMP_RESOLVERS = 1 << 2;
12022        public static final int DUMP_PERMISSIONS = 1 << 3;
12023        public static final int DUMP_PACKAGES = 1 << 4;
12024        public static final int DUMP_SHARED_USERS = 1 << 5;
12025        public static final int DUMP_MESSAGES = 1 << 6;
12026        public static final int DUMP_PROVIDERS = 1 << 7;
12027        public static final int DUMP_VERIFIERS = 1 << 8;
12028        public static final int DUMP_PREFERRED = 1 << 9;
12029        public static final int DUMP_PREFERRED_XML = 1 << 10;
12030        public static final int DUMP_KEYSETS = 1 << 11;
12031        public static final int DUMP_VERSION = 1 << 12;
12032        public static final int DUMP_INSTALLS = 1 << 13;
12033
12034        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12035
12036        private int mTypes;
12037
12038        private int mOptions;
12039
12040        private boolean mTitlePrinted;
12041
12042        private SharedUserSetting mSharedUser;
12043
12044        public boolean isDumping(int type) {
12045            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12046                return true;
12047            }
12048
12049            return (mTypes & type) != 0;
12050        }
12051
12052        public void setDump(int type) {
12053            mTypes |= type;
12054        }
12055
12056        public boolean isOptionEnabled(int option) {
12057            return (mOptions & option) != 0;
12058        }
12059
12060        public void setOptionEnabled(int option) {
12061            mOptions |= option;
12062        }
12063
12064        public boolean onTitlePrinted() {
12065            final boolean printed = mTitlePrinted;
12066            mTitlePrinted = true;
12067            return printed;
12068        }
12069
12070        public boolean getTitlePrinted() {
12071            return mTitlePrinted;
12072        }
12073
12074        public void setTitlePrinted(boolean enabled) {
12075            mTitlePrinted = enabled;
12076        }
12077
12078        public SharedUserSetting getSharedUser() {
12079            return mSharedUser;
12080        }
12081
12082        public void setSharedUser(SharedUserSetting user) {
12083            mSharedUser = user;
12084        }
12085    }
12086
12087    @Override
12088    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12089        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12090                != PackageManager.PERMISSION_GRANTED) {
12091            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12092                    + Binder.getCallingPid()
12093                    + ", uid=" + Binder.getCallingUid()
12094                    + " without permission "
12095                    + android.Manifest.permission.DUMP);
12096            return;
12097        }
12098
12099        DumpState dumpState = new DumpState();
12100        boolean fullPreferred = false;
12101        boolean checkin = false;
12102
12103        String packageName = null;
12104
12105        int opti = 0;
12106        while (opti < args.length) {
12107            String opt = args[opti];
12108            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12109                break;
12110            }
12111            opti++;
12112            if ("-a".equals(opt)) {
12113                // Right now we only know how to print all.
12114            } else if ("-h".equals(opt)) {
12115                pw.println("Package manager dump options:");
12116                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12117                pw.println("    --checkin: dump for a checkin");
12118                pw.println("    -f: print details of intent filters");
12119                pw.println("    -h: print this help");
12120                pw.println("  cmd may be one of:");
12121                pw.println("    l[ibraries]: list known shared libraries");
12122                pw.println("    f[ibraries]: list device features");
12123                pw.println("    k[eysets]: print known keysets");
12124                pw.println("    r[esolvers]: dump intent resolvers");
12125                pw.println("    perm[issions]: dump permissions");
12126                pw.println("    pref[erred]: print preferred package settings");
12127                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12128                pw.println("    prov[iders]: dump content providers");
12129                pw.println("    p[ackages]: dump installed packages");
12130                pw.println("    s[hared-users]: dump shared user IDs");
12131                pw.println("    m[essages]: print collected runtime messages");
12132                pw.println("    v[erifiers]: print package verifier info");
12133                pw.println("    version: print database version info");
12134                pw.println("    write: write current settings now");
12135                pw.println("    <package.name>: info about given package");
12136                pw.println("    installs: details about install sessions");
12137                return;
12138            } else if ("--checkin".equals(opt)) {
12139                checkin = true;
12140            } else if ("-f".equals(opt)) {
12141                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12142            } else {
12143                pw.println("Unknown argument: " + opt + "; use -h for help");
12144            }
12145        }
12146
12147        // Is the caller requesting to dump a particular piece of data?
12148        if (opti < args.length) {
12149            String cmd = args[opti];
12150            opti++;
12151            // Is this a package name?
12152            if ("android".equals(cmd) || cmd.contains(".")) {
12153                packageName = cmd;
12154                // When dumping a single package, we always dump all of its
12155                // filter information since the amount of data will be reasonable.
12156                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12157            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12158                dumpState.setDump(DumpState.DUMP_LIBS);
12159            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12160                dumpState.setDump(DumpState.DUMP_FEATURES);
12161            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12162                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12163            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12164                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12165            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12166                dumpState.setDump(DumpState.DUMP_PREFERRED);
12167            } else if ("preferred-xml".equals(cmd)) {
12168                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12169                if (opti < args.length && "--full".equals(args[opti])) {
12170                    fullPreferred = true;
12171                    opti++;
12172                }
12173            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12174                dumpState.setDump(DumpState.DUMP_PACKAGES);
12175            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12176                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12177            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12178                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12179            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12180                dumpState.setDump(DumpState.DUMP_MESSAGES);
12181            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12182                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12183            } else if ("version".equals(cmd)) {
12184                dumpState.setDump(DumpState.DUMP_VERSION);
12185            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12186                dumpState.setDump(DumpState.DUMP_KEYSETS);
12187            } else if ("write".equals(cmd)) {
12188                synchronized (mPackages) {
12189                    mSettings.writeLPr();
12190                    pw.println("Settings written.");
12191                    return;
12192                }
12193            } else if ("installs".equals(cmd)) {
12194                dumpState.setDump(DumpState.DUMP_INSTALLS);
12195            }
12196        }
12197
12198        if (checkin) {
12199            pw.println("vers,1");
12200        }
12201
12202        // reader
12203        synchronized (mPackages) {
12204            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12205                if (!checkin) {
12206                    if (dumpState.onTitlePrinted())
12207                        pw.println();
12208                    pw.println("Database versions:");
12209                    pw.print("  SDK Version:");
12210                    pw.print(" internal=");
12211                    pw.print(mSettings.mInternalSdkPlatform);
12212                    pw.print(" external=");
12213                    pw.println(mSettings.mExternalSdkPlatform);
12214                    pw.print("  DB Version:");
12215                    pw.print(" internal=");
12216                    pw.print(mSettings.mInternalDatabaseVersion);
12217                    pw.print(" external=");
12218                    pw.println(mSettings.mExternalDatabaseVersion);
12219                }
12220            }
12221
12222            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12223                if (!checkin) {
12224                    if (dumpState.onTitlePrinted())
12225                        pw.println();
12226                    pw.println("Verifiers:");
12227                    pw.print("  Required: ");
12228                    pw.print(mRequiredVerifierPackage);
12229                    pw.print(" (uid=");
12230                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12231                    pw.println(")");
12232                } else if (mRequiredVerifierPackage != null) {
12233                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12234                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12235                }
12236            }
12237
12238            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12239                boolean printedHeader = false;
12240                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12241                while (it.hasNext()) {
12242                    String name = it.next();
12243                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12244                    if (!checkin) {
12245                        if (!printedHeader) {
12246                            if (dumpState.onTitlePrinted())
12247                                pw.println();
12248                            pw.println("Libraries:");
12249                            printedHeader = true;
12250                        }
12251                        pw.print("  ");
12252                    } else {
12253                        pw.print("lib,");
12254                    }
12255                    pw.print(name);
12256                    if (!checkin) {
12257                        pw.print(" -> ");
12258                    }
12259                    if (ent.path != null) {
12260                        if (!checkin) {
12261                            pw.print("(jar) ");
12262                            pw.print(ent.path);
12263                        } else {
12264                            pw.print(",jar,");
12265                            pw.print(ent.path);
12266                        }
12267                    } else {
12268                        if (!checkin) {
12269                            pw.print("(apk) ");
12270                            pw.print(ent.apk);
12271                        } else {
12272                            pw.print(",apk,");
12273                            pw.print(ent.apk);
12274                        }
12275                    }
12276                    pw.println();
12277                }
12278            }
12279
12280            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12281                if (dumpState.onTitlePrinted())
12282                    pw.println();
12283                if (!checkin) {
12284                    pw.println("Features:");
12285                }
12286                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12287                while (it.hasNext()) {
12288                    String name = it.next();
12289                    if (!checkin) {
12290                        pw.print("  ");
12291                    } else {
12292                        pw.print("feat,");
12293                    }
12294                    pw.println(name);
12295                }
12296            }
12297
12298            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12299                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12300                        : "Activity Resolver Table:", "  ", packageName,
12301                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12302                    dumpState.setTitlePrinted(true);
12303                }
12304                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12305                        : "Receiver Resolver Table:", "  ", packageName,
12306                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12307                    dumpState.setTitlePrinted(true);
12308                }
12309                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12310                        : "Service Resolver Table:", "  ", packageName,
12311                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12312                    dumpState.setTitlePrinted(true);
12313                }
12314                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12315                        : "Provider Resolver Table:", "  ", packageName,
12316                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12317                    dumpState.setTitlePrinted(true);
12318                }
12319            }
12320
12321            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12322                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12323                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12324                    int user = mSettings.mPreferredActivities.keyAt(i);
12325                    if (pir.dump(pw,
12326                            dumpState.getTitlePrinted()
12327                                ? "\nPreferred Activities User " + user + ":"
12328                                : "Preferred Activities User " + user + ":", "  ",
12329                            packageName, true)) {
12330                        dumpState.setTitlePrinted(true);
12331                    }
12332                }
12333            }
12334
12335            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12336                pw.flush();
12337                FileOutputStream fout = new FileOutputStream(fd);
12338                BufferedOutputStream str = new BufferedOutputStream(fout);
12339                XmlSerializer serializer = new FastXmlSerializer();
12340                try {
12341                    serializer.setOutput(str, "utf-8");
12342                    serializer.startDocument(null, true);
12343                    serializer.setFeature(
12344                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12345                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12346                    serializer.endDocument();
12347                    serializer.flush();
12348                } catch (IllegalArgumentException e) {
12349                    pw.println("Failed writing: " + e);
12350                } catch (IllegalStateException e) {
12351                    pw.println("Failed writing: " + e);
12352                } catch (IOException e) {
12353                    pw.println("Failed writing: " + e);
12354                }
12355            }
12356
12357            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12358                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12359            }
12360
12361            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12362                boolean printedSomething = false;
12363                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12364                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12365                        continue;
12366                    }
12367                    if (!printedSomething) {
12368                        if (dumpState.onTitlePrinted())
12369                            pw.println();
12370                        pw.println("Registered ContentProviders:");
12371                        printedSomething = true;
12372                    }
12373                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12374                    pw.print("    "); pw.println(p.toString());
12375                }
12376                printedSomething = false;
12377                for (Map.Entry<String, PackageParser.Provider> entry :
12378                        mProvidersByAuthority.entrySet()) {
12379                    PackageParser.Provider p = entry.getValue();
12380                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12381                        continue;
12382                    }
12383                    if (!printedSomething) {
12384                        if (dumpState.onTitlePrinted())
12385                            pw.println();
12386                        pw.println("ContentProvider Authorities:");
12387                        printedSomething = true;
12388                    }
12389                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12390                    pw.print("    "); pw.println(p.toString());
12391                    if (p.info != null && p.info.applicationInfo != null) {
12392                        final String appInfo = p.info.applicationInfo.toString();
12393                        pw.print("      applicationInfo="); pw.println(appInfo);
12394                    }
12395                }
12396            }
12397
12398            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12399                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12400            }
12401
12402            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12403                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12404            }
12405
12406            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12407                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12408            }
12409
12410            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12411                if (dumpState.onTitlePrinted()) pw.println();
12412                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12413            }
12414
12415            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12416                if (dumpState.onTitlePrinted()) pw.println();
12417                mSettings.dumpReadMessagesLPr(pw, dumpState);
12418
12419                pw.println();
12420                pw.println("Package warning messages:");
12421                final File fname = getSettingsProblemFile();
12422                FileInputStream in = null;
12423                try {
12424                    in = new FileInputStream(fname);
12425                    final int avail = in.available();
12426                    final byte[] data = new byte[avail];
12427                    in.read(data);
12428                    pw.print(new String(data));
12429                } catch (FileNotFoundException e) {
12430                } catch (IOException e) {
12431                } finally {
12432                    if (in != null) {
12433                        try {
12434                            in.close();
12435                        } catch (IOException e) {
12436                        }
12437                    }
12438                }
12439            }
12440        }
12441    }
12442
12443    // ------- apps on sdcard specific code -------
12444    static final boolean DEBUG_SD_INSTALL = false;
12445
12446    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12447
12448    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12449
12450    private boolean mMediaMounted = false;
12451
12452    private String getEncryptKey() {
12453        try {
12454            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12455                    SD_ENCRYPTION_KEYSTORE_NAME);
12456            if (sdEncKey == null) {
12457                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12458                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12459                if (sdEncKey == null) {
12460                    Slog.e(TAG, "Failed to create encryption keys");
12461                    return null;
12462                }
12463            }
12464            return sdEncKey;
12465        } catch (NoSuchAlgorithmException nsae) {
12466            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12467            return null;
12468        } catch (IOException ioe) {
12469            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12470            return null;
12471        }
12472
12473    }
12474
12475    /* package */static String getTempContainerId() {
12476        int tmpIdx = 1;
12477        String list[] = PackageHelper.getSecureContainerList();
12478        if (list != null) {
12479            for (final String name : list) {
12480                // Ignore null and non-temporary container entries
12481                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12482                    continue;
12483                }
12484
12485                String subStr = name.substring(mTempContainerPrefix.length());
12486                try {
12487                    int cid = Integer.parseInt(subStr);
12488                    if (cid >= tmpIdx) {
12489                        tmpIdx = cid + 1;
12490                    }
12491                } catch (NumberFormatException e) {
12492                }
12493            }
12494        }
12495        return mTempContainerPrefix + tmpIdx;
12496    }
12497
12498    /*
12499     * Update media status on PackageManager.
12500     */
12501    @Override
12502    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12503        int callingUid = Binder.getCallingUid();
12504        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12505            throw new SecurityException("Media status can only be updated by the system");
12506        }
12507        // reader; this apparently protects mMediaMounted, but should probably
12508        // be a different lock in that case.
12509        synchronized (mPackages) {
12510            Log.i(TAG, "Updating external media status from "
12511                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12512                    + (mediaStatus ? "mounted" : "unmounted"));
12513            if (DEBUG_SD_INSTALL)
12514                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12515                        + ", mMediaMounted=" + mMediaMounted);
12516            if (mediaStatus == mMediaMounted) {
12517                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12518                        : 0, -1);
12519                mHandler.sendMessage(msg);
12520                return;
12521            }
12522            mMediaMounted = mediaStatus;
12523        }
12524        // Queue up an async operation since the package installation may take a
12525        // little while.
12526        mHandler.post(new Runnable() {
12527            public void run() {
12528                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12529            }
12530        });
12531    }
12532
12533    /**
12534     * Called by MountService when the initial ASECs to scan are available.
12535     * Should block until all the ASEC containers are finished being scanned.
12536     */
12537    public void scanAvailableAsecs() {
12538        updateExternalMediaStatusInner(true, false, false);
12539        if (mShouldRestoreconData) {
12540            SELinuxMMAC.setRestoreconDone();
12541            mShouldRestoreconData = false;
12542        }
12543    }
12544
12545    /*
12546     * Collect information of applications on external media, map them against
12547     * existing containers and update information based on current mount status.
12548     * Please note that we always have to report status if reportStatus has been
12549     * set to true especially when unloading packages.
12550     */
12551    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12552            boolean externalStorage) {
12553        // Collection of uids
12554        int uidArr[] = null;
12555        // Collection of stale containers
12556        HashSet<String> removeCids = new HashSet<String>();
12557        // Collection of packages on external media with valid containers.
12558        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12559        // Get list of secure containers.
12560        final String list[] = PackageHelper.getSecureContainerList();
12561        if (list == null || list.length == 0) {
12562            Log.i(TAG, "No secure containers on sdcard");
12563        } else {
12564            // Process list of secure containers and categorize them
12565            // as active or stale based on their package internal state.
12566            int uidList[] = new int[list.length];
12567            int num = 0;
12568            // reader
12569            synchronized (mPackages) {
12570                for (String cid : list) {
12571                    if (DEBUG_SD_INSTALL)
12572                        Log.i(TAG, "Processing container " + cid);
12573                    String pkgName = getAsecPackageName(cid);
12574                    if (pkgName == null) {
12575                        if (DEBUG_SD_INSTALL)
12576                            Log.i(TAG, "Container : " + cid + " stale");
12577                        removeCids.add(cid);
12578                        continue;
12579                    }
12580                    if (DEBUG_SD_INSTALL)
12581                        Log.i(TAG, "Looking for pkg : " + pkgName);
12582
12583                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12584                    if (ps == null) {
12585                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12586                        removeCids.add(cid);
12587                        continue;
12588                    }
12589
12590                    /*
12591                     * Skip packages that are not external if we're unmounting
12592                     * external storage.
12593                     */
12594                    if (externalStorage && !isMounted && !isExternal(ps)) {
12595                        continue;
12596                    }
12597
12598                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12599                            getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps));
12600                    // The package status is changed only if the code path
12601                    // matches between settings and the container id.
12602                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12603                        if (DEBUG_SD_INSTALL) {
12604                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12605                                    + " at code path: " + ps.codePathString);
12606                        }
12607
12608                        // We do have a valid package installed on sdcard
12609                        processCids.put(args, ps.codePathString);
12610                        final int uid = ps.appId;
12611                        if (uid != -1) {
12612                            uidList[num++] = uid;
12613                        }
12614                    } else {
12615                        Log.i(TAG, "Deleting stale container for " + cid);
12616                        removeCids.add(cid);
12617                    }
12618                }
12619            }
12620
12621            if (num > 0) {
12622                // Sort uid list
12623                Arrays.sort(uidList, 0, num);
12624                // Throw away duplicates
12625                uidArr = new int[num];
12626                uidArr[0] = uidList[0];
12627                int di = 0;
12628                for (int i = 1; i < num; i++) {
12629                    if (uidList[i - 1] != uidList[i]) {
12630                        uidArr[di++] = uidList[i];
12631                    }
12632                }
12633            }
12634        }
12635        // Process packages with valid entries.
12636        if (isMounted) {
12637            if (DEBUG_SD_INSTALL)
12638                Log.i(TAG, "Loading packages");
12639            loadMediaPackages(processCids, uidArr, removeCids);
12640            startCleaningPackages();
12641        } else {
12642            if (DEBUG_SD_INSTALL)
12643                Log.i(TAG, "Unloading packages");
12644            unloadMediaPackages(processCids, uidArr, reportStatus);
12645        }
12646    }
12647
12648   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12649           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12650        int size = pkgList.size();
12651        if (size > 0) {
12652            // Send broadcasts here
12653            Bundle extras = new Bundle();
12654            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12655                    .toArray(new String[size]));
12656            if (uidArr != null) {
12657                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12658            }
12659            if (replacing) {
12660                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12661            }
12662            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12663                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12664            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12665        }
12666    }
12667
12668   /*
12669     * Look at potentially valid container ids from processCids If package
12670     * information doesn't match the one on record or package scanning fails,
12671     * the cid is added to list of removeCids. We currently don't delete stale
12672     * containers.
12673     */
12674   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12675            HashSet<String> removeCids) {
12676        ArrayList<String> pkgList = new ArrayList<String>();
12677        Set<AsecInstallArgs> keys = processCids.keySet();
12678        boolean doGc = false;
12679        for (AsecInstallArgs args : keys) {
12680            String codePath = processCids.get(args);
12681            if (DEBUG_SD_INSTALL)
12682                Log.i(TAG, "Loading container : " + args.cid);
12683            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12684            try {
12685                // Make sure there are no container errors first.
12686                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12687                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12688                            + " when installing from sdcard");
12689                    continue;
12690                }
12691                // Check code path here.
12692                if (codePath == null || !codePath.equals(args.getCodePath())) {
12693                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12694                            + " does not match one in settings " + codePath);
12695                    continue;
12696                }
12697                // Parse package
12698                int parseFlags = mDefParseFlags;
12699                if (args.isExternal()) {
12700                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12701                }
12702                if (args.isFwdLocked()) {
12703                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12704                }
12705
12706                doGc = true;
12707                synchronized (mInstallLock) {
12708                    PackageParser.Package pkg = null;
12709                    try {
12710                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null);
12711                    } catch (PackageManagerException e) {
12712                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12713                    }
12714                    // Scan the package
12715                    if (pkg != null) {
12716                        /*
12717                         * TODO why is the lock being held? doPostInstall is
12718                         * called in other places without the lock. This needs
12719                         * to be straightened out.
12720                         */
12721                        // writer
12722                        synchronized (mPackages) {
12723                            retCode = PackageManager.INSTALL_SUCCEEDED;
12724                            pkgList.add(pkg.packageName);
12725                            // Post process args
12726                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12727                                    pkg.applicationInfo.uid);
12728                        }
12729                    } else {
12730                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12731                    }
12732                }
12733
12734            } finally {
12735                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12736                    // Don't destroy container here. Wait till gc clears things
12737                    // up.
12738                    removeCids.add(args.cid);
12739                }
12740            }
12741        }
12742        // writer
12743        synchronized (mPackages) {
12744            // If the platform SDK has changed since the last time we booted,
12745            // we need to re-grant app permission to catch any new ones that
12746            // appear. This is really a hack, and means that apps can in some
12747            // cases get permissions that the user didn't initially explicitly
12748            // allow... it would be nice to have some better way to handle
12749            // this situation.
12750            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12751            if (regrantPermissions)
12752                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12753                        + mSdkVersion + "; regranting permissions for external storage");
12754            mSettings.mExternalSdkPlatform = mSdkVersion;
12755
12756            // Make sure group IDs have been assigned, and any permission
12757            // changes in other apps are accounted for
12758            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12759                    | (regrantPermissions
12760                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12761                            : 0));
12762
12763            mSettings.updateExternalDatabaseVersion();
12764
12765            // can downgrade to reader
12766            // Persist settings
12767            mSettings.writeLPr();
12768        }
12769        // Send a broadcast to let everyone know we are done processing
12770        if (pkgList.size() > 0) {
12771            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12772        }
12773        // Force gc to avoid any stale parser references that we might have.
12774        if (doGc) {
12775            Runtime.getRuntime().gc();
12776        }
12777        // List stale containers and destroy stale temporary containers.
12778        if (removeCids != null) {
12779            for (String cid : removeCids) {
12780                if (cid.startsWith(mTempContainerPrefix)) {
12781                    Log.i(TAG, "Destroying stale temporary container " + cid);
12782                    PackageHelper.destroySdDir(cid);
12783                } else {
12784                    Log.w(TAG, "Container " + cid + " is stale");
12785               }
12786           }
12787        }
12788    }
12789
12790   /*
12791     * Utility method to unload a list of specified containers
12792     */
12793    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12794        // Just unmount all valid containers.
12795        for (AsecInstallArgs arg : cidArgs) {
12796            synchronized (mInstallLock) {
12797                arg.doPostDeleteLI(false);
12798           }
12799       }
12800   }
12801
12802    /*
12803     * Unload packages mounted on external media. This involves deleting package
12804     * data from internal structures, sending broadcasts about diabled packages,
12805     * gc'ing to free up references, unmounting all secure containers
12806     * corresponding to packages on external media, and posting a
12807     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12808     * that we always have to post this message if status has been requested no
12809     * matter what.
12810     */
12811    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12812            final boolean reportStatus) {
12813        if (DEBUG_SD_INSTALL)
12814            Log.i(TAG, "unloading media packages");
12815        ArrayList<String> pkgList = new ArrayList<String>();
12816        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12817        final Set<AsecInstallArgs> keys = processCids.keySet();
12818        for (AsecInstallArgs args : keys) {
12819            String pkgName = args.getPackageName();
12820            if (DEBUG_SD_INSTALL)
12821                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12822            // Delete package internally
12823            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12824            synchronized (mInstallLock) {
12825                boolean res = deletePackageLI(pkgName, null, false, null, null,
12826                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12827                if (res) {
12828                    pkgList.add(pkgName);
12829                } else {
12830                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12831                    failedList.add(args);
12832                }
12833            }
12834        }
12835
12836        // reader
12837        synchronized (mPackages) {
12838            // We didn't update the settings after removing each package;
12839            // write them now for all packages.
12840            mSettings.writeLPr();
12841        }
12842
12843        // We have to absolutely send UPDATED_MEDIA_STATUS only
12844        // after confirming that all the receivers processed the ordered
12845        // broadcast when packages get disabled, force a gc to clean things up.
12846        // and unload all the containers.
12847        if (pkgList.size() > 0) {
12848            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12849                    new IIntentReceiver.Stub() {
12850                public void performReceive(Intent intent, int resultCode, String data,
12851                        Bundle extras, boolean ordered, boolean sticky,
12852                        int sendingUser) throws RemoteException {
12853                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12854                            reportStatus ? 1 : 0, 1, keys);
12855                    mHandler.sendMessage(msg);
12856                }
12857            });
12858        } else {
12859            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12860                    keys);
12861            mHandler.sendMessage(msg);
12862        }
12863    }
12864
12865    /** Binder call */
12866    @Override
12867    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12868            final int flags) {
12869        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12870        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12871        int returnCode = PackageManager.MOVE_SUCCEEDED;
12872        int currFlags = 0;
12873        int newFlags = 0;
12874        // reader
12875        synchronized (mPackages) {
12876            PackageParser.Package pkg = mPackages.get(packageName);
12877            if (pkg == null) {
12878                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12879            } else {
12880                // Disable moving fwd locked apps and system packages
12881                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12882                    Slog.w(TAG, "Cannot move system application");
12883                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12884                } else if (pkg.mOperationPending) {
12885                    Slog.w(TAG, "Attempt to move package which has pending operations");
12886                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12887                } else {
12888                    // Find install location first
12889                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12890                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12891                        Slog.w(TAG, "Ambigous flags specified for move location.");
12892                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12893                    } else {
12894                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12895                                : PackageManager.INSTALL_INTERNAL;
12896                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12897                                : PackageManager.INSTALL_INTERNAL;
12898
12899                        if (newFlags == currFlags) {
12900                            Slog.w(TAG, "No move required. Trying to move to same location");
12901                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12902                        } else {
12903                            if (isForwardLocked(pkg)) {
12904                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12905                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12906                            }
12907                        }
12908                    }
12909                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12910                        pkg.mOperationPending = true;
12911                    }
12912                }
12913            }
12914
12915            /*
12916             * TODO this next block probably shouldn't be inside the lock. We
12917             * can't guarantee these won't change after this is fired off
12918             * anyway.
12919             */
12920            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12921                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false),
12922                        returnCode);
12923            } else {
12924                Message msg = mHandler.obtainMessage(INIT_COPY);
12925                final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
12926                final boolean multiArch = isMultiArch(pkg.applicationInfo);
12927                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
12928                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
12929                        pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch);
12930                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12931                        instructionSets, pkg.applicationInfo.uid, user, multiArch);
12932                msg.obj = mp;
12933                mHandler.sendMessage(msg);
12934            }
12935        }
12936    }
12937
12938    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12939        // Queue up an async operation since the package deletion may take a
12940        // little while.
12941        mHandler.post(new Runnable() {
12942            public void run() {
12943                // TODO fix this; this does nothing.
12944                mHandler.removeCallbacks(this);
12945                int returnCode = currentStatus;
12946                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12947                    int uidArr[] = null;
12948                    ArrayList<String> pkgList = null;
12949                    synchronized (mPackages) {
12950                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12951                        if (pkg == null) {
12952                            Slog.w(TAG, " Package " + mp.packageName
12953                                    + " doesn't exist. Aborting move");
12954                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12955                        } else if (!mp.srcArgs.getCodePath().equals(
12956                                pkg.applicationInfo.getCodePath())) {
12957                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12958                                    + mp.srcArgs.getCodePath() + " to "
12959                                    + pkg.applicationInfo.getCodePath()
12960                                    + " Aborting move and returning error");
12961                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12962                        } else {
12963                            uidArr = new int[] {
12964                                pkg.applicationInfo.uid
12965                            };
12966                            pkgList = new ArrayList<String>();
12967                            pkgList.add(mp.packageName);
12968                        }
12969                    }
12970                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12971                        // Send resources unavailable broadcast
12972                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12973                        // Update package code and resource paths
12974                        synchronized (mInstallLock) {
12975                            synchronized (mPackages) {
12976                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12977                                // Recheck for package again.
12978                                if (pkg == null) {
12979                                    Slog.w(TAG, " Package " + mp.packageName
12980                                            + " doesn't exist. Aborting move");
12981                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12982                                } else if (!mp.srcArgs.getCodePath().equals(
12983                                        pkg.applicationInfo.getCodePath())) {
12984                                    Slog.w(TAG, "Package " + mp.packageName
12985                                            + " code path changed from " + mp.srcArgs.getCodePath()
12986                                            + " to " + pkg.applicationInfo.getCodePath()
12987                                            + " Aborting move and returning error");
12988                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12989                                } else {
12990                                    final String oldCodePath = pkg.codePath;
12991                                    final String newCodePath = mp.targetArgs.getCodePath();
12992                                    final String newResPath = mp.targetArgs.getResourcePath();
12993                                    // TODO: This assumes the new style of installation.
12994                                    // should we look at legacyNativeLibraryPath ?
12995                                    final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath();
12996                                    final File newNativeDir = new File(newNativeRoot);
12997
12998                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12999                                        // TODO(multiArch): Fix this so that it looks at the existing
13000                                        // recorded CPU abis from the package. There's no need for a separate
13001                                        // round of ABI scanning here.
13002                                        NativeLibraryHelper.Handle handle = null;
13003                                        try {
13004                                            handle = NativeLibraryHelper.Handle.create(
13005                                                    new File(newCodePath));
13006                                            final int abi = NativeLibraryHelper.findSupportedAbi(
13007                                                    handle, Build.SUPPORTED_ABIS);
13008                                            if (abi >= 0) {
13009                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
13010                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
13011                                            }
13012                                        } catch (IOException ioe) {
13013                                            Slog.w(TAG, "Unable to extract native libs for package :"
13014                                                    + mp.packageName, ioe);
13015                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
13016                                        } finally {
13017                                            IoUtils.closeQuietly(handle);
13018                                        }
13019                                    }
13020
13021                                    final int[] users = sUserManager.getUserIds();
13022                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13023                                        for (int user : users) {
13024                                            // TODO(multiArch): Fix this so that it links to the
13025                                            // correct directory. We're currently pointing to root. but we
13026                                            // must point to the arch specific subdirectory (if applicable).
13027                                            //
13028                                            // TODO(multiArch): Bogus reference to nativeLibraryDir.
13029                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
13030                                                    newNativeRoot, user) < 0) {
13031                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13032                                            }
13033                                        }
13034                                    }
13035
13036                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13037                                        pkg.codePath = newCodePath;
13038                                        pkg.baseCodePath = newCodePath;
13039                                        // Move dex files around
13040                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
13041                                            // Moving of dex files failed. Set
13042                                            // error code and abort move.
13043                                            pkg.codePath = oldCodePath;
13044                                            pkg.baseCodePath = oldCodePath;
13045                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
13046                                        }
13047                                    }
13048
13049                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13050                                        pkg.applicationInfo.setCodePath(newCodePath);
13051                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
13052                                        pkg.applicationInfo.setSplitCodePaths(null);
13053                                        pkg.applicationInfo.setResourcePath(newResPath);
13054                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
13055                                        pkg.applicationInfo.setSplitResourcePaths(null);
13056
13057                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
13058                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
13059                                        ps.codePathString = ps.codePath.getPath();
13060                                        ps.resourcePath = new File(pkg.applicationInfo.getResourcePath());
13061                                        ps.resourcePathString = ps.resourcePath.getPath();
13062
13063                                        // Note that we don't have to recalculate the primary and secondary
13064                                        // CPU ABIs because they must already have been calculated during the
13065                                        // initial install of the app.
13066                                        ps.legacyNativeLibraryPathString = null;
13067
13068                                        // Set the application info flag
13069                                        // correctly.
13070                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
13071                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13072                                        } else {
13073                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
13074                                        }
13075                                        ps.setFlags(pkg.applicationInfo.flags);
13076                                        mAppDirs.remove(oldCodePath);
13077                                        mAppDirs.put(newCodePath, pkg);
13078                                        // Persist settings
13079                                        mSettings.writeLPr();
13080                                    }
13081                                }
13082                            }
13083                        }
13084                        // Send resources available broadcast
13085                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13086                    }
13087                }
13088                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13089                    // Clean up failed installation
13090                    if (mp.targetArgs != null) {
13091                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
13092                                -1);
13093                    }
13094                } else {
13095                    // Force a gc to clear things up.
13096                    Runtime.getRuntime().gc();
13097                    // Delete older code
13098                    synchronized (mInstallLock) {
13099                        mp.srcArgs.doPostDeleteLI(true);
13100                    }
13101                }
13102
13103                // Allow more operations on this file if we didn't fail because
13104                // an operation was already pending for this package.
13105                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13106                    synchronized (mPackages) {
13107                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13108                        if (pkg != null) {
13109                            pkg.mOperationPending = false;
13110                       }
13111                   }
13112                }
13113
13114                IPackageMoveObserver observer = mp.observer;
13115                if (observer != null) {
13116                    try {
13117                        observer.packageMoved(mp.packageName, returnCode);
13118                    } catch (RemoteException e) {
13119                        Log.i(TAG, "Observer no longer exists.");
13120                    }
13121                }
13122            }
13123        });
13124    }
13125
13126    @Override
13127    public boolean setInstallLocation(int loc) {
13128        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13129                null);
13130        if (getInstallLocation() == loc) {
13131            return true;
13132        }
13133        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13134                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13135            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13136                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13137            return true;
13138        }
13139        return false;
13140   }
13141
13142    @Override
13143    public int getInstallLocation() {
13144        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13145                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13146                PackageHelper.APP_INSTALL_AUTO);
13147    }
13148
13149    /** Called by UserManagerService */
13150    void cleanUpUserLILPw(int userHandle) {
13151        mDirtyUsers.remove(userHandle);
13152        mSettings.removeUserLPw(userHandle);
13153        mPendingBroadcasts.remove(userHandle);
13154        if (mInstaller != null) {
13155            // Technically, we shouldn't be doing this with the package lock
13156            // held.  However, this is very rare, and there is already so much
13157            // other disk I/O going on, that we'll let it slide for now.
13158            mInstaller.removeUserDataDirs(userHandle);
13159        }
13160        mUserNeedsBadging.delete(userHandle);
13161    }
13162
13163    /** Called by UserManagerService */
13164    void createNewUserLILPw(int userHandle, File path) {
13165        if (mInstaller != null) {
13166            mInstaller.createUserConfig(userHandle);
13167            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13168        }
13169    }
13170
13171    @Override
13172    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13173        mContext.enforceCallingOrSelfPermission(
13174                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13175                "Only package verification agents can read the verifier device identity");
13176
13177        synchronized (mPackages) {
13178            return mSettings.getVerifierDeviceIdentityLPw();
13179        }
13180    }
13181
13182    @Override
13183    public void setPermissionEnforced(String permission, boolean enforced) {
13184        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13185        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13186            synchronized (mPackages) {
13187                if (mSettings.mReadExternalStorageEnforced == null
13188                        || mSettings.mReadExternalStorageEnforced != enforced) {
13189                    mSettings.mReadExternalStorageEnforced = enforced;
13190                    mSettings.writeLPr();
13191                }
13192            }
13193            // kill any non-foreground processes so we restart them and
13194            // grant/revoke the GID.
13195            final IActivityManager am = ActivityManagerNative.getDefault();
13196            if (am != null) {
13197                final long token = Binder.clearCallingIdentity();
13198                try {
13199                    am.killProcessesBelowForeground("setPermissionEnforcement");
13200                } catch (RemoteException e) {
13201                } finally {
13202                    Binder.restoreCallingIdentity(token);
13203                }
13204            }
13205        } else {
13206            throw new IllegalArgumentException("No selective enforcement for " + permission);
13207        }
13208    }
13209
13210    @Override
13211    @Deprecated
13212    public boolean isPermissionEnforced(String permission) {
13213        return true;
13214    }
13215
13216    @Override
13217    public boolean isStorageLow() {
13218        final long token = Binder.clearCallingIdentity();
13219        try {
13220            final DeviceStorageMonitorInternal
13221                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13222            if (dsm != null) {
13223                return dsm.isMemoryLow();
13224            } else {
13225                return false;
13226            }
13227        } finally {
13228            Binder.restoreCallingIdentity(token);
13229        }
13230    }
13231
13232    @Override
13233    public IPackageInstaller getPackageInstaller() {
13234        return mInstallerService;
13235    }
13236
13237    private boolean userNeedsBadging(int userId) {
13238        int index = mUserNeedsBadging.indexOfKey(userId);
13239        if (index < 0) {
13240            final UserInfo userInfo;
13241            final long token = Binder.clearCallingIdentity();
13242            try {
13243                userInfo = sUserManager.getUserInfo(userId);
13244            } finally {
13245                Binder.restoreCallingIdentity(token);
13246            }
13247            final boolean b;
13248            if (userInfo != null && userInfo.isManagedProfile()) {
13249                b = true;
13250            } else {
13251                b = false;
13252            }
13253            mUserNeedsBadging.put(userId, b);
13254            return b;
13255        }
13256        return mUserNeedsBadging.valueAt(index);
13257    }
13258
13259    @Override
13260    public KeySetHandle getKeySetByAlias(String packageName, String alias) {
13261        if (packageName == null || alias == null) {
13262            return null;
13263        }
13264        synchronized(mPackages) {
13265            final PackageParser.Package pkg = mPackages.get(packageName);
13266            if (pkg == null) {
13267                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13268                throw new IllegalArgumentException("Unknown package: " + packageName);
13269            }
13270            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13271                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13272                throw new SecurityException("May not access KeySets defined by"
13273                        + " aliases in other applications.");
13274            }
13275            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13276            return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias);
13277        }
13278    }
13279
13280    @Override
13281    public KeySetHandle getSigningKeySet(String packageName) {
13282        if (packageName == null) {
13283            return null;
13284        }
13285        synchronized(mPackages) {
13286            final PackageParser.Package pkg = mPackages.get(packageName);
13287            if (pkg == null) {
13288                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13289                throw new IllegalArgumentException("Unknown package: " + packageName);
13290            }
13291            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13292                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13293                throw new SecurityException("May not access signing KeySet of other apps.");
13294            }
13295            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13296            return ksms.getSigningKeySetByPackageNameLPr(packageName);
13297        }
13298    }
13299
13300    @Override
13301    public boolean isPackageSignedByKeySet(String packageName, IBinder ks) {
13302        if (packageName == null || ks == null) {
13303            return false;
13304        }
13305        synchronized(mPackages) {
13306            final PackageParser.Package pkg = mPackages.get(packageName);
13307            if (pkg == null) {
13308                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13309                throw new IllegalArgumentException("Unknown package: " + packageName);
13310            }
13311            if (ks instanceof KeySetHandle) {
13312                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13313                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks);
13314            }
13315            return false;
13316        }
13317    }
13318
13319    @Override
13320    public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) {
13321        if (packageName == null || ks == null) {
13322            return false;
13323        }
13324        synchronized(mPackages) {
13325            final PackageParser.Package pkg = mPackages.get(packageName);
13326            if (pkg == null) {
13327                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13328                throw new IllegalArgumentException("Unknown package: " + packageName);
13329            }
13330            if (ks instanceof KeySetHandle) {
13331                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13332                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks);
13333            }
13334            return false;
13335        }
13336    }
13337}
13338