PackageManagerService.java revision 48e17629b0b6c89cb77342c0364a1cf3a0b2a0fb
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
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 com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
56import static com.android.internal.util.ArrayUtils.appendInt;
57import static com.android.internal.util.ArrayUtils.removeInt;
58
59import android.util.ArrayMap;
60
61import com.android.internal.R;
62import com.android.internal.app.IMediaContainerService;
63import com.android.internal.app.ResolverActivity;
64import com.android.internal.content.NativeLibraryHelper;
65import com.android.internal.content.PackageHelper;
66import com.android.internal.os.IParcelFileDescriptorFactory;
67import com.android.internal.util.ArrayUtils;
68import com.android.internal.util.FastPrintWriter;
69import com.android.internal.util.FastXmlSerializer;
70import com.android.internal.util.IndentingPrintWriter;
71import com.android.server.EventLogTags;
72import com.android.server.IntentResolver;
73import com.android.server.LocalServices;
74import com.android.server.ServiceThread;
75import com.android.server.SystemConfig;
76import com.android.server.Watchdog;
77import com.android.server.pm.Settings.DatabaseVersion;
78import com.android.server.storage.DeviceStorageMonitorInternal;
79
80import org.xmlpull.v1.XmlSerializer;
81
82import android.app.ActivityManager;
83import android.app.ActivityManagerNative;
84import android.app.AppGlobals;
85import android.app.IActivityManager;
86import android.app.admin.IDevicePolicyManager;
87import android.app.backup.IBackupManager;
88import android.app.usage.UsageStats;
89import android.app.usage.UsageStatsManager;
90import android.content.BroadcastReceiver;
91import android.content.ComponentName;
92import android.content.Context;
93import android.content.IIntentReceiver;
94import android.content.Intent;
95import android.content.IntentFilter;
96import android.content.IntentSender;
97import android.content.IntentSender.SendIntentException;
98import android.content.ServiceConnection;
99import android.content.pm.ActivityInfo;
100import android.content.pm.ApplicationInfo;
101import android.content.pm.FeatureInfo;
102import android.content.pm.IPackageDataObserver;
103import android.content.pm.IPackageDeleteObserver;
104import android.content.pm.IPackageDeleteObserver2;
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.InstrumentationInfo;
111import android.content.pm.KeySet;
112import android.content.pm.ManifestDigest;
113import android.content.pm.PackageCleanItem;
114import android.content.pm.PackageInfo;
115import android.content.pm.PackageInfoLite;
116import android.content.pm.PackageInstaller;
117import android.content.pm.PackageManager;
118import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
119import android.content.pm.PackageParser.ActivityIntentInfo;
120import android.content.pm.PackageParser.PackageLite;
121import android.content.pm.PackageParser.PackageParserException;
122import android.content.pm.PackageParser;
123import android.content.pm.PackageStats;
124import android.content.pm.PackageUserState;
125import android.content.pm.ParceledListSlice;
126import android.content.pm.PermissionGroupInfo;
127import android.content.pm.PermissionInfo;
128import android.content.pm.ProviderInfo;
129import android.content.pm.ResolveInfo;
130import android.content.pm.ServiceInfo;
131import android.content.pm.Signature;
132import android.content.pm.UserInfo;
133import android.content.pm.VerificationParams;
134import android.content.pm.VerifierDeviceIdentity;
135import android.content.pm.VerifierInfo;
136import android.content.res.Resources;
137import android.hardware.display.DisplayManager;
138import android.net.Uri;
139import android.os.Binder;
140import android.os.Build;
141import android.os.Bundle;
142import android.os.Environment;
143import android.os.Environment.UserEnvironment;
144import android.os.storage.IMountService;
145import android.os.storage.StorageManager;
146import android.os.Debug;
147import android.os.FileUtils;
148import android.os.Handler;
149import android.os.IBinder;
150import android.os.Looper;
151import android.os.Message;
152import android.os.Parcel;
153import android.os.ParcelFileDescriptor;
154import android.os.Process;
155import android.os.RemoteException;
156import android.os.SELinux;
157import android.os.ServiceManager;
158import android.os.SystemClock;
159import android.os.SystemProperties;
160import android.os.UserHandle;
161import android.os.UserManager;
162import android.security.KeyStore;
163import android.security.SystemKeyStore;
164import android.system.ErrnoException;
165import android.system.Os;
166import android.system.StructStat;
167import android.text.TextUtils;
168import android.text.format.DateUtils;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.PrintStreamPrinter;
177import android.util.Slog;
178import android.util.SparseArray;
179import android.util.SparseBooleanArray;
180import android.view.Display;
181
182import java.io.BufferedInputStream;
183import java.io.BufferedOutputStream;
184import java.io.BufferedReader;
185import java.io.File;
186import java.io.FileDescriptor;
187import java.io.FileInputStream;
188import java.io.FileNotFoundException;
189import java.io.FileOutputStream;
190import java.io.FileReader;
191import java.io.FilenameFilter;
192import java.io.IOException;
193import java.io.InputStream;
194import java.io.PrintWriter;
195import java.nio.charset.StandardCharsets;
196import java.security.NoSuchAlgorithmException;
197import java.security.PublicKey;
198import java.security.cert.CertificateEncodingException;
199import java.security.cert.CertificateException;
200import java.text.SimpleDateFormat;
201import java.util.ArrayList;
202import java.util.Arrays;
203import java.util.Collection;
204import java.util.Collections;
205import java.util.Comparator;
206import java.util.Date;
207import java.util.Iterator;
208import java.util.List;
209import java.util.Map;
210import java.util.Objects;
211import java.util.Set;
212import java.util.concurrent.atomic.AtomicBoolean;
213import java.util.concurrent.atomic.AtomicLong;
214
215import dalvik.system.DexFile;
216import dalvik.system.StaleDexCacheError;
217import dalvik.system.VMRuntime;
218
219import libcore.io.IoUtils;
220import libcore.util.EmptyArray;
221
222/**
223 * Keep track of all those .apks everywhere.
224 *
225 * This is very central to the platform's security; please run the unit
226 * tests whenever making modifications here:
227 *
228mmm frameworks/base/tests/AndroidTests
229adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
230adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
231 *
232 * {@hide}
233 */
234public class PackageManagerService extends IPackageManager.Stub {
235    static final String TAG = "PackageManager";
236    static final boolean DEBUG_SETTINGS = false;
237    static final boolean DEBUG_PREFERRED = false;
238    static final boolean DEBUG_UPGRADE = false;
239    private static final boolean DEBUG_INSTALL = false;
240    private static final boolean DEBUG_REMOVE = false;
241    private static final boolean DEBUG_BROADCASTS = false;
242    private static final boolean DEBUG_SHOW_INFO = false;
243    private static final boolean DEBUG_PACKAGE_INFO = false;
244    private static final boolean DEBUG_INTENT_MATCHING = false;
245    private static final boolean DEBUG_PACKAGE_SCANNING = false;
246    private static final boolean DEBUG_VERIFY = false;
247    private static final boolean DEBUG_DEXOPT = false;
248    private static final boolean DEBUG_ABI_SELECTION = false;
249
250    private static final int RADIO_UID = Process.PHONE_UID;
251    private static final int LOG_UID = Process.LOG_UID;
252    private static final int NFC_UID = Process.NFC_UID;
253    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
254    private static final int SHELL_UID = Process.SHELL_UID;
255
256    // Cap the size of permission trees that 3rd party apps can define
257    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
258
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_NO_DEX = 1<<1;
264    static final int SCAN_FORCE_DEX = 1<<2;
265    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
266    static final int SCAN_NEW_INSTALL = 1<<4;
267    static final int SCAN_NO_PATHS = 1<<5;
268    static final int SCAN_UPDATE_TIME = 1<<6;
269    static final int SCAN_DEFER_DEX = 1<<7;
270    static final int SCAN_BOOTING = 1<<8;
271    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
272    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
273    static final int SCAN_REPLACING = 1<<11;
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     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
287     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
288     * settings entry if available, otherwise we use the hardcoded default.  If it's been
289     * more than this long since the last fstrim, we force one during the boot sequence.
290     *
291     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
292     * one gets run at the next available charging+idle time.  This final mandatory
293     * no-fstrim check kicks in only of the other scheduling criteria is never met.
294     */
295    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
296
297    /**
298     * Whether verification is enabled by default.
299     */
300    private static final boolean DEFAULT_VERIFY_ENABLE = true;
301
302    /**
303     * The default maximum time to wait for the verification agent to return in
304     * milliseconds.
305     */
306    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
307
308    /**
309     * The default response for package verification timeout.
310     *
311     * This can be either PackageManager.VERIFICATION_ALLOW or
312     * PackageManager.VERIFICATION_REJECT.
313     */
314    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
315
316    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
317
318    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
319            DEFAULT_CONTAINER_PACKAGE,
320            "com.android.defcontainer.DefaultContainerService");
321
322    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
323
324    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
325
326    private static String sPreferredInstructionSet;
327
328    final ServiceThread mHandlerThread;
329
330    private static final String IDMAP_PREFIX = "/data/resource-cache/";
331    private static final String IDMAP_SUFFIX = "@idmap";
332
333    final PackageHandler mHandler;
334
335    /**
336     * Messages for {@link #mHandler} that need to wait for system ready before
337     * being dispatched.
338     */
339    private ArrayList<Message> mPostSystemReadyMessages;
340
341    final int mSdkVersion = Build.VERSION.SDK_INT;
342
343    final Context mContext;
344    final boolean mFactoryTest;
345    final boolean mOnlyCore;
346    final boolean mLazyDexOpt;
347    final long mDexOptLRUThresholdInMills;
348    final DisplayMetrics mMetrics;
349    final int mDefParseFlags;
350    final String[] mSeparateProcesses;
351    final boolean mIsUpgrade;
352
353    // This is where all application persistent data goes.
354    final File mAppDataDir;
355
356    // This is where all application persistent data goes for secondary users.
357    final File mUserAppDataDir;
358
359    /** The location for ASEC container files on internal storage. */
360    final String mAsecInternalPath;
361
362    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
363    // LOCK HELD.  Can be called with mInstallLock held.
364    final Installer mInstaller;
365
366    /** Directory where installed third-party apps stored */
367    final File mAppInstallDir;
368
369    /**
370     * Directory to which applications installed internally have their
371     * 32 bit native libraries copied.
372     */
373    private File mAppLib32InstallDir;
374
375    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
376    // apps.
377    final File mDrmAppPrivateInstallDir;
378
379    // ----------------------------------------------------------------
380
381    // Lock for state used when installing and doing other long running
382    // operations.  Methods that must be called with this lock held have
383    // the suffix "LI".
384    final Object mInstallLock = new Object();
385
386    // ----------------------------------------------------------------
387
388    // Keys are String (package name), values are Package.  This also serves
389    // as the lock for the global state.  Methods that must be called with
390    // this lock held have the prefix "LP".
391    final ArrayMap<String, PackageParser.Package> mPackages =
392            new ArrayMap<String, PackageParser.Package>();
393
394    // Tracks available target package names -> overlay package paths.
395    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
396        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
397
398    final Settings mSettings;
399    boolean mRestoredSettings;
400
401    // System configuration read by SystemConfig.
402    final int[] mGlobalGids;
403    final SparseArray<ArraySet<String>> mSystemPermissions;
404    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
405
406    // If mac_permissions.xml was found for seinfo labeling.
407    boolean mFoundPolicyFile;
408
409    // If a recursive restorecon of /data/data/<pkg> is needed.
410    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
411
412    public static final class SharedLibraryEntry {
413        public final String path;
414        public final String apk;
415
416        SharedLibraryEntry(String _path, String _apk) {
417            path = _path;
418            apk = _apk;
419        }
420    }
421
422    // Currently known shared libraries.
423    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
424            new ArrayMap<String, SharedLibraryEntry>();
425
426    // All available activities, for your resolving pleasure.
427    final ActivityIntentResolver mActivities =
428            new ActivityIntentResolver();
429
430    // All available receivers, for your resolving pleasure.
431    final ActivityIntentResolver mReceivers =
432            new ActivityIntentResolver();
433
434    // All available services, for your resolving pleasure.
435    final ServiceIntentResolver mServices = new ServiceIntentResolver();
436
437    // All available providers, for your resolving pleasure.
438    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
439
440    // Mapping from provider base names (first directory in content URI codePath)
441    // to the provider information.
442    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
443            new ArrayMap<String, PackageParser.Provider>();
444
445    // Mapping from instrumentation class names to info about them.
446    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
447            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
448
449    // Mapping from permission names to info about them.
450    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
451            new ArrayMap<String, PackageParser.PermissionGroup>();
452
453    // Packages whose data we have transfered into another package, thus
454    // should no longer exist.
455    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
456
457    // Broadcast actions that are only available to the system.
458    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
459
460    /** List of packages waiting for verification. */
461    final SparseArray<PackageVerificationState> mPendingVerification
462            = new SparseArray<PackageVerificationState>();
463
464    /** Set of packages associated with each app op permission. */
465    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
466
467    final PackageInstallerService mInstallerService;
468
469    ArraySet<PackageParser.Package> mDeferredDexOpt = null;
470
471    // Cache of users who need badging.
472    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
473
474    /** Token for keys in mPendingVerification. */
475    private int mPendingVerificationToken = 0;
476
477    volatile boolean mSystemReady;
478    volatile boolean mSafeMode;
479    volatile boolean mHasSystemUidErrors;
480
481    ApplicationInfo mAndroidApplication;
482    final ActivityInfo mResolveActivity = new ActivityInfo();
483    final ResolveInfo mResolveInfo = new ResolveInfo();
484    ComponentName mResolveComponentName;
485    PackageParser.Package mPlatformPackage;
486    ComponentName mCustomResolverComponentName;
487
488    boolean mResolverReplaced = false;
489
490    // Set of pending broadcasts for aggregating enable/disable of components.
491    static class PendingPackageBroadcasts {
492        // for each user id, a map of <package name -> components within that package>
493        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
494
495        public PendingPackageBroadcasts() {
496            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
497        }
498
499        public ArrayList<String> get(int userId, String packageName) {
500            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
501            return packages.get(packageName);
502        }
503
504        public void put(int userId, String packageName, ArrayList<String> components) {
505            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
506            packages.put(packageName, components);
507        }
508
509        public void remove(int userId, String packageName) {
510            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
511            if (packages != null) {
512                packages.remove(packageName);
513            }
514        }
515
516        public void remove(int userId) {
517            mUidMap.remove(userId);
518        }
519
520        public int userIdCount() {
521            return mUidMap.size();
522        }
523
524        public int userIdAt(int n) {
525            return mUidMap.keyAt(n);
526        }
527
528        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
529            return mUidMap.get(userId);
530        }
531
532        public int size() {
533            // total number of pending broadcast entries across all userIds
534            int num = 0;
535            for (int i = 0; i< mUidMap.size(); i++) {
536                num += mUidMap.valueAt(i).size();
537            }
538            return num;
539        }
540
541        public void clear() {
542            mUidMap.clear();
543        }
544
545        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
546            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
547            if (map == null) {
548                map = new ArrayMap<String, ArrayList<String>>();
549                mUidMap.put(userId, map);
550            }
551            return map;
552        }
553    }
554    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
555
556    // Service Connection to remote media container service to copy
557    // package uri's from external media onto secure containers
558    // or internal storage.
559    private IMediaContainerService mContainerService = null;
560
561    static final int SEND_PENDING_BROADCAST = 1;
562    static final int MCS_BOUND = 3;
563    static final int END_COPY = 4;
564    static final int INIT_COPY = 5;
565    static final int MCS_UNBIND = 6;
566    static final int START_CLEANING_PACKAGE = 7;
567    static final int FIND_INSTALL_LOC = 8;
568    static final int POST_INSTALL = 9;
569    static final int MCS_RECONNECT = 10;
570    static final int MCS_GIVE_UP = 11;
571    static final int UPDATED_MEDIA_STATUS = 12;
572    static final int WRITE_SETTINGS = 13;
573    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
574    static final int PACKAGE_VERIFIED = 15;
575    static final int CHECK_PENDING_VERIFICATION = 16;
576
577    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
578
579    // Delay time in millisecs
580    static final int BROADCAST_DELAY = 10 * 1000;
581
582    static UserManagerService sUserManager;
583
584    // Stores a list of users whose package restrictions file needs to be updated
585    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
586
587    final private DefaultContainerConnection mDefContainerConn =
588            new DefaultContainerConnection();
589    class DefaultContainerConnection implements ServiceConnection {
590        public void onServiceConnected(ComponentName name, IBinder service) {
591            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
592            IMediaContainerService imcs =
593                IMediaContainerService.Stub.asInterface(service);
594            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
595        }
596
597        public void onServiceDisconnected(ComponentName name) {
598            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
599        }
600    };
601
602    // Recordkeeping of restore-after-install operations that are currently in flight
603    // between the Package Manager and the Backup Manager
604    class PostInstallData {
605        public InstallArgs args;
606        public PackageInstalledInfo res;
607
608        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
609            args = _a;
610            res = _r;
611        }
612    };
613    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
614    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
615
616    private final String mRequiredVerifierPackage;
617
618    private final PackageUsage mPackageUsage = new PackageUsage();
619
620    private class PackageUsage {
621        private static final int WRITE_INTERVAL
622            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
623
624        private final Object mFileLock = new Object();
625        private final AtomicLong mLastWritten = new AtomicLong(0);
626        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
627
628        private boolean mIsHistoricalPackageUsageAvailable = true;
629
630        boolean isHistoricalPackageUsageAvailable() {
631            return mIsHistoricalPackageUsageAvailable;
632        }
633
634        void write(boolean force) {
635            if (force) {
636                writeInternal();
637                return;
638            }
639            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
640                && !DEBUG_DEXOPT) {
641                return;
642            }
643            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
644                new Thread("PackageUsage_DiskWriter") {
645                    @Override
646                    public void run() {
647                        try {
648                            writeInternal();
649                        } finally {
650                            mBackgroundWriteRunning.set(false);
651                        }
652                    }
653                }.start();
654            }
655        }
656
657        private void writeInternal() {
658            synchronized (mPackages) {
659                synchronized (mFileLock) {
660                    AtomicFile file = getFile();
661                    FileOutputStream f = null;
662                    try {
663                        f = file.startWrite();
664                        BufferedOutputStream out = new BufferedOutputStream(f);
665                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
666                        StringBuilder sb = new StringBuilder();
667                        for (PackageParser.Package pkg : mPackages.values()) {
668                            if (pkg.mLastPackageUsageTimeInMills == 0) {
669                                continue;
670                            }
671                            sb.setLength(0);
672                            sb.append(pkg.packageName);
673                            sb.append(' ');
674                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
675                            sb.append('\n');
676                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
677                        }
678                        out.flush();
679                        file.finishWrite(f);
680                    } catch (IOException e) {
681                        if (f != null) {
682                            file.failWrite(f);
683                        }
684                        Log.e(TAG, "Failed to write package usage times", e);
685                    }
686                }
687            }
688            mLastWritten.set(SystemClock.elapsedRealtime());
689        }
690
691        void readLP() {
692            synchronized (mFileLock) {
693                AtomicFile file = getFile();
694                BufferedInputStream in = null;
695                try {
696                    in = new BufferedInputStream(file.openRead());
697                    StringBuffer sb = new StringBuffer();
698                    while (true) {
699                        String packageName = readToken(in, sb, ' ');
700                        if (packageName == null) {
701                            break;
702                        }
703                        String timeInMillisString = readToken(in, sb, '\n');
704                        if (timeInMillisString == null) {
705                            throw new IOException("Failed to find last usage time for package "
706                                                  + packageName);
707                        }
708                        PackageParser.Package pkg = mPackages.get(packageName);
709                        if (pkg == null) {
710                            continue;
711                        }
712                        long timeInMillis;
713                        try {
714                            timeInMillis = Long.parseLong(timeInMillisString.toString());
715                        } catch (NumberFormatException e) {
716                            throw new IOException("Failed to parse " + timeInMillisString
717                                                  + " as a long.", e);
718                        }
719                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
720                    }
721                } catch (FileNotFoundException expected) {
722                    mIsHistoricalPackageUsageAvailable = false;
723                } catch (IOException e) {
724                    Log.w(TAG, "Failed to read package usage times", e);
725                } finally {
726                    IoUtils.closeQuietly(in);
727                }
728            }
729            mLastWritten.set(SystemClock.elapsedRealtime());
730        }
731
732        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
733                throws IOException {
734            sb.setLength(0);
735            while (true) {
736                int ch = in.read();
737                if (ch == -1) {
738                    if (sb.length() == 0) {
739                        return null;
740                    }
741                    throw new IOException("Unexpected EOF");
742                }
743                if (ch == endOfToken) {
744                    return sb.toString();
745                }
746                sb.append((char)ch);
747            }
748        }
749
750        private AtomicFile getFile() {
751            File dataDir = Environment.getDataDirectory();
752            File systemDir = new File(dataDir, "system");
753            File fname = new File(systemDir, "package-usage.list");
754            return new AtomicFile(fname);
755        }
756    }
757
758    class PackageHandler extends Handler {
759        private boolean mBound = false;
760        final ArrayList<HandlerParams> mPendingInstalls =
761            new ArrayList<HandlerParams>();
762
763        private boolean connectToService() {
764            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
765                    " DefaultContainerService");
766            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
767            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
768            if (mContext.bindServiceAsUser(service, mDefContainerConn,
769                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
770                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771                mBound = true;
772                return true;
773            }
774            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
775            return false;
776        }
777
778        private void disconnectService() {
779            mContainerService = null;
780            mBound = false;
781            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
782            mContext.unbindService(mDefContainerConn);
783            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
784        }
785
786        PackageHandler(Looper looper) {
787            super(looper);
788        }
789
790        public void handleMessage(Message msg) {
791            try {
792                doHandleMessage(msg);
793            } finally {
794                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
795            }
796        }
797
798        void doHandleMessage(Message msg) {
799            switch (msg.what) {
800                case INIT_COPY: {
801                    HandlerParams params = (HandlerParams) msg.obj;
802                    int idx = mPendingInstalls.size();
803                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
804                    // If a bind was already initiated we dont really
805                    // need to do anything. The pending install
806                    // will be processed later on.
807                    if (!mBound) {
808                        // If this is the only one pending we might
809                        // have to bind to the service again.
810                        if (!connectToService()) {
811                            Slog.e(TAG, "Failed to bind to media container service");
812                            params.serviceError();
813                            return;
814                        } else {
815                            // Once we bind to the service, the first
816                            // pending request will be processed.
817                            mPendingInstalls.add(idx, params);
818                        }
819                    } else {
820                        mPendingInstalls.add(idx, params);
821                        // Already bound to the service. Just make
822                        // sure we trigger off processing the first request.
823                        if (idx == 0) {
824                            mHandler.sendEmptyMessage(MCS_BOUND);
825                        }
826                    }
827                    break;
828                }
829                case MCS_BOUND: {
830                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
831                    if (msg.obj != null) {
832                        mContainerService = (IMediaContainerService) msg.obj;
833                    }
834                    if (mContainerService == null) {
835                        // Something seriously wrong. Bail out
836                        Slog.e(TAG, "Cannot bind to media container service");
837                        for (HandlerParams params : mPendingInstalls) {
838                            // Indicate service bind error
839                            params.serviceError();
840                        }
841                        mPendingInstalls.clear();
842                    } else if (mPendingInstalls.size() > 0) {
843                        HandlerParams params = mPendingInstalls.get(0);
844                        if (params != null) {
845                            if (params.startCopy()) {
846                                // We are done...  look for more work or to
847                                // go idle.
848                                if (DEBUG_SD_INSTALL) Log.i(TAG,
849                                        "Checking for more work or unbind...");
850                                // Delete pending install
851                                if (mPendingInstalls.size() > 0) {
852                                    mPendingInstalls.remove(0);
853                                }
854                                if (mPendingInstalls.size() == 0) {
855                                    if (mBound) {
856                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
857                                                "Posting delayed MCS_UNBIND");
858                                        removeMessages(MCS_UNBIND);
859                                        Message ubmsg = obtainMessage(MCS_UNBIND);
860                                        // Unbind after a little delay, to avoid
861                                        // continual thrashing.
862                                        sendMessageDelayed(ubmsg, 10000);
863                                    }
864                                } else {
865                                    // There are more pending requests in queue.
866                                    // Just post MCS_BOUND message to trigger processing
867                                    // of next pending install.
868                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
869                                            "Posting MCS_BOUND for next work");
870                                    mHandler.sendEmptyMessage(MCS_BOUND);
871                                }
872                            }
873                        }
874                    } else {
875                        // Should never happen ideally.
876                        Slog.w(TAG, "Empty queue");
877                    }
878                    break;
879                }
880                case MCS_RECONNECT: {
881                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
882                    if (mPendingInstalls.size() > 0) {
883                        if (mBound) {
884                            disconnectService();
885                        }
886                        if (!connectToService()) {
887                            Slog.e(TAG, "Failed to bind to media container service");
888                            for (HandlerParams params : mPendingInstalls) {
889                                // Indicate service bind error
890                                params.serviceError();
891                            }
892                            mPendingInstalls.clear();
893                        }
894                    }
895                    break;
896                }
897                case MCS_UNBIND: {
898                    // If there is no actual work left, then time to unbind.
899                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
900
901                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
902                        if (mBound) {
903                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
904
905                            disconnectService();
906                        }
907                    } else if (mPendingInstalls.size() > 0) {
908                        // There are more pending requests in queue.
909                        // Just post MCS_BOUND message to trigger processing
910                        // of next pending install.
911                        mHandler.sendEmptyMessage(MCS_BOUND);
912                    }
913
914                    break;
915                }
916                case MCS_GIVE_UP: {
917                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
918                    mPendingInstalls.remove(0);
919                    break;
920                }
921                case SEND_PENDING_BROADCAST: {
922                    String packages[];
923                    ArrayList<String> components[];
924                    int size = 0;
925                    int uids[];
926                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
927                    synchronized (mPackages) {
928                        if (mPendingBroadcasts == null) {
929                            return;
930                        }
931                        size = mPendingBroadcasts.size();
932                        if (size <= 0) {
933                            // Nothing to be done. Just return
934                            return;
935                        }
936                        packages = new String[size];
937                        components = new ArrayList[size];
938                        uids = new int[size];
939                        int i = 0;  // filling out the above arrays
940
941                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
942                            int packageUserId = mPendingBroadcasts.userIdAt(n);
943                            Iterator<Map.Entry<String, ArrayList<String>>> it
944                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
945                                            .entrySet().iterator();
946                            while (it.hasNext() && i < size) {
947                                Map.Entry<String, ArrayList<String>> ent = it.next();
948                                packages[i] = ent.getKey();
949                                components[i] = ent.getValue();
950                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
951                                uids[i] = (ps != null)
952                                        ? UserHandle.getUid(packageUserId, ps.appId)
953                                        : -1;
954                                i++;
955                            }
956                        }
957                        size = i;
958                        mPendingBroadcasts.clear();
959                    }
960                    // Send broadcasts
961                    for (int i = 0; i < size; i++) {
962                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
963                    }
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
965                    break;
966                }
967                case START_CLEANING_PACKAGE: {
968                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
969                    final String packageName = (String)msg.obj;
970                    final int userId = msg.arg1;
971                    final boolean andCode = msg.arg2 != 0;
972                    synchronized (mPackages) {
973                        if (userId == UserHandle.USER_ALL) {
974                            int[] users = sUserManager.getUserIds();
975                            for (int user : users) {
976                                mSettings.addPackageToCleanLPw(
977                                        new PackageCleanItem(user, packageName, andCode));
978                            }
979                        } else {
980                            mSettings.addPackageToCleanLPw(
981                                    new PackageCleanItem(userId, packageName, andCode));
982                        }
983                    }
984                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
985                    startCleaningPackages();
986                } break;
987                case POST_INSTALL: {
988                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
989                    PostInstallData data = mRunningInstalls.get(msg.arg1);
990                    mRunningInstalls.delete(msg.arg1);
991                    boolean deleteOld = false;
992
993                    if (data != null) {
994                        InstallArgs args = data.args;
995                        PackageInstalledInfo res = data.res;
996
997                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
998                            res.removedInfo.sendBroadcast(false, true, false);
999                            Bundle extras = new Bundle(1);
1000                            extras.putInt(Intent.EXTRA_UID, res.uid);
1001                            // Determine the set of users who are adding this
1002                            // package for the first time vs. those who are seeing
1003                            // an update.
1004                            int[] firstUsers;
1005                            int[] updateUsers = new int[0];
1006                            if (res.origUsers == null || res.origUsers.length == 0) {
1007                                firstUsers = res.newUsers;
1008                            } else {
1009                                firstUsers = new int[0];
1010                                for (int i=0; i<res.newUsers.length; i++) {
1011                                    int user = res.newUsers[i];
1012                                    boolean isNew = true;
1013                                    for (int j=0; j<res.origUsers.length; j++) {
1014                                        if (res.origUsers[j] == user) {
1015                                            isNew = false;
1016                                            break;
1017                                        }
1018                                    }
1019                                    if (isNew) {
1020                                        int[] newFirst = new int[firstUsers.length+1];
1021                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1022                                                firstUsers.length);
1023                                        newFirst[firstUsers.length] = user;
1024                                        firstUsers = newFirst;
1025                                    } else {
1026                                        int[] newUpdate = new int[updateUsers.length+1];
1027                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1028                                                updateUsers.length);
1029                                        newUpdate[updateUsers.length] = user;
1030                                        updateUsers = newUpdate;
1031                                    }
1032                                }
1033                            }
1034                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1035                                    res.pkg.applicationInfo.packageName,
1036                                    extras, null, null, firstUsers);
1037                            final boolean update = res.removedInfo.removedPackage != null;
1038                            if (update) {
1039                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1040                            }
1041                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1042                                    res.pkg.applicationInfo.packageName,
1043                                    extras, null, null, updateUsers);
1044                            if (update) {
1045                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1046                                        res.pkg.applicationInfo.packageName,
1047                                        extras, null, null, updateUsers);
1048                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1049                                        null, null,
1050                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1051
1052                                // treat asec-hosted packages like removable media on upgrade
1053                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1054                                    if (DEBUG_INSTALL) {
1055                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1056                                                + " is ASEC-hosted -> AVAILABLE");
1057                                    }
1058                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1059                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1060                                    pkgList.add(res.pkg.applicationInfo.packageName);
1061                                    sendResourcesChangedBroadcast(true, true,
1062                                            pkgList,uidArray, null);
1063                                }
1064                            }
1065                            if (res.removedInfo.args != null) {
1066                                // Remove the replaced package's older resources safely now
1067                                deleteOld = true;
1068                            }
1069
1070                            // Log current value of "unknown sources" setting
1071                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1072                                getUnknownSourcesSettings());
1073                        }
1074                        // Force a gc to clear up things
1075                        Runtime.getRuntime().gc();
1076                        // We delete after a gc for applications  on sdcard.
1077                        if (deleteOld) {
1078                            synchronized (mInstallLock) {
1079                                res.removedInfo.args.doPostDeleteLI(true);
1080                            }
1081                        }
1082                        if (args.observer != null) {
1083                            try {
1084                                Bundle extras = extrasForInstallResult(res);
1085                                args.observer.onPackageInstalled(res.name, res.returnCode,
1086                                        res.returnMsg, extras);
1087                            } catch (RemoteException e) {
1088                                Slog.i(TAG, "Observer no longer exists.");
1089                            }
1090                        }
1091                    } else {
1092                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1093                    }
1094                } break;
1095                case UPDATED_MEDIA_STATUS: {
1096                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1097                    boolean reportStatus = msg.arg1 == 1;
1098                    boolean doGc = msg.arg2 == 1;
1099                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1100                    if (doGc) {
1101                        // Force a gc to clear up stale containers.
1102                        Runtime.getRuntime().gc();
1103                    }
1104                    if (msg.obj != null) {
1105                        @SuppressWarnings("unchecked")
1106                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1107                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1108                        // Unload containers
1109                        unloadAllContainers(args);
1110                    }
1111                    if (reportStatus) {
1112                        try {
1113                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1114                            PackageHelper.getMountService().finishMediaUpdate();
1115                        } catch (RemoteException e) {
1116                            Log.e(TAG, "MountService not running?");
1117                        }
1118                    }
1119                } break;
1120                case WRITE_SETTINGS: {
1121                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1122                    synchronized (mPackages) {
1123                        removeMessages(WRITE_SETTINGS);
1124                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1125                        mSettings.writeLPr();
1126                        mDirtyUsers.clear();
1127                    }
1128                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1129                } break;
1130                case WRITE_PACKAGE_RESTRICTIONS: {
1131                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1132                    synchronized (mPackages) {
1133                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1134                        for (int userId : mDirtyUsers) {
1135                            mSettings.writePackageRestrictionsLPr(userId);
1136                        }
1137                        mDirtyUsers.clear();
1138                    }
1139                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1140                } break;
1141                case CHECK_PENDING_VERIFICATION: {
1142                    final int verificationId = msg.arg1;
1143                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1144
1145                    if ((state != null) && !state.timeoutExtended()) {
1146                        final InstallArgs args = state.getInstallArgs();
1147                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1148
1149                        Slog.i(TAG, "Verification timed out for " + originUri);
1150                        mPendingVerification.remove(verificationId);
1151
1152                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1153
1154                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1155                            Slog.i(TAG, "Continuing with installation of " + originUri);
1156                            state.setVerifierResponse(Binder.getCallingUid(),
1157                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1158                            broadcastPackageVerified(verificationId, originUri,
1159                                    PackageManager.VERIFICATION_ALLOW,
1160                                    state.getInstallArgs().getUser());
1161                            try {
1162                                ret = args.copyApk(mContainerService, true);
1163                            } catch (RemoteException e) {
1164                                Slog.e(TAG, "Could not contact the ContainerService");
1165                            }
1166                        } else {
1167                            broadcastPackageVerified(verificationId, originUri,
1168                                    PackageManager.VERIFICATION_REJECT,
1169                                    state.getInstallArgs().getUser());
1170                        }
1171
1172                        processPendingInstall(args, ret);
1173                        mHandler.sendEmptyMessage(MCS_UNBIND);
1174                    }
1175                    break;
1176                }
1177                case PACKAGE_VERIFIED: {
1178                    final int verificationId = msg.arg1;
1179
1180                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1181                    if (state == null) {
1182                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1183                        break;
1184                    }
1185
1186                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1187
1188                    state.setVerifierResponse(response.callerUid, response.code);
1189
1190                    if (state.isVerificationComplete()) {
1191                        mPendingVerification.remove(verificationId);
1192
1193                        final InstallArgs args = state.getInstallArgs();
1194                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1195
1196                        int ret;
1197                        if (state.isInstallAllowed()) {
1198                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1199                            broadcastPackageVerified(verificationId, originUri,
1200                                    response.code, state.getInstallArgs().getUser());
1201                            try {
1202                                ret = args.copyApk(mContainerService, true);
1203                            } catch (RemoteException e) {
1204                                Slog.e(TAG, "Could not contact the ContainerService");
1205                            }
1206                        } else {
1207                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1208                        }
1209
1210                        processPendingInstall(args, ret);
1211
1212                        mHandler.sendEmptyMessage(MCS_UNBIND);
1213                    }
1214
1215                    break;
1216                }
1217            }
1218        }
1219    }
1220
1221    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1222        Bundle extras = null;
1223        switch (res.returnCode) {
1224            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1225                extras = new Bundle();
1226                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1227                        res.origPermission);
1228                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1229                        res.origPackage);
1230                break;
1231            }
1232        }
1233        return extras;
1234    }
1235
1236    void scheduleWriteSettingsLocked() {
1237        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1238            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1239        }
1240    }
1241
1242    void scheduleWritePackageRestrictionsLocked(int userId) {
1243        if (!sUserManager.exists(userId)) return;
1244        mDirtyUsers.add(userId);
1245        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1246            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1247        }
1248    }
1249
1250    public static final PackageManagerService main(Context context, Installer installer,
1251            boolean factoryTest, boolean onlyCore) {
1252        PackageManagerService m = new PackageManagerService(context, installer,
1253                factoryTest, onlyCore);
1254        ServiceManager.addService("package", m);
1255        return m;
1256    }
1257
1258    static String[] splitString(String str, char sep) {
1259        int count = 1;
1260        int i = 0;
1261        while ((i=str.indexOf(sep, i)) >= 0) {
1262            count++;
1263            i++;
1264        }
1265
1266        String[] res = new String[count];
1267        i=0;
1268        count = 0;
1269        int lastI=0;
1270        while ((i=str.indexOf(sep, i)) >= 0) {
1271            res[count] = str.substring(lastI, i);
1272            count++;
1273            i++;
1274            lastI = i;
1275        }
1276        res[count] = str.substring(lastI, str.length());
1277        return res;
1278    }
1279
1280    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1281        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1282                Context.DISPLAY_SERVICE);
1283        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1284    }
1285
1286    public PackageManagerService(Context context, Installer installer,
1287            boolean factoryTest, boolean onlyCore) {
1288        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1289                SystemClock.uptimeMillis());
1290
1291        if (mSdkVersion <= 0) {
1292            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1293        }
1294
1295        mContext = context;
1296        mFactoryTest = factoryTest;
1297        mOnlyCore = onlyCore;
1298        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1299        mMetrics = new DisplayMetrics();
1300        mSettings = new Settings(context);
1301        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1302                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1304                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1306                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1308                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1309        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1310                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1311        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1312                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1313
1314        // TODO: add a property to control this?
1315        long dexOptLRUThresholdInMinutes;
1316        if (mLazyDexOpt) {
1317            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1318        } else {
1319            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1320        }
1321        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1322
1323        String separateProcesses = SystemProperties.get("debug.separate_processes");
1324        if (separateProcesses != null && separateProcesses.length() > 0) {
1325            if ("*".equals(separateProcesses)) {
1326                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1327                mSeparateProcesses = null;
1328                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1329            } else {
1330                mDefParseFlags = 0;
1331                mSeparateProcesses = separateProcesses.split(",");
1332                Slog.w(TAG, "Running with debug.separate_processes: "
1333                        + separateProcesses);
1334            }
1335        } else {
1336            mDefParseFlags = 0;
1337            mSeparateProcesses = null;
1338        }
1339
1340        mInstaller = installer;
1341
1342        getDefaultDisplayMetrics(context, mMetrics);
1343
1344        SystemConfig systemConfig = SystemConfig.getInstance();
1345        mGlobalGids = systemConfig.getGlobalGids();
1346        mSystemPermissions = systemConfig.getSystemPermissions();
1347        mAvailableFeatures = systemConfig.getAvailableFeatures();
1348
1349        synchronized (mInstallLock) {
1350        // writer
1351        synchronized (mPackages) {
1352            mHandlerThread = new ServiceThread(TAG,
1353                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1354            mHandlerThread.start();
1355            mHandler = new PackageHandler(mHandlerThread.getLooper());
1356            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1357
1358            File dataDir = Environment.getDataDirectory();
1359            mAppDataDir = new File(dataDir, "data");
1360            mAppInstallDir = new File(dataDir, "app");
1361            mAppLib32InstallDir = new File(dataDir, "app-lib");
1362            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1363            mUserAppDataDir = new File(dataDir, "user");
1364            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1365
1366            sUserManager = new UserManagerService(context, this,
1367                    mInstallLock, mPackages);
1368
1369            // Propagate permission configuration in to package manager.
1370            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1371                    = systemConfig.getPermissions();
1372            for (int i=0; i<permConfig.size(); i++) {
1373                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1374                BasePermission bp = mSettings.mPermissions.get(perm.name);
1375                if (bp == null) {
1376                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1377                    mSettings.mPermissions.put(perm.name, bp);
1378                }
1379                if (perm.gids != null) {
1380                    bp.gids = appendInts(bp.gids, perm.gids);
1381                }
1382            }
1383
1384            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1385            for (int i=0; i<libConfig.size(); i++) {
1386                mSharedLibraries.put(libConfig.keyAt(i),
1387                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1388            }
1389
1390            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1391
1392            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1393                    mSdkVersion, mOnlyCore);
1394
1395            String customResolverActivity = Resources.getSystem().getString(
1396                    R.string.config_customResolverActivity);
1397            if (TextUtils.isEmpty(customResolverActivity)) {
1398                customResolverActivity = null;
1399            } else {
1400                mCustomResolverComponentName = ComponentName.unflattenFromString(
1401                        customResolverActivity);
1402            }
1403
1404            long startTime = SystemClock.uptimeMillis();
1405
1406            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1407                    startTime);
1408
1409            // Set flag to monitor and not change apk file paths when
1410            // scanning install directories.
1411            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1412
1413            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1414
1415            /**
1416             * Add everything in the in the boot class path to the
1417             * list of process files because dexopt will have been run
1418             * if necessary during zygote startup.
1419             */
1420            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1421            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1422
1423            if (bootClassPath != null) {
1424                String[] bootClassPathElements = splitString(bootClassPath, ':');
1425                for (String element : bootClassPathElements) {
1426                    alreadyDexOpted.add(element);
1427                }
1428            } else {
1429                Slog.w(TAG, "No BOOTCLASSPATH found!");
1430            }
1431
1432            if (systemServerClassPath != null) {
1433                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1434                for (String element : systemServerClassPathElements) {
1435                    alreadyDexOpted.add(element);
1436                }
1437            } else {
1438                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1439            }
1440
1441            final List<String> allInstructionSets = getAllInstructionSets();
1442            final String[] dexCodeInstructionSets =
1443                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1444
1445            /**
1446             * Ensure all external libraries have had dexopt run on them.
1447             */
1448            if (mSharedLibraries.size() > 0) {
1449                // NOTE: For now, we're compiling these system "shared libraries"
1450                // (and framework jars) into all available architectures. It's possible
1451                // to compile them only when we come across an app that uses them (there's
1452                // already logic for that in scanPackageLI) but that adds some complexity.
1453                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1454                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1455                        final String lib = libEntry.path;
1456                        if (lib == null) {
1457                            continue;
1458                        }
1459
1460                        try {
1461                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1462                                                                                 dexCodeInstructionSet,
1463                                                                                 false);
1464                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1465                                alreadyDexOpted.add(lib);
1466
1467                                // The list of "shared libraries" we have at this point is
1468                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1469                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1470                                } else {
1471                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1472                                }
1473                            }
1474                        } catch (FileNotFoundException e) {
1475                            Slog.w(TAG, "Library not found: " + lib);
1476                        } catch (IOException e) {
1477                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1478                                    + e.getMessage());
1479                        }
1480                    }
1481                }
1482            }
1483
1484            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1485
1486            // Gross hack for now: we know this file doesn't contain any
1487            // code, so don't dexopt it to avoid the resulting log spew.
1488            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1489
1490            // Gross hack for now: we know this file is only part of
1491            // the boot class path for art, so don't dexopt it to
1492            // avoid the resulting log spew.
1493            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1494
1495            /**
1496             * And there are a number of commands implemented in Java, which
1497             * we currently need to do the dexopt on so that they can be
1498             * run from a non-root shell.
1499             */
1500            String[] frameworkFiles = frameworkDir.list();
1501            if (frameworkFiles != null) {
1502                // TODO: We could compile these only for the most preferred ABI. We should
1503                // first double check that the dex files for these commands are not referenced
1504                // by other system apps.
1505                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1506                    for (int i=0; i<frameworkFiles.length; i++) {
1507                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1508                        String path = libPath.getPath();
1509                        // Skip the file if we already did it.
1510                        if (alreadyDexOpted.contains(path)) {
1511                            continue;
1512                        }
1513                        // Skip the file if it is not a type we want to dexopt.
1514                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1515                            continue;
1516                        }
1517                        try {
1518                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1519                                                                                 dexCodeInstructionSet,
1520                                                                                 false);
1521                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1522                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1523                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1524                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1525                            }
1526                        } catch (FileNotFoundException e) {
1527                            Slog.w(TAG, "Jar not found: " + path);
1528                        } catch (IOException e) {
1529                            Slog.w(TAG, "Exception reading jar: " + path, e);
1530                        }
1531                    }
1532                }
1533            }
1534
1535            // Collect vendor overlay packages.
1536            // (Do this before scanning any apps.)
1537            // For security and version matching reason, only consider
1538            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1539            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1540            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1541                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1542
1543            // Find base frameworks (resource packages without code).
1544            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1545                    | PackageParser.PARSE_IS_SYSTEM_DIR
1546                    | PackageParser.PARSE_IS_PRIVILEGED,
1547                    scanFlags | SCAN_NO_DEX, 0);
1548
1549            // Collected privileged system packages.
1550            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1551            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1552                    | PackageParser.PARSE_IS_SYSTEM_DIR
1553                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1554
1555            // Collect ordinary system packages.
1556            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1557            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1558                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1559
1560            // Collect all vendor packages.
1561            File vendorAppDir = new File("/vendor/app");
1562            try {
1563                vendorAppDir = vendorAppDir.getCanonicalFile();
1564            } catch (IOException e) {
1565                // failed to look up canonical path, continue with original one
1566            }
1567            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1568                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1569
1570            // Collect all OEM packages.
1571            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1572            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1573                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1574
1575            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1576            mInstaller.moveFiles();
1577
1578            // Prune any system packages that no longer exist.
1579            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1580            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1581            if (!mOnlyCore) {
1582                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1583                while (psit.hasNext()) {
1584                    PackageSetting ps = psit.next();
1585
1586                    /*
1587                     * If this is not a system app, it can't be a
1588                     * disable system app.
1589                     */
1590                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1591                        continue;
1592                    }
1593
1594                    /*
1595                     * If the package is scanned, it's not erased.
1596                     */
1597                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1598                    if (scannedPkg != null) {
1599                        /*
1600                         * If the system app is both scanned and in the
1601                         * disabled packages list, then it must have been
1602                         * added via OTA. Remove it from the currently
1603                         * scanned package so the previously user-installed
1604                         * application can be scanned.
1605                         */
1606                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1607                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1608                                    + ps.name + "; removing system app.  Last known codePath="
1609                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1610                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1611                                    + scannedPkg.mVersionCode);
1612                            removePackageLI(ps, true);
1613                            expectingBetter.put(ps.name, ps.codePath);
1614                        }
1615
1616                        continue;
1617                    }
1618
1619                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1620                        psit.remove();
1621                        logCriticalInfo(Log.WARN, "System package " + ps.name
1622                                + " no longer exists; wiping its data");
1623                        removeDataDirsLI(ps.name);
1624                    } else {
1625                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1626                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1627                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1628                        }
1629                    }
1630                }
1631            }
1632
1633            //look for any incomplete package installations
1634            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1635            //clean up list
1636            for(int i = 0; i < deletePkgsList.size(); i++) {
1637                //clean up here
1638                cleanupInstallFailedPackage(deletePkgsList.get(i));
1639            }
1640            //delete tmp files
1641            deleteTempPackageFiles();
1642
1643            // Remove any shared userIDs that have no associated packages
1644            mSettings.pruneSharedUsersLPw();
1645
1646            if (!mOnlyCore) {
1647                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1648                        SystemClock.uptimeMillis());
1649                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1650
1651                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1652                        scanFlags, 0);
1653
1654                /**
1655                 * Remove disable package settings for any updated system
1656                 * apps that were removed via an OTA. If they're not a
1657                 * previously-updated app, remove them completely.
1658                 * Otherwise, just revoke their system-level permissions.
1659                 */
1660                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1661                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1662                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1663
1664                    String msg;
1665                    if (deletedPkg == null) {
1666                        msg = "Updated system package " + deletedAppName
1667                                + " no longer exists; wiping its data";
1668                        removeDataDirsLI(deletedAppName);
1669                    } else {
1670                        msg = "Updated system app + " + deletedAppName
1671                                + " no longer present; removing system privileges for "
1672                                + deletedAppName;
1673
1674                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1675
1676                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1677                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1678                    }
1679                    logCriticalInfo(Log.WARN, msg);
1680                }
1681
1682                /**
1683                 * Make sure all system apps that we expected to appear on
1684                 * the userdata partition actually showed up. If they never
1685                 * appeared, crawl back and revive the system version.
1686                 */
1687                for (int i = 0; i < expectingBetter.size(); i++) {
1688                    final String packageName = expectingBetter.keyAt(i);
1689                    if (!mPackages.containsKey(packageName)) {
1690                        final File scanFile = expectingBetter.valueAt(i);
1691
1692                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1693                                + " but never showed up; reverting to system");
1694
1695                        final int reparseFlags;
1696                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1697                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1698                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1699                                    | PackageParser.PARSE_IS_PRIVILEGED;
1700                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1701                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1702                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1703                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1704                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1705                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1706                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1707                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1708                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1709                        } else {
1710                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1711                            continue;
1712                        }
1713
1714                        mSettings.enableSystemPackageLPw(packageName);
1715
1716                        try {
1717                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1718                        } catch (PackageManagerException e) {
1719                            Slog.e(TAG, "Failed to parse original system package: "
1720                                    + e.getMessage());
1721                        }
1722                    }
1723                }
1724            }
1725
1726            // Now that we know all of the shared libraries, update all clients to have
1727            // the correct library paths.
1728            updateAllSharedLibrariesLPw();
1729
1730            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1731                // NOTE: We ignore potential failures here during a system scan (like
1732                // the rest of the commands above) because there's precious little we
1733                // can do about it. A settings error is reported, though.
1734                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1735                        false /* force dexopt */, false /* defer dexopt */);
1736            }
1737
1738            // Now that we know all the packages we are keeping,
1739            // read and update their last usage times.
1740            mPackageUsage.readLP();
1741
1742            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1743                    SystemClock.uptimeMillis());
1744            Slog.i(TAG, "Time to scan packages: "
1745                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1746                    + " seconds");
1747
1748            // If the platform SDK has changed since the last time we booted,
1749            // we need to re-grant app permission to catch any new ones that
1750            // appear.  This is really a hack, and means that apps can in some
1751            // cases get permissions that the user didn't initially explicitly
1752            // allow...  it would be nice to have some better way to handle
1753            // this situation.
1754            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1755                    != mSdkVersion;
1756            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1757                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1758                    + "; regranting permissions for internal storage");
1759            mSettings.mInternalSdkPlatform = mSdkVersion;
1760
1761            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1762                    | (regrantPermissions
1763                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1764                            : 0));
1765
1766            // If this is the first boot, and it is a normal boot, then
1767            // we need to initialize the default preferred apps.
1768            if (!mRestoredSettings && !onlyCore) {
1769                mSettings.readDefaultPreferredAppsLPw(this, 0);
1770            }
1771
1772            // If this is first boot after an OTA, and a normal boot, then
1773            // we need to clear code cache directories.
1774            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1775            if (mIsUpgrade && !onlyCore) {
1776                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1777                for (String pkgName : mSettings.mPackages.keySet()) {
1778                    deleteCodeCacheDirsLI(pkgName);
1779                }
1780                mSettings.mFingerprint = Build.FINGERPRINT;
1781            }
1782
1783            // All the changes are done during package scanning.
1784            mSettings.updateInternalDatabaseVersion();
1785
1786            // can downgrade to reader
1787            mSettings.writeLPr();
1788
1789            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1790                    SystemClock.uptimeMillis());
1791
1792
1793            mRequiredVerifierPackage = getRequiredVerifierLPr();
1794        } // synchronized (mPackages)
1795        } // synchronized (mInstallLock)
1796
1797        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1798
1799        // Now after opening every single application zip, make sure they
1800        // are all flushed.  Not really needed, but keeps things nice and
1801        // tidy.
1802        Runtime.getRuntime().gc();
1803    }
1804
1805    @Override
1806    public boolean isFirstBoot() {
1807        return !mRestoredSettings;
1808    }
1809
1810    @Override
1811    public boolean isOnlyCoreApps() {
1812        return mOnlyCore;
1813    }
1814
1815    @Override
1816    public boolean isUpgrade() {
1817        return mIsUpgrade;
1818    }
1819
1820    private String getRequiredVerifierLPr() {
1821        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1822        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1823                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1824
1825        String requiredVerifier = null;
1826
1827        final int N = receivers.size();
1828        for (int i = 0; i < N; i++) {
1829            final ResolveInfo info = receivers.get(i);
1830
1831            if (info.activityInfo == null) {
1832                continue;
1833            }
1834
1835            final String packageName = info.activityInfo.packageName;
1836
1837            final PackageSetting ps = mSettings.mPackages.get(packageName);
1838            if (ps == null) {
1839                continue;
1840            }
1841
1842            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1843            if (!gp.grantedPermissions
1844                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1845                continue;
1846            }
1847
1848            if (requiredVerifier != null) {
1849                throw new RuntimeException("There can be only one required verifier");
1850            }
1851
1852            requiredVerifier = packageName;
1853        }
1854
1855        return requiredVerifier;
1856    }
1857
1858    @Override
1859    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1860            throws RemoteException {
1861        try {
1862            return super.onTransact(code, data, reply, flags);
1863        } catch (RuntimeException e) {
1864            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1865                Slog.wtf(TAG, "Package Manager Crash", e);
1866            }
1867            throw e;
1868        }
1869    }
1870
1871    void cleanupInstallFailedPackage(PackageSetting ps) {
1872        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1873
1874        removeDataDirsLI(ps.name);
1875        if (ps.codePath != null) {
1876            if (ps.codePath.isDirectory()) {
1877                FileUtils.deleteContents(ps.codePath);
1878            }
1879            ps.codePath.delete();
1880        }
1881        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1882            if (ps.resourcePath.isDirectory()) {
1883                FileUtils.deleteContents(ps.resourcePath);
1884            }
1885            ps.resourcePath.delete();
1886        }
1887        mSettings.removePackageLPw(ps.name);
1888    }
1889
1890    static int[] appendInts(int[] cur, int[] add) {
1891        if (add == null) return cur;
1892        if (cur == null) return add;
1893        final int N = add.length;
1894        for (int i=0; i<N; i++) {
1895            cur = appendInt(cur, add[i]);
1896        }
1897        return cur;
1898    }
1899
1900    static int[] removeInts(int[] cur, int[] rem) {
1901        if (rem == null) return cur;
1902        if (cur == null) return cur;
1903        final int N = rem.length;
1904        for (int i=0; i<N; i++) {
1905            cur = removeInt(cur, rem[i]);
1906        }
1907        return cur;
1908    }
1909
1910    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1911        if (!sUserManager.exists(userId)) return null;
1912        final PackageSetting ps = (PackageSetting) p.mExtras;
1913        if (ps == null) {
1914            return null;
1915        }
1916        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1917        final PackageUserState state = ps.readUserState(userId);
1918        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1919                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1920                state, userId);
1921    }
1922
1923    @Override
1924    public boolean isPackageAvailable(String packageName, int userId) {
1925        if (!sUserManager.exists(userId)) return false;
1926        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1927        synchronized (mPackages) {
1928            PackageParser.Package p = mPackages.get(packageName);
1929            if (p != null) {
1930                final PackageSetting ps = (PackageSetting) p.mExtras;
1931                if (ps != null) {
1932                    final PackageUserState state = ps.readUserState(userId);
1933                    if (state != null) {
1934                        return PackageParser.isAvailable(state);
1935                    }
1936                }
1937            }
1938        }
1939        return false;
1940    }
1941
1942    @Override
1943    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1944        if (!sUserManager.exists(userId)) return null;
1945        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1946        // reader
1947        synchronized (mPackages) {
1948            PackageParser.Package p = mPackages.get(packageName);
1949            if (DEBUG_PACKAGE_INFO)
1950                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1951            if (p != null) {
1952                return generatePackageInfo(p, flags, userId);
1953            }
1954            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1955                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1956            }
1957        }
1958        return null;
1959    }
1960
1961    @Override
1962    public String[] currentToCanonicalPackageNames(String[] names) {
1963        String[] out = new String[names.length];
1964        // reader
1965        synchronized (mPackages) {
1966            for (int i=names.length-1; i>=0; i--) {
1967                PackageSetting ps = mSettings.mPackages.get(names[i]);
1968                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1969            }
1970        }
1971        return out;
1972    }
1973
1974    @Override
1975    public String[] canonicalToCurrentPackageNames(String[] names) {
1976        String[] out = new String[names.length];
1977        // reader
1978        synchronized (mPackages) {
1979            for (int i=names.length-1; i>=0; i--) {
1980                String cur = mSettings.mRenamedPackages.get(names[i]);
1981                out[i] = cur != null ? cur : names[i];
1982            }
1983        }
1984        return out;
1985    }
1986
1987    @Override
1988    public int getPackageUid(String packageName, int userId) {
1989        if (!sUserManager.exists(userId)) return -1;
1990        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1991        // reader
1992        synchronized (mPackages) {
1993            PackageParser.Package p = mPackages.get(packageName);
1994            if(p != null) {
1995                return UserHandle.getUid(userId, p.applicationInfo.uid);
1996            }
1997            PackageSetting ps = mSettings.mPackages.get(packageName);
1998            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1999                return -1;
2000            }
2001            p = ps.pkg;
2002            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2003        }
2004    }
2005
2006    @Override
2007    public int[] getPackageGids(String packageName) {
2008        // reader
2009        synchronized (mPackages) {
2010            PackageParser.Package p = mPackages.get(packageName);
2011            if (DEBUG_PACKAGE_INFO)
2012                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2013            if (p != null) {
2014                final PackageSetting ps = (PackageSetting)p.mExtras;
2015                return ps.getGids();
2016            }
2017        }
2018        // stupid thing to indicate an error.
2019        return new int[0];
2020    }
2021
2022    static final PermissionInfo generatePermissionInfo(
2023            BasePermission bp, int flags) {
2024        if (bp.perm != null) {
2025            return PackageParser.generatePermissionInfo(bp.perm, flags);
2026        }
2027        PermissionInfo pi = new PermissionInfo();
2028        pi.name = bp.name;
2029        pi.packageName = bp.sourcePackage;
2030        pi.nonLocalizedLabel = bp.name;
2031        pi.protectionLevel = bp.protectionLevel;
2032        return pi;
2033    }
2034
2035    @Override
2036    public PermissionInfo getPermissionInfo(String name, int flags) {
2037        // reader
2038        synchronized (mPackages) {
2039            final BasePermission p = mSettings.mPermissions.get(name);
2040            if (p != null) {
2041                return generatePermissionInfo(p, flags);
2042            }
2043            return null;
2044        }
2045    }
2046
2047    @Override
2048    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2049        // reader
2050        synchronized (mPackages) {
2051            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2052            for (BasePermission p : mSettings.mPermissions.values()) {
2053                if (group == null) {
2054                    if (p.perm == null || p.perm.info.group == null) {
2055                        out.add(generatePermissionInfo(p, flags));
2056                    }
2057                } else {
2058                    if (p.perm != null && group.equals(p.perm.info.group)) {
2059                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2060                    }
2061                }
2062            }
2063
2064            if (out.size() > 0) {
2065                return out;
2066            }
2067            return mPermissionGroups.containsKey(group) ? out : null;
2068        }
2069    }
2070
2071    @Override
2072    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2073        // reader
2074        synchronized (mPackages) {
2075            return PackageParser.generatePermissionGroupInfo(
2076                    mPermissionGroups.get(name), flags);
2077        }
2078    }
2079
2080    @Override
2081    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2082        // reader
2083        synchronized (mPackages) {
2084            final int N = mPermissionGroups.size();
2085            ArrayList<PermissionGroupInfo> out
2086                    = new ArrayList<PermissionGroupInfo>(N);
2087            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2088                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2089            }
2090            return out;
2091        }
2092    }
2093
2094    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2095            int userId) {
2096        if (!sUserManager.exists(userId)) return null;
2097        PackageSetting ps = mSettings.mPackages.get(packageName);
2098        if (ps != null) {
2099            if (ps.pkg == null) {
2100                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2101                        flags, userId);
2102                if (pInfo != null) {
2103                    return pInfo.applicationInfo;
2104                }
2105                return null;
2106            }
2107            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2108                    ps.readUserState(userId), userId);
2109        }
2110        return null;
2111    }
2112
2113    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2114            int userId) {
2115        if (!sUserManager.exists(userId)) return null;
2116        PackageSetting ps = mSettings.mPackages.get(packageName);
2117        if (ps != null) {
2118            PackageParser.Package pkg = ps.pkg;
2119            if (pkg == null) {
2120                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2121                    return null;
2122                }
2123                // Only data remains, so we aren't worried about code paths
2124                pkg = new PackageParser.Package(packageName);
2125                pkg.applicationInfo.packageName = packageName;
2126                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2127                pkg.applicationInfo.dataDir =
2128                        getDataPathForPackage(packageName, 0).getPath();
2129                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2130                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2131            }
2132            return generatePackageInfo(pkg, flags, userId);
2133        }
2134        return null;
2135    }
2136
2137    @Override
2138    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2139        if (!sUserManager.exists(userId)) return null;
2140        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2141        // writer
2142        synchronized (mPackages) {
2143            PackageParser.Package p = mPackages.get(packageName);
2144            if (DEBUG_PACKAGE_INFO) Log.v(
2145                    TAG, "getApplicationInfo " + packageName
2146                    + ": " + p);
2147            if (p != null) {
2148                PackageSetting ps = mSettings.mPackages.get(packageName);
2149                if (ps == null) return null;
2150                // Note: isEnabledLP() does not apply here - always return info
2151                return PackageParser.generateApplicationInfo(
2152                        p, flags, ps.readUserState(userId), userId);
2153            }
2154            if ("android".equals(packageName)||"system".equals(packageName)) {
2155                return mAndroidApplication;
2156            }
2157            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2158                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2159            }
2160        }
2161        return null;
2162    }
2163
2164
2165    @Override
2166    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2167        mContext.enforceCallingOrSelfPermission(
2168                android.Manifest.permission.CLEAR_APP_CACHE, null);
2169        // Queue up an async operation since clearing cache may take a little while.
2170        mHandler.post(new Runnable() {
2171            public void run() {
2172                mHandler.removeCallbacks(this);
2173                int retCode = -1;
2174                synchronized (mInstallLock) {
2175                    retCode = mInstaller.freeCache(freeStorageSize);
2176                    if (retCode < 0) {
2177                        Slog.w(TAG, "Couldn't clear application caches");
2178                    }
2179                }
2180                if (observer != null) {
2181                    try {
2182                        observer.onRemoveCompleted(null, (retCode >= 0));
2183                    } catch (RemoteException e) {
2184                        Slog.w(TAG, "RemoveException when invoking call back");
2185                    }
2186                }
2187            }
2188        });
2189    }
2190
2191    @Override
2192    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2193        mContext.enforceCallingOrSelfPermission(
2194                android.Manifest.permission.CLEAR_APP_CACHE, null);
2195        // Queue up an async operation since clearing cache may take a little while.
2196        mHandler.post(new Runnable() {
2197            public void run() {
2198                mHandler.removeCallbacks(this);
2199                int retCode = -1;
2200                synchronized (mInstallLock) {
2201                    retCode = mInstaller.freeCache(freeStorageSize);
2202                    if (retCode < 0) {
2203                        Slog.w(TAG, "Couldn't clear application caches");
2204                    }
2205                }
2206                if(pi != null) {
2207                    try {
2208                        // Callback via pending intent
2209                        int code = (retCode >= 0) ? 1 : 0;
2210                        pi.sendIntent(null, code, null,
2211                                null, null);
2212                    } catch (SendIntentException e1) {
2213                        Slog.i(TAG, "Failed to send pending intent");
2214                    }
2215                }
2216            }
2217        });
2218    }
2219
2220    void freeStorage(long freeStorageSize) throws IOException {
2221        synchronized (mInstallLock) {
2222            if (mInstaller.freeCache(freeStorageSize) < 0) {
2223                throw new IOException("Failed to free enough space");
2224            }
2225        }
2226    }
2227
2228    @Override
2229    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2230        if (!sUserManager.exists(userId)) return null;
2231        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2232        synchronized (mPackages) {
2233            PackageParser.Activity a = mActivities.mActivities.get(component);
2234
2235            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2236            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2237                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2238                if (ps == null) return null;
2239                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2240                        userId);
2241            }
2242            if (mResolveComponentName.equals(component)) {
2243                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2244                        new PackageUserState(), userId);
2245            }
2246        }
2247        return null;
2248    }
2249
2250    @Override
2251    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2252            String resolvedType) {
2253        synchronized (mPackages) {
2254            PackageParser.Activity a = mActivities.mActivities.get(component);
2255            if (a == null) {
2256                return false;
2257            }
2258            for (int i=0; i<a.intents.size(); i++) {
2259                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2260                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2261                    return true;
2262                }
2263            }
2264            return false;
2265        }
2266    }
2267
2268    @Override
2269    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2270        if (!sUserManager.exists(userId)) return null;
2271        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2272        synchronized (mPackages) {
2273            PackageParser.Activity a = mReceivers.mActivities.get(component);
2274            if (DEBUG_PACKAGE_INFO) Log.v(
2275                TAG, "getReceiverInfo " + component + ": " + a);
2276            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2277                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2278                if (ps == null) return null;
2279                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2280                        userId);
2281            }
2282        }
2283        return null;
2284    }
2285
2286    @Override
2287    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2288        if (!sUserManager.exists(userId)) return null;
2289        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2290        synchronized (mPackages) {
2291            PackageParser.Service s = mServices.mServices.get(component);
2292            if (DEBUG_PACKAGE_INFO) Log.v(
2293                TAG, "getServiceInfo " + component + ": " + s);
2294            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2295                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2296                if (ps == null) return null;
2297                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2298                        userId);
2299            }
2300        }
2301        return null;
2302    }
2303
2304    @Override
2305    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2306        if (!sUserManager.exists(userId)) return null;
2307        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2308        synchronized (mPackages) {
2309            PackageParser.Provider p = mProviders.mProviders.get(component);
2310            if (DEBUG_PACKAGE_INFO) Log.v(
2311                TAG, "getProviderInfo " + component + ": " + p);
2312            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2313                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2314                if (ps == null) return null;
2315                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2316                        userId);
2317            }
2318        }
2319        return null;
2320    }
2321
2322    @Override
2323    public String[] getSystemSharedLibraryNames() {
2324        Set<String> libSet;
2325        synchronized (mPackages) {
2326            libSet = mSharedLibraries.keySet();
2327            int size = libSet.size();
2328            if (size > 0) {
2329                String[] libs = new String[size];
2330                libSet.toArray(libs);
2331                return libs;
2332            }
2333        }
2334        return null;
2335    }
2336
2337    @Override
2338    public FeatureInfo[] getSystemAvailableFeatures() {
2339        Collection<FeatureInfo> featSet;
2340        synchronized (mPackages) {
2341            featSet = mAvailableFeatures.values();
2342            int size = featSet.size();
2343            if (size > 0) {
2344                FeatureInfo[] features = new FeatureInfo[size+1];
2345                featSet.toArray(features);
2346                FeatureInfo fi = new FeatureInfo();
2347                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2348                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2349                features[size] = fi;
2350                return features;
2351            }
2352        }
2353        return null;
2354    }
2355
2356    @Override
2357    public boolean hasSystemFeature(String name) {
2358        synchronized (mPackages) {
2359            return mAvailableFeatures.containsKey(name);
2360        }
2361    }
2362
2363    private void checkValidCaller(int uid, int userId) {
2364        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2365            return;
2366
2367        throw new SecurityException("Caller uid=" + uid
2368                + " is not privileged to communicate with user=" + userId);
2369    }
2370
2371    @Override
2372    public int checkPermission(String permName, String pkgName) {
2373        synchronized (mPackages) {
2374            PackageParser.Package p = mPackages.get(pkgName);
2375            if (p != null && p.mExtras != null) {
2376                PackageSetting ps = (PackageSetting)p.mExtras;
2377                if (ps.sharedUser != null) {
2378                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2379                        return PackageManager.PERMISSION_GRANTED;
2380                    }
2381                } else if (ps.grantedPermissions.contains(permName)) {
2382                    return PackageManager.PERMISSION_GRANTED;
2383                }
2384            }
2385        }
2386        return PackageManager.PERMISSION_DENIED;
2387    }
2388
2389    @Override
2390    public int checkUidPermission(String permName, int uid) {
2391        synchronized (mPackages) {
2392            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2393            if (obj != null) {
2394                GrantedPermissions gp = (GrantedPermissions)obj;
2395                if (gp.grantedPermissions.contains(permName)) {
2396                    return PackageManager.PERMISSION_GRANTED;
2397                }
2398            } else {
2399                ArraySet<String> perms = mSystemPermissions.get(uid);
2400                if (perms != null && perms.contains(permName)) {
2401                    return PackageManager.PERMISSION_GRANTED;
2402                }
2403            }
2404        }
2405        return PackageManager.PERMISSION_DENIED;
2406    }
2407
2408    /**
2409     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2410     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2411     * @param checkShell TODO(yamasani):
2412     * @param message the message to log on security exception
2413     */
2414    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2415            boolean checkShell, String message) {
2416        if (userId < 0) {
2417            throw new IllegalArgumentException("Invalid userId " + userId);
2418        }
2419        if (checkShell) {
2420            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2421        }
2422        if (userId == UserHandle.getUserId(callingUid)) return;
2423        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2424            if (requireFullPermission) {
2425                mContext.enforceCallingOrSelfPermission(
2426                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2427            } else {
2428                try {
2429                    mContext.enforceCallingOrSelfPermission(
2430                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2431                } catch (SecurityException se) {
2432                    mContext.enforceCallingOrSelfPermission(
2433                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2434                }
2435            }
2436        }
2437    }
2438
2439    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2440        if (callingUid == Process.SHELL_UID) {
2441            if (userHandle >= 0
2442                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2443                throw new SecurityException("Shell does not have permission to access user "
2444                        + userHandle);
2445            } else if (userHandle < 0) {
2446                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2447                        + Debug.getCallers(3));
2448            }
2449        }
2450    }
2451
2452    private BasePermission findPermissionTreeLP(String permName) {
2453        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2454            if (permName.startsWith(bp.name) &&
2455                    permName.length() > bp.name.length() &&
2456                    permName.charAt(bp.name.length()) == '.') {
2457                return bp;
2458            }
2459        }
2460        return null;
2461    }
2462
2463    private BasePermission checkPermissionTreeLP(String permName) {
2464        if (permName != null) {
2465            BasePermission bp = findPermissionTreeLP(permName);
2466            if (bp != null) {
2467                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2468                    return bp;
2469                }
2470                throw new SecurityException("Calling uid "
2471                        + Binder.getCallingUid()
2472                        + " is not allowed to add to permission tree "
2473                        + bp.name + " owned by uid " + bp.uid);
2474            }
2475        }
2476        throw new SecurityException("No permission tree found for " + permName);
2477    }
2478
2479    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2480        if (s1 == null) {
2481            return s2 == null;
2482        }
2483        if (s2 == null) {
2484            return false;
2485        }
2486        if (s1.getClass() != s2.getClass()) {
2487            return false;
2488        }
2489        return s1.equals(s2);
2490    }
2491
2492    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2493        if (pi1.icon != pi2.icon) return false;
2494        if (pi1.logo != pi2.logo) return false;
2495        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2496        if (!compareStrings(pi1.name, pi2.name)) return false;
2497        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2498        // We'll take care of setting this one.
2499        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2500        // These are not currently stored in settings.
2501        //if (!compareStrings(pi1.group, pi2.group)) return false;
2502        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2503        //if (pi1.labelRes != pi2.labelRes) return false;
2504        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2505        return true;
2506    }
2507
2508    int permissionInfoFootprint(PermissionInfo info) {
2509        int size = info.name.length();
2510        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2511        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2512        return size;
2513    }
2514
2515    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2516        int size = 0;
2517        for (BasePermission perm : mSettings.mPermissions.values()) {
2518            if (perm.uid == tree.uid) {
2519                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2520            }
2521        }
2522        return size;
2523    }
2524
2525    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2526        // We calculate the max size of permissions defined by this uid and throw
2527        // if that plus the size of 'info' would exceed our stated maximum.
2528        if (tree.uid != Process.SYSTEM_UID) {
2529            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2530            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2531                throw new SecurityException("Permission tree size cap exceeded");
2532            }
2533        }
2534    }
2535
2536    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2537        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2538            throw new SecurityException("Label must be specified in permission");
2539        }
2540        BasePermission tree = checkPermissionTreeLP(info.name);
2541        BasePermission bp = mSettings.mPermissions.get(info.name);
2542        boolean added = bp == null;
2543        boolean changed = true;
2544        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2545        if (added) {
2546            enforcePermissionCapLocked(info, tree);
2547            bp = new BasePermission(info.name, tree.sourcePackage,
2548                    BasePermission.TYPE_DYNAMIC);
2549        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2550            throw new SecurityException(
2551                    "Not allowed to modify non-dynamic permission "
2552                    + info.name);
2553        } else {
2554            if (bp.protectionLevel == fixedLevel
2555                    && bp.perm.owner.equals(tree.perm.owner)
2556                    && bp.uid == tree.uid
2557                    && comparePermissionInfos(bp.perm.info, info)) {
2558                changed = false;
2559            }
2560        }
2561        bp.protectionLevel = fixedLevel;
2562        info = new PermissionInfo(info);
2563        info.protectionLevel = fixedLevel;
2564        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2565        bp.perm.info.packageName = tree.perm.info.packageName;
2566        bp.uid = tree.uid;
2567        if (added) {
2568            mSettings.mPermissions.put(info.name, bp);
2569        }
2570        if (changed) {
2571            if (!async) {
2572                mSettings.writeLPr();
2573            } else {
2574                scheduleWriteSettingsLocked();
2575            }
2576        }
2577        return added;
2578    }
2579
2580    @Override
2581    public boolean addPermission(PermissionInfo info) {
2582        synchronized (mPackages) {
2583            return addPermissionLocked(info, false);
2584        }
2585    }
2586
2587    @Override
2588    public boolean addPermissionAsync(PermissionInfo info) {
2589        synchronized (mPackages) {
2590            return addPermissionLocked(info, true);
2591        }
2592    }
2593
2594    @Override
2595    public void removePermission(String name) {
2596        synchronized (mPackages) {
2597            checkPermissionTreeLP(name);
2598            BasePermission bp = mSettings.mPermissions.get(name);
2599            if (bp != null) {
2600                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2601                    throw new SecurityException(
2602                            "Not allowed to modify non-dynamic permission "
2603                            + name);
2604                }
2605                mSettings.mPermissions.remove(name);
2606                mSettings.writeLPr();
2607            }
2608        }
2609    }
2610
2611    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2612        int index = pkg.requestedPermissions.indexOf(bp.name);
2613        if (index == -1) {
2614            throw new SecurityException("Package " + pkg.packageName
2615                    + " has not requested permission " + bp.name);
2616        }
2617        boolean isNormal =
2618                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2619                        == PermissionInfo.PROTECTION_NORMAL);
2620        boolean isDangerous =
2621                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2622                        == PermissionInfo.PROTECTION_DANGEROUS);
2623        boolean isDevelopment =
2624                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2625
2626        if (!isNormal && !isDangerous && !isDevelopment) {
2627            throw new SecurityException("Permission " + bp.name
2628                    + " is not a changeable permission type");
2629        }
2630
2631        if (isNormal || isDangerous) {
2632            if (pkg.requestedPermissionsRequired.get(index)) {
2633                throw new SecurityException("Can't change " + bp.name
2634                        + ". It is required by the application");
2635            }
2636        }
2637    }
2638
2639    @Override
2640    public void grantPermission(String packageName, String permissionName) {
2641        mContext.enforceCallingOrSelfPermission(
2642                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2643        synchronized (mPackages) {
2644            final PackageParser.Package pkg = mPackages.get(packageName);
2645            if (pkg == null) {
2646                throw new IllegalArgumentException("Unknown package: " + packageName);
2647            }
2648            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2649            if (bp == null) {
2650                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2651            }
2652
2653            checkGrantRevokePermissions(pkg, bp);
2654
2655            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2656            if (ps == null) {
2657                return;
2658            }
2659            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2660            if (gp.grantedPermissions.add(permissionName)) {
2661                if (ps.haveGids) {
2662                    gp.gids = appendInts(gp.gids, bp.gids);
2663                }
2664                mSettings.writeLPr();
2665            }
2666        }
2667    }
2668
2669    @Override
2670    public void revokePermission(String packageName, String permissionName) {
2671        int changedAppId = -1;
2672
2673        synchronized (mPackages) {
2674            final PackageParser.Package pkg = mPackages.get(packageName);
2675            if (pkg == null) {
2676                throw new IllegalArgumentException("Unknown package: " + packageName);
2677            }
2678            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2679                mContext.enforceCallingOrSelfPermission(
2680                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2681            }
2682            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2683            if (bp == null) {
2684                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2685            }
2686
2687            checkGrantRevokePermissions(pkg, bp);
2688
2689            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2690            if (ps == null) {
2691                return;
2692            }
2693            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2694            if (gp.grantedPermissions.remove(permissionName)) {
2695                gp.grantedPermissions.remove(permissionName);
2696                if (ps.haveGids) {
2697                    gp.gids = removeInts(gp.gids, bp.gids);
2698                }
2699                mSettings.writeLPr();
2700                changedAppId = ps.appId;
2701            }
2702        }
2703
2704        if (changedAppId >= 0) {
2705            // We changed the perm on someone, kill its processes.
2706            IActivityManager am = ActivityManagerNative.getDefault();
2707            if (am != null) {
2708                final int callingUserId = UserHandle.getCallingUserId();
2709                final long ident = Binder.clearCallingIdentity();
2710                try {
2711                    //XXX we should only revoke for the calling user's app permissions,
2712                    // but for now we impact all users.
2713                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2714                    //        "revoke " + permissionName);
2715                    int[] users = sUserManager.getUserIds();
2716                    for (int user : users) {
2717                        am.killUid(UserHandle.getUid(user, changedAppId),
2718                                "revoke " + permissionName);
2719                    }
2720                } catch (RemoteException e) {
2721                } finally {
2722                    Binder.restoreCallingIdentity(ident);
2723                }
2724            }
2725        }
2726    }
2727
2728    @Override
2729    public boolean isProtectedBroadcast(String actionName) {
2730        synchronized (mPackages) {
2731            return mProtectedBroadcasts.contains(actionName);
2732        }
2733    }
2734
2735    @Override
2736    public int checkSignatures(String pkg1, String pkg2) {
2737        synchronized (mPackages) {
2738            final PackageParser.Package p1 = mPackages.get(pkg1);
2739            final PackageParser.Package p2 = mPackages.get(pkg2);
2740            if (p1 == null || p1.mExtras == null
2741                    || p2 == null || p2.mExtras == null) {
2742                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2743            }
2744            return compareSignatures(p1.mSignatures, p2.mSignatures);
2745        }
2746    }
2747
2748    @Override
2749    public int checkUidSignatures(int uid1, int uid2) {
2750        // Map to base uids.
2751        uid1 = UserHandle.getAppId(uid1);
2752        uid2 = UserHandle.getAppId(uid2);
2753        // reader
2754        synchronized (mPackages) {
2755            Signature[] s1;
2756            Signature[] s2;
2757            Object obj = mSettings.getUserIdLPr(uid1);
2758            if (obj != null) {
2759                if (obj instanceof SharedUserSetting) {
2760                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2761                } else if (obj instanceof PackageSetting) {
2762                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2763                } else {
2764                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2765                }
2766            } else {
2767                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2768            }
2769            obj = mSettings.getUserIdLPr(uid2);
2770            if (obj != null) {
2771                if (obj instanceof SharedUserSetting) {
2772                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2773                } else if (obj instanceof PackageSetting) {
2774                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2775                } else {
2776                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2777                }
2778            } else {
2779                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2780            }
2781            return compareSignatures(s1, s2);
2782        }
2783    }
2784
2785    /**
2786     * Compares two sets of signatures. Returns:
2787     * <br />
2788     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2789     * <br />
2790     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2791     * <br />
2792     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2793     * <br />
2794     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2795     * <br />
2796     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2797     */
2798    static int compareSignatures(Signature[] s1, Signature[] s2) {
2799        if (s1 == null) {
2800            return s2 == null
2801                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2802                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2803        }
2804
2805        if (s2 == null) {
2806            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2807        }
2808
2809        if (s1.length != s2.length) {
2810            return PackageManager.SIGNATURE_NO_MATCH;
2811        }
2812
2813        // Since both signature sets are of size 1, we can compare without HashSets.
2814        if (s1.length == 1) {
2815            return s1[0].equals(s2[0]) ?
2816                    PackageManager.SIGNATURE_MATCH :
2817                    PackageManager.SIGNATURE_NO_MATCH;
2818        }
2819
2820        ArraySet<Signature> set1 = new ArraySet<Signature>();
2821        for (Signature sig : s1) {
2822            set1.add(sig);
2823        }
2824        ArraySet<Signature> set2 = new ArraySet<Signature>();
2825        for (Signature sig : s2) {
2826            set2.add(sig);
2827        }
2828        // Make sure s2 contains all signatures in s1.
2829        if (set1.equals(set2)) {
2830            return PackageManager.SIGNATURE_MATCH;
2831        }
2832        return PackageManager.SIGNATURE_NO_MATCH;
2833    }
2834
2835    /**
2836     * If the database version for this type of package (internal storage or
2837     * external storage) is less than the version where package signatures
2838     * were updated, return true.
2839     */
2840    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2841        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2842                DatabaseVersion.SIGNATURE_END_ENTITY))
2843                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2844                        DatabaseVersion.SIGNATURE_END_ENTITY));
2845    }
2846
2847    /**
2848     * Used for backward compatibility to make sure any packages with
2849     * certificate chains get upgraded to the new style. {@code existingSigs}
2850     * will be in the old format (since they were stored on disk from before the
2851     * system upgrade) and {@code scannedSigs} will be in the newer format.
2852     */
2853    private int compareSignaturesCompat(PackageSignatures existingSigs,
2854            PackageParser.Package scannedPkg) {
2855        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2856            return PackageManager.SIGNATURE_NO_MATCH;
2857        }
2858
2859        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2860        for (Signature sig : existingSigs.mSignatures) {
2861            existingSet.add(sig);
2862        }
2863        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2864        for (Signature sig : scannedPkg.mSignatures) {
2865            try {
2866                Signature[] chainSignatures = sig.getChainSignatures();
2867                for (Signature chainSig : chainSignatures) {
2868                    scannedCompatSet.add(chainSig);
2869                }
2870            } catch (CertificateEncodingException e) {
2871                scannedCompatSet.add(sig);
2872            }
2873        }
2874        /*
2875         * Make sure the expanded scanned set contains all signatures in the
2876         * existing one.
2877         */
2878        if (scannedCompatSet.equals(existingSet)) {
2879            // Migrate the old signatures to the new scheme.
2880            existingSigs.assignSignatures(scannedPkg.mSignatures);
2881            // The new KeySets will be re-added later in the scanning process.
2882            synchronized (mPackages) {
2883                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2884            }
2885            return PackageManager.SIGNATURE_MATCH;
2886        }
2887        return PackageManager.SIGNATURE_NO_MATCH;
2888    }
2889
2890    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2891        if (isExternal(scannedPkg)) {
2892            return mSettings.isExternalDatabaseVersionOlderThan(
2893                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2894        } else {
2895            return mSettings.isInternalDatabaseVersionOlderThan(
2896                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2897        }
2898    }
2899
2900    private int compareSignaturesRecover(PackageSignatures existingSigs,
2901            PackageParser.Package scannedPkg) {
2902        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
2903            return PackageManager.SIGNATURE_NO_MATCH;
2904        }
2905
2906        String msg = null;
2907        try {
2908            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
2909                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
2910                        + scannedPkg.packageName);
2911                return PackageManager.SIGNATURE_MATCH;
2912            }
2913        } catch (CertificateException e) {
2914            msg = e.getMessage();
2915        }
2916
2917        logCriticalInfo(Log.INFO,
2918                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
2919        return PackageManager.SIGNATURE_NO_MATCH;
2920    }
2921
2922    @Override
2923    public String[] getPackagesForUid(int uid) {
2924        uid = UserHandle.getAppId(uid);
2925        // reader
2926        synchronized (mPackages) {
2927            Object obj = mSettings.getUserIdLPr(uid);
2928            if (obj instanceof SharedUserSetting) {
2929                final SharedUserSetting sus = (SharedUserSetting) obj;
2930                final int N = sus.packages.size();
2931                final String[] res = new String[N];
2932                final Iterator<PackageSetting> it = sus.packages.iterator();
2933                int i = 0;
2934                while (it.hasNext()) {
2935                    res[i++] = it.next().name;
2936                }
2937                return res;
2938            } else if (obj instanceof PackageSetting) {
2939                final PackageSetting ps = (PackageSetting) obj;
2940                return new String[] { ps.name };
2941            }
2942        }
2943        return null;
2944    }
2945
2946    @Override
2947    public String getNameForUid(int uid) {
2948        // reader
2949        synchronized (mPackages) {
2950            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2951            if (obj instanceof SharedUserSetting) {
2952                final SharedUserSetting sus = (SharedUserSetting) obj;
2953                return sus.name + ":" + sus.userId;
2954            } else if (obj instanceof PackageSetting) {
2955                final PackageSetting ps = (PackageSetting) obj;
2956                return ps.name;
2957            }
2958        }
2959        return null;
2960    }
2961
2962    @Override
2963    public int getUidForSharedUser(String sharedUserName) {
2964        if(sharedUserName == null) {
2965            return -1;
2966        }
2967        // reader
2968        synchronized (mPackages) {
2969            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2970            if (suid == null) {
2971                return -1;
2972            }
2973            return suid.userId;
2974        }
2975    }
2976
2977    @Override
2978    public int getFlagsForUid(int uid) {
2979        synchronized (mPackages) {
2980            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2981            if (obj instanceof SharedUserSetting) {
2982                final SharedUserSetting sus = (SharedUserSetting) obj;
2983                return sus.pkgFlags;
2984            } else if (obj instanceof PackageSetting) {
2985                final PackageSetting ps = (PackageSetting) obj;
2986                return ps.pkgFlags;
2987            }
2988        }
2989        return 0;
2990    }
2991
2992    @Override
2993    public boolean isUidPrivileged(int uid) {
2994        uid = UserHandle.getAppId(uid);
2995        // reader
2996        synchronized (mPackages) {
2997            Object obj = mSettings.getUserIdLPr(uid);
2998            if (obj instanceof SharedUserSetting) {
2999                final SharedUserSetting sus = (SharedUserSetting) obj;
3000                final Iterator<PackageSetting> it = sus.packages.iterator();
3001                while (it.hasNext()) {
3002                    if (it.next().isPrivileged()) {
3003                        return true;
3004                    }
3005                }
3006            } else if (obj instanceof PackageSetting) {
3007                final PackageSetting ps = (PackageSetting) obj;
3008                return ps.isPrivileged();
3009            }
3010        }
3011        return false;
3012    }
3013
3014    @Override
3015    public String[] getAppOpPermissionPackages(String permissionName) {
3016        synchronized (mPackages) {
3017            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3018            if (pkgs == null) {
3019                return null;
3020            }
3021            return pkgs.toArray(new String[pkgs.size()]);
3022        }
3023    }
3024
3025    @Override
3026    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3027            int flags, int userId) {
3028        if (!sUserManager.exists(userId)) return null;
3029        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3030        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3031        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3032    }
3033
3034    @Override
3035    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3036            IntentFilter filter, int match, ComponentName activity) {
3037        final int userId = UserHandle.getCallingUserId();
3038        if (DEBUG_PREFERRED) {
3039            Log.v(TAG, "setLastChosenActivity intent=" + intent
3040                + " resolvedType=" + resolvedType
3041                + " flags=" + flags
3042                + " filter=" + filter
3043                + " match=" + match
3044                + " activity=" + activity);
3045            filter.dump(new PrintStreamPrinter(System.out), "    ");
3046        }
3047        intent.setComponent(null);
3048        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3049        // Find any earlier preferred or last chosen entries and nuke them
3050        findPreferredActivity(intent, resolvedType,
3051                flags, query, 0, false, true, false, userId);
3052        // Add the new activity as the last chosen for this filter
3053        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3054                "Setting last chosen");
3055    }
3056
3057    @Override
3058    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3059        final int userId = UserHandle.getCallingUserId();
3060        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3061        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3062        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3063                false, false, false, userId);
3064    }
3065
3066    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3067            int flags, List<ResolveInfo> query, int userId) {
3068        if (query != null) {
3069            final int N = query.size();
3070            if (N == 1) {
3071                return query.get(0);
3072            } else if (N > 1) {
3073                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3074                // If there is more than one activity with the same priority,
3075                // then let the user decide between them.
3076                ResolveInfo r0 = query.get(0);
3077                ResolveInfo r1 = query.get(1);
3078                if (DEBUG_INTENT_MATCHING || debug) {
3079                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3080                            + r1.activityInfo.name + "=" + r1.priority);
3081                }
3082                // If the first activity has a higher priority, or a different
3083                // default, then it is always desireable to pick it.
3084                if (r0.priority != r1.priority
3085                        || r0.preferredOrder != r1.preferredOrder
3086                        || r0.isDefault != r1.isDefault) {
3087                    return query.get(0);
3088                }
3089                // If we have saved a preference for a preferred activity for
3090                // this Intent, use that.
3091                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3092                        flags, query, r0.priority, true, false, debug, userId);
3093                if (ri != null) {
3094                    return ri;
3095                }
3096                if (userId != 0) {
3097                    ri = new ResolveInfo(mResolveInfo);
3098                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3099                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3100                            ri.activityInfo.applicationInfo);
3101                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3102                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3103                    return ri;
3104                }
3105                return mResolveInfo;
3106            }
3107        }
3108        return null;
3109    }
3110
3111    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3112            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3113        final int N = query.size();
3114        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3115                .get(userId);
3116        // Get the list of persistent preferred activities that handle the intent
3117        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3118        List<PersistentPreferredActivity> pprefs = ppir != null
3119                ? ppir.queryIntent(intent, resolvedType,
3120                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3121                : null;
3122        if (pprefs != null && pprefs.size() > 0) {
3123            final int M = pprefs.size();
3124            for (int i=0; i<M; i++) {
3125                final PersistentPreferredActivity ppa = pprefs.get(i);
3126                if (DEBUG_PREFERRED || debug) {
3127                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3128                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3129                            + "\n  component=" + ppa.mComponent);
3130                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3131                }
3132                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3133                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3134                if (DEBUG_PREFERRED || debug) {
3135                    Slog.v(TAG, "Found persistent preferred activity:");
3136                    if (ai != null) {
3137                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3138                    } else {
3139                        Slog.v(TAG, "  null");
3140                    }
3141                }
3142                if (ai == null) {
3143                    // This previously registered persistent preferred activity
3144                    // component is no longer known. Ignore it and do NOT remove it.
3145                    continue;
3146                }
3147                for (int j=0; j<N; j++) {
3148                    final ResolveInfo ri = query.get(j);
3149                    if (!ri.activityInfo.applicationInfo.packageName
3150                            .equals(ai.applicationInfo.packageName)) {
3151                        continue;
3152                    }
3153                    if (!ri.activityInfo.name.equals(ai.name)) {
3154                        continue;
3155                    }
3156                    //  Found a persistent preference that can handle the intent.
3157                    if (DEBUG_PREFERRED || debug) {
3158                        Slog.v(TAG, "Returning persistent preferred activity: " +
3159                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3160                    }
3161                    return ri;
3162                }
3163            }
3164        }
3165        return null;
3166    }
3167
3168    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3169            List<ResolveInfo> query, int priority, boolean always,
3170            boolean removeMatches, boolean debug, int userId) {
3171        if (!sUserManager.exists(userId)) return null;
3172        // writer
3173        synchronized (mPackages) {
3174            if (intent.getSelector() != null) {
3175                intent = intent.getSelector();
3176            }
3177            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3178
3179            // Try to find a matching persistent preferred activity.
3180            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3181                    debug, userId);
3182
3183            // If a persistent preferred activity matched, use it.
3184            if (pri != null) {
3185                return pri;
3186            }
3187
3188            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3189            // Get the list of preferred activities that handle the intent
3190            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3191            List<PreferredActivity> prefs = pir != null
3192                    ? pir.queryIntent(intent, resolvedType,
3193                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3194                    : null;
3195            if (prefs != null && prefs.size() > 0) {
3196                boolean changed = false;
3197                try {
3198                    // First figure out how good the original match set is.
3199                    // We will only allow preferred activities that came
3200                    // from the same match quality.
3201                    int match = 0;
3202
3203                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3204
3205                    final int N = query.size();
3206                    for (int j=0; j<N; j++) {
3207                        final ResolveInfo ri = query.get(j);
3208                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3209                                + ": 0x" + Integer.toHexString(match));
3210                        if (ri.match > match) {
3211                            match = ri.match;
3212                        }
3213                    }
3214
3215                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3216                            + Integer.toHexString(match));
3217
3218                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3219                    final int M = prefs.size();
3220                    for (int i=0; i<M; i++) {
3221                        final PreferredActivity pa = prefs.get(i);
3222                        if (DEBUG_PREFERRED || debug) {
3223                            Slog.v(TAG, "Checking PreferredActivity ds="
3224                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3225                                    + "\n  component=" + pa.mPref.mComponent);
3226                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3227                        }
3228                        if (pa.mPref.mMatch != match) {
3229                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3230                                    + Integer.toHexString(pa.mPref.mMatch));
3231                            continue;
3232                        }
3233                        // If it's not an "always" type preferred activity and that's what we're
3234                        // looking for, skip it.
3235                        if (always && !pa.mPref.mAlways) {
3236                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3237                            continue;
3238                        }
3239                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3240                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3241                        if (DEBUG_PREFERRED || debug) {
3242                            Slog.v(TAG, "Found preferred activity:");
3243                            if (ai != null) {
3244                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3245                            } else {
3246                                Slog.v(TAG, "  null");
3247                            }
3248                        }
3249                        if (ai == null) {
3250                            // This previously registered preferred activity
3251                            // component is no longer known.  Most likely an update
3252                            // to the app was installed and in the new version this
3253                            // component no longer exists.  Clean it up by removing
3254                            // it from the preferred activities list, and skip it.
3255                            Slog.w(TAG, "Removing dangling preferred activity: "
3256                                    + pa.mPref.mComponent);
3257                            pir.removeFilter(pa);
3258                            changed = true;
3259                            continue;
3260                        }
3261                        for (int j=0; j<N; j++) {
3262                            final ResolveInfo ri = query.get(j);
3263                            if (!ri.activityInfo.applicationInfo.packageName
3264                                    .equals(ai.applicationInfo.packageName)) {
3265                                continue;
3266                            }
3267                            if (!ri.activityInfo.name.equals(ai.name)) {
3268                                continue;
3269                            }
3270
3271                            if (removeMatches) {
3272                                pir.removeFilter(pa);
3273                                changed = true;
3274                                if (DEBUG_PREFERRED) {
3275                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3276                                }
3277                                break;
3278                            }
3279
3280                            // Okay we found a previously set preferred or last chosen app.
3281                            // If the result set is different from when this
3282                            // was created, we need to clear it and re-ask the
3283                            // user their preference, if we're looking for an "always" type entry.
3284                            if (always && !pa.mPref.sameSet(query, priority)) {
3285                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3286                                        + intent + " type " + resolvedType);
3287                                if (DEBUG_PREFERRED) {
3288                                    Slog.v(TAG, "Removing preferred activity since set changed "
3289                                            + pa.mPref.mComponent);
3290                                }
3291                                pir.removeFilter(pa);
3292                                // Re-add the filter as a "last chosen" entry (!always)
3293                                PreferredActivity lastChosen = new PreferredActivity(
3294                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3295                                pir.addFilter(lastChosen);
3296                                changed = true;
3297                                return null;
3298                            }
3299
3300                            // Yay! Either the set matched or we're looking for the last chosen
3301                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3302                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3303                            return ri;
3304                        }
3305                    }
3306                } finally {
3307                    if (changed) {
3308                        if (DEBUG_PREFERRED) {
3309                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3310                        }
3311                        scheduleWritePackageRestrictionsLocked(userId);
3312                    }
3313                }
3314            }
3315        }
3316        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3317        return null;
3318    }
3319
3320    /*
3321     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3322     */
3323    @Override
3324    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3325            int targetUserId) {
3326        mContext.enforceCallingOrSelfPermission(
3327                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3328        List<CrossProfileIntentFilter> matches =
3329                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3330        if (matches != null) {
3331            int size = matches.size();
3332            for (int i = 0; i < size; i++) {
3333                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3334            }
3335        }
3336        return false;
3337    }
3338
3339    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3340            String resolvedType, int userId) {
3341        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3342        if (resolver != null) {
3343            return resolver.queryIntent(intent, resolvedType, false, userId);
3344        }
3345        return null;
3346    }
3347
3348    @Override
3349    public List<ResolveInfo> queryIntentActivities(Intent intent,
3350            String resolvedType, int flags, int userId) {
3351        if (!sUserManager.exists(userId)) return Collections.emptyList();
3352        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3353        ComponentName comp = intent.getComponent();
3354        if (comp == null) {
3355            if (intent.getSelector() != null) {
3356                intent = intent.getSelector();
3357                comp = intent.getComponent();
3358            }
3359        }
3360
3361        if (comp != null) {
3362            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3363            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3364            if (ai != null) {
3365                final ResolveInfo ri = new ResolveInfo();
3366                ri.activityInfo = ai;
3367                list.add(ri);
3368            }
3369            return list;
3370        }
3371
3372        // reader
3373        synchronized (mPackages) {
3374            final String pkgName = intent.getPackage();
3375            if (pkgName == null) {
3376                List<CrossProfileIntentFilter> matchingFilters =
3377                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3378                // Check for results that need to skip the current profile.
3379                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3380                        resolvedType, flags, userId);
3381                if (resolveInfo != null) {
3382                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3383                    result.add(resolveInfo);
3384                    return result;
3385                }
3386                // Check for cross profile results.
3387                resolveInfo = queryCrossProfileIntents(
3388                        matchingFilters, intent, resolvedType, flags, userId);
3389
3390                // Check for results in the current profile.
3391                List<ResolveInfo> result = mActivities.queryIntent(
3392                        intent, resolvedType, flags, userId);
3393                if (resolveInfo != null) {
3394                    result.add(resolveInfo);
3395                    Collections.sort(result, mResolvePrioritySorter);
3396                }
3397                return result;
3398            }
3399            final PackageParser.Package pkg = mPackages.get(pkgName);
3400            if (pkg != null) {
3401                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3402                        pkg.activities, userId);
3403            }
3404            return new ArrayList<ResolveInfo>();
3405        }
3406    }
3407
3408    private ResolveInfo querySkipCurrentProfileIntents(
3409            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3410            int flags, int sourceUserId) {
3411        if (matchingFilters != null) {
3412            int size = matchingFilters.size();
3413            for (int i = 0; i < size; i ++) {
3414                CrossProfileIntentFilter filter = matchingFilters.get(i);
3415                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3416                    // Checking if there are activities in the target user that can handle the
3417                    // intent.
3418                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3419                            flags, sourceUserId);
3420                    if (resolveInfo != null) {
3421                        return resolveInfo;
3422                    }
3423                }
3424            }
3425        }
3426        return null;
3427    }
3428
3429    // Return matching ResolveInfo if any for skip current profile intent filters.
3430    private ResolveInfo queryCrossProfileIntents(
3431            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3432            int flags, int sourceUserId) {
3433        if (matchingFilters != null) {
3434            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3435            // match the same intent. For performance reasons, it is better not to
3436            // run queryIntent twice for the same userId
3437            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3438            int size = matchingFilters.size();
3439            for (int i = 0; i < size; i++) {
3440                CrossProfileIntentFilter filter = matchingFilters.get(i);
3441                int targetUserId = filter.getTargetUserId();
3442                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3443                        && !alreadyTriedUserIds.get(targetUserId)) {
3444                    // Checking if there are activities in the target user that can handle the
3445                    // intent.
3446                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3447                            flags, sourceUserId);
3448                    if (resolveInfo != null) return resolveInfo;
3449                    alreadyTriedUserIds.put(targetUserId, true);
3450                }
3451            }
3452        }
3453        return null;
3454    }
3455
3456    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3457            String resolvedType, int flags, int sourceUserId) {
3458        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3459                resolvedType, flags, filter.getTargetUserId());
3460        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3461            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3462        }
3463        return null;
3464    }
3465
3466    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3467            int sourceUserId, int targetUserId) {
3468        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3469        String className;
3470        if (targetUserId == UserHandle.USER_OWNER) {
3471            className = FORWARD_INTENT_TO_USER_OWNER;
3472        } else {
3473            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3474        }
3475        ComponentName forwardingActivityComponentName = new ComponentName(
3476                mAndroidApplication.packageName, className);
3477        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3478                sourceUserId);
3479        if (targetUserId == UserHandle.USER_OWNER) {
3480            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3481            forwardingResolveInfo.noResourceId = true;
3482        }
3483        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3484        forwardingResolveInfo.priority = 0;
3485        forwardingResolveInfo.preferredOrder = 0;
3486        forwardingResolveInfo.match = 0;
3487        forwardingResolveInfo.isDefault = true;
3488        forwardingResolveInfo.filter = filter;
3489        forwardingResolveInfo.targetUserId = targetUserId;
3490        return forwardingResolveInfo;
3491    }
3492
3493    @Override
3494    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3495            Intent[] specifics, String[] specificTypes, Intent intent,
3496            String resolvedType, int flags, int userId) {
3497        if (!sUserManager.exists(userId)) return Collections.emptyList();
3498        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3499                false, "query intent activity options");
3500        final String resultsAction = intent.getAction();
3501
3502        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3503                | PackageManager.GET_RESOLVED_FILTER, userId);
3504
3505        if (DEBUG_INTENT_MATCHING) {
3506            Log.v(TAG, "Query " + intent + ": " + results);
3507        }
3508
3509        int specificsPos = 0;
3510        int N;
3511
3512        // todo: note that the algorithm used here is O(N^2).  This
3513        // isn't a problem in our current environment, but if we start running
3514        // into situations where we have more than 5 or 10 matches then this
3515        // should probably be changed to something smarter...
3516
3517        // First we go through and resolve each of the specific items
3518        // that were supplied, taking care of removing any corresponding
3519        // duplicate items in the generic resolve list.
3520        if (specifics != null) {
3521            for (int i=0; i<specifics.length; i++) {
3522                final Intent sintent = specifics[i];
3523                if (sintent == null) {
3524                    continue;
3525                }
3526
3527                if (DEBUG_INTENT_MATCHING) {
3528                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3529                }
3530
3531                String action = sintent.getAction();
3532                if (resultsAction != null && resultsAction.equals(action)) {
3533                    // If this action was explicitly requested, then don't
3534                    // remove things that have it.
3535                    action = null;
3536                }
3537
3538                ResolveInfo ri = null;
3539                ActivityInfo ai = null;
3540
3541                ComponentName comp = sintent.getComponent();
3542                if (comp == null) {
3543                    ri = resolveIntent(
3544                        sintent,
3545                        specificTypes != null ? specificTypes[i] : null,
3546                            flags, userId);
3547                    if (ri == null) {
3548                        continue;
3549                    }
3550                    if (ri == mResolveInfo) {
3551                        // ACK!  Must do something better with this.
3552                    }
3553                    ai = ri.activityInfo;
3554                    comp = new ComponentName(ai.applicationInfo.packageName,
3555                            ai.name);
3556                } else {
3557                    ai = getActivityInfo(comp, flags, userId);
3558                    if (ai == null) {
3559                        continue;
3560                    }
3561                }
3562
3563                // Look for any generic query activities that are duplicates
3564                // of this specific one, and remove them from the results.
3565                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3566                N = results.size();
3567                int j;
3568                for (j=specificsPos; j<N; j++) {
3569                    ResolveInfo sri = results.get(j);
3570                    if ((sri.activityInfo.name.equals(comp.getClassName())
3571                            && sri.activityInfo.applicationInfo.packageName.equals(
3572                                    comp.getPackageName()))
3573                        || (action != null && sri.filter.matchAction(action))) {
3574                        results.remove(j);
3575                        if (DEBUG_INTENT_MATCHING) Log.v(
3576                            TAG, "Removing duplicate item from " + j
3577                            + " due to specific " + specificsPos);
3578                        if (ri == null) {
3579                            ri = sri;
3580                        }
3581                        j--;
3582                        N--;
3583                    }
3584                }
3585
3586                // Add this specific item to its proper place.
3587                if (ri == null) {
3588                    ri = new ResolveInfo();
3589                    ri.activityInfo = ai;
3590                }
3591                results.add(specificsPos, ri);
3592                ri.specificIndex = i;
3593                specificsPos++;
3594            }
3595        }
3596
3597        // Now we go through the remaining generic results and remove any
3598        // duplicate actions that are found here.
3599        N = results.size();
3600        for (int i=specificsPos; i<N-1; i++) {
3601            final ResolveInfo rii = results.get(i);
3602            if (rii.filter == null) {
3603                continue;
3604            }
3605
3606            // Iterate over all of the actions of this result's intent
3607            // filter...  typically this should be just one.
3608            final Iterator<String> it = rii.filter.actionsIterator();
3609            if (it == null) {
3610                continue;
3611            }
3612            while (it.hasNext()) {
3613                final String action = it.next();
3614                if (resultsAction != null && resultsAction.equals(action)) {
3615                    // If this action was explicitly requested, then don't
3616                    // remove things that have it.
3617                    continue;
3618                }
3619                for (int j=i+1; j<N; j++) {
3620                    final ResolveInfo rij = results.get(j);
3621                    if (rij.filter != null && rij.filter.hasAction(action)) {
3622                        results.remove(j);
3623                        if (DEBUG_INTENT_MATCHING) Log.v(
3624                            TAG, "Removing duplicate item from " + j
3625                            + " due to action " + action + " at " + i);
3626                        j--;
3627                        N--;
3628                    }
3629                }
3630            }
3631
3632            // If the caller didn't request filter information, drop it now
3633            // so we don't have to marshall/unmarshall it.
3634            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3635                rii.filter = null;
3636            }
3637        }
3638
3639        // Filter out the caller activity if so requested.
3640        if (caller != null) {
3641            N = results.size();
3642            for (int i=0; i<N; i++) {
3643                ActivityInfo ainfo = results.get(i).activityInfo;
3644                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3645                        && caller.getClassName().equals(ainfo.name)) {
3646                    results.remove(i);
3647                    break;
3648                }
3649            }
3650        }
3651
3652        // If the caller didn't request filter information,
3653        // drop them now so we don't have to
3654        // marshall/unmarshall it.
3655        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3656            N = results.size();
3657            for (int i=0; i<N; i++) {
3658                results.get(i).filter = null;
3659            }
3660        }
3661
3662        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3663        return results;
3664    }
3665
3666    @Override
3667    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3668            int userId) {
3669        if (!sUserManager.exists(userId)) return Collections.emptyList();
3670        ComponentName comp = intent.getComponent();
3671        if (comp == null) {
3672            if (intent.getSelector() != null) {
3673                intent = intent.getSelector();
3674                comp = intent.getComponent();
3675            }
3676        }
3677        if (comp != null) {
3678            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3679            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3680            if (ai != null) {
3681                ResolveInfo ri = new ResolveInfo();
3682                ri.activityInfo = ai;
3683                list.add(ri);
3684            }
3685            return list;
3686        }
3687
3688        // reader
3689        synchronized (mPackages) {
3690            String pkgName = intent.getPackage();
3691            if (pkgName == null) {
3692                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3693            }
3694            final PackageParser.Package pkg = mPackages.get(pkgName);
3695            if (pkg != null) {
3696                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3697                        userId);
3698            }
3699            return null;
3700        }
3701    }
3702
3703    @Override
3704    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3705        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3706        if (!sUserManager.exists(userId)) return null;
3707        if (query != null) {
3708            if (query.size() >= 1) {
3709                // If there is more than one service with the same priority,
3710                // just arbitrarily pick the first one.
3711                return query.get(0);
3712            }
3713        }
3714        return null;
3715    }
3716
3717    @Override
3718    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3719            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 ServiceInfo si = getServiceInfo(comp, flags, userId);
3731            if (si != null) {
3732                final ResolveInfo ri = new ResolveInfo();
3733                ri.serviceInfo = si;
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 mServices.queryIntent(intent, resolvedType, flags, userId);
3744            }
3745            final PackageParser.Package pkg = mPackages.get(pkgName);
3746            if (pkg != null) {
3747                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3748                        userId);
3749            }
3750            return null;
3751        }
3752    }
3753
3754    @Override
3755    public List<ResolveInfo> queryIntentContentProviders(
3756            Intent intent, String resolvedType, int flags, int userId) {
3757        if (!sUserManager.exists(userId)) return Collections.emptyList();
3758        ComponentName comp = intent.getComponent();
3759        if (comp == null) {
3760            if (intent.getSelector() != null) {
3761                intent = intent.getSelector();
3762                comp = intent.getComponent();
3763            }
3764        }
3765        if (comp != null) {
3766            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3767            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3768            if (pi != null) {
3769                final ResolveInfo ri = new ResolveInfo();
3770                ri.providerInfo = pi;
3771                list.add(ri);
3772            }
3773            return list;
3774        }
3775
3776        // reader
3777        synchronized (mPackages) {
3778            String pkgName = intent.getPackage();
3779            if (pkgName == null) {
3780                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3781            }
3782            final PackageParser.Package pkg = mPackages.get(pkgName);
3783            if (pkg != null) {
3784                return mProviders.queryIntentForPackage(
3785                        intent, resolvedType, flags, pkg.providers, userId);
3786            }
3787            return null;
3788        }
3789    }
3790
3791    @Override
3792    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3793        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3794
3795        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3796
3797        // writer
3798        synchronized (mPackages) {
3799            ArrayList<PackageInfo> list;
3800            if (listUninstalled) {
3801                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3802                for (PackageSetting ps : mSettings.mPackages.values()) {
3803                    PackageInfo pi;
3804                    if (ps.pkg != null) {
3805                        pi = generatePackageInfo(ps.pkg, flags, userId);
3806                    } else {
3807                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3808                    }
3809                    if (pi != null) {
3810                        list.add(pi);
3811                    }
3812                }
3813            } else {
3814                list = new ArrayList<PackageInfo>(mPackages.size());
3815                for (PackageParser.Package p : mPackages.values()) {
3816                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3817                    if (pi != null) {
3818                        list.add(pi);
3819                    }
3820                }
3821            }
3822
3823            return new ParceledListSlice<PackageInfo>(list);
3824        }
3825    }
3826
3827    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3828            String[] permissions, boolean[] tmp, int flags, int userId) {
3829        int numMatch = 0;
3830        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3831        for (int i=0; i<permissions.length; i++) {
3832            if (gp.grantedPermissions.contains(permissions[i])) {
3833                tmp[i] = true;
3834                numMatch++;
3835            } else {
3836                tmp[i] = false;
3837            }
3838        }
3839        if (numMatch == 0) {
3840            return;
3841        }
3842        PackageInfo pi;
3843        if (ps.pkg != null) {
3844            pi = generatePackageInfo(ps.pkg, flags, userId);
3845        } else {
3846            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3847        }
3848        // The above might return null in cases of uninstalled apps or install-state
3849        // skew across users/profiles.
3850        if (pi != null) {
3851            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3852                if (numMatch == permissions.length) {
3853                    pi.requestedPermissions = permissions;
3854                } else {
3855                    pi.requestedPermissions = new String[numMatch];
3856                    numMatch = 0;
3857                    for (int i=0; i<permissions.length; i++) {
3858                        if (tmp[i]) {
3859                            pi.requestedPermissions[numMatch] = permissions[i];
3860                            numMatch++;
3861                        }
3862                    }
3863                }
3864            }
3865            list.add(pi);
3866        }
3867    }
3868
3869    @Override
3870    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3871            String[] permissions, int flags, int userId) {
3872        if (!sUserManager.exists(userId)) return null;
3873        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3874
3875        // writer
3876        synchronized (mPackages) {
3877            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3878            boolean[] tmpBools = new boolean[permissions.length];
3879            if (listUninstalled) {
3880                for (PackageSetting ps : mSettings.mPackages.values()) {
3881                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3882                }
3883            } else {
3884                for (PackageParser.Package pkg : mPackages.values()) {
3885                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3886                    if (ps != null) {
3887                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3888                                userId);
3889                    }
3890                }
3891            }
3892
3893            return new ParceledListSlice<PackageInfo>(list);
3894        }
3895    }
3896
3897    @Override
3898    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3899        if (!sUserManager.exists(userId)) return null;
3900        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3901
3902        // writer
3903        synchronized (mPackages) {
3904            ArrayList<ApplicationInfo> list;
3905            if (listUninstalled) {
3906                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3907                for (PackageSetting ps : mSettings.mPackages.values()) {
3908                    ApplicationInfo ai;
3909                    if (ps.pkg != null) {
3910                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3911                                ps.readUserState(userId), userId);
3912                    } else {
3913                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3914                    }
3915                    if (ai != null) {
3916                        list.add(ai);
3917                    }
3918                }
3919            } else {
3920                list = new ArrayList<ApplicationInfo>(mPackages.size());
3921                for (PackageParser.Package p : mPackages.values()) {
3922                    if (p.mExtras != null) {
3923                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3924                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3925                        if (ai != null) {
3926                            list.add(ai);
3927                        }
3928                    }
3929                }
3930            }
3931
3932            return new ParceledListSlice<ApplicationInfo>(list);
3933        }
3934    }
3935
3936    public List<ApplicationInfo> getPersistentApplications(int flags) {
3937        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3938
3939        // reader
3940        synchronized (mPackages) {
3941            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3942            final int userId = UserHandle.getCallingUserId();
3943            while (i.hasNext()) {
3944                final PackageParser.Package p = i.next();
3945                if (p.applicationInfo != null
3946                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3947                        && (!mSafeMode || isSystemApp(p))) {
3948                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3949                    if (ps != null) {
3950                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3951                                ps.readUserState(userId), userId);
3952                        if (ai != null) {
3953                            finalList.add(ai);
3954                        }
3955                    }
3956                }
3957            }
3958        }
3959
3960        return finalList;
3961    }
3962
3963    @Override
3964    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3965        if (!sUserManager.exists(userId)) return null;
3966        // reader
3967        synchronized (mPackages) {
3968            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3969            PackageSetting ps = provider != null
3970                    ? mSettings.mPackages.get(provider.owner.packageName)
3971                    : null;
3972            return ps != null
3973                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3974                    && (!mSafeMode || (provider.info.applicationInfo.flags
3975                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3976                    ? PackageParser.generateProviderInfo(provider, flags,
3977                            ps.readUserState(userId), userId)
3978                    : null;
3979        }
3980    }
3981
3982    /**
3983     * @deprecated
3984     */
3985    @Deprecated
3986    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3987        // reader
3988        synchronized (mPackages) {
3989            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3990                    .entrySet().iterator();
3991            final int userId = UserHandle.getCallingUserId();
3992            while (i.hasNext()) {
3993                Map.Entry<String, PackageParser.Provider> entry = i.next();
3994                PackageParser.Provider p = entry.getValue();
3995                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3996
3997                if (ps != null && p.syncable
3998                        && (!mSafeMode || (p.info.applicationInfo.flags
3999                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4000                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4001                            ps.readUserState(userId), userId);
4002                    if (info != null) {
4003                        outNames.add(entry.getKey());
4004                        outInfo.add(info);
4005                    }
4006                }
4007            }
4008        }
4009    }
4010
4011    @Override
4012    public List<ProviderInfo> queryContentProviders(String processName,
4013            int uid, int flags) {
4014        ArrayList<ProviderInfo> finalList = null;
4015        // reader
4016        synchronized (mPackages) {
4017            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4018            final int userId = processName != null ?
4019                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4020            while (i.hasNext()) {
4021                final PackageParser.Provider p = i.next();
4022                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4023                if (ps != null && p.info.authority != null
4024                        && (processName == null
4025                                || (p.info.processName.equals(processName)
4026                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4027                        && mSettings.isEnabledLPr(p.info, flags, userId)
4028                        && (!mSafeMode
4029                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4030                    if (finalList == null) {
4031                        finalList = new ArrayList<ProviderInfo>(3);
4032                    }
4033                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4034                            ps.readUserState(userId), userId);
4035                    if (info != null) {
4036                        finalList.add(info);
4037                    }
4038                }
4039            }
4040        }
4041
4042        if (finalList != null) {
4043            Collections.sort(finalList, mProviderInitOrderSorter);
4044        }
4045
4046        return finalList;
4047    }
4048
4049    @Override
4050    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4051            int flags) {
4052        // reader
4053        synchronized (mPackages) {
4054            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4055            return PackageParser.generateInstrumentationInfo(i, flags);
4056        }
4057    }
4058
4059    @Override
4060    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4061            int flags) {
4062        ArrayList<InstrumentationInfo> finalList =
4063            new ArrayList<InstrumentationInfo>();
4064
4065        // reader
4066        synchronized (mPackages) {
4067            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4068            while (i.hasNext()) {
4069                final PackageParser.Instrumentation p = i.next();
4070                if (targetPackage == null
4071                        || targetPackage.equals(p.info.targetPackage)) {
4072                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4073                            flags);
4074                    if (ii != null) {
4075                        finalList.add(ii);
4076                    }
4077                }
4078            }
4079        }
4080
4081        return finalList;
4082    }
4083
4084    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4085        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4086        if (overlays == null) {
4087            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4088            return;
4089        }
4090        for (PackageParser.Package opkg : overlays.values()) {
4091            // Not much to do if idmap fails: we already logged the error
4092            // and we certainly don't want to abort installation of pkg simply
4093            // because an overlay didn't fit properly. For these reasons,
4094            // ignore the return value of createIdmapForPackagePairLI.
4095            createIdmapForPackagePairLI(pkg, opkg);
4096        }
4097    }
4098
4099    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4100            PackageParser.Package opkg) {
4101        if (!opkg.mTrustedOverlay) {
4102            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4103                    opkg.baseCodePath + ": overlay not trusted");
4104            return false;
4105        }
4106        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4107        if (overlaySet == null) {
4108            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4109                    opkg.baseCodePath + " but target package has no known overlays");
4110            return false;
4111        }
4112        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4113        // TODO: generate idmap for split APKs
4114        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4115            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4116                    + opkg.baseCodePath);
4117            return false;
4118        }
4119        PackageParser.Package[] overlayArray =
4120            overlaySet.values().toArray(new PackageParser.Package[0]);
4121        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4122            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4123                return p1.mOverlayPriority - p2.mOverlayPriority;
4124            }
4125        };
4126        Arrays.sort(overlayArray, cmp);
4127
4128        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4129        int i = 0;
4130        for (PackageParser.Package p : overlayArray) {
4131            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4132        }
4133        return true;
4134    }
4135
4136    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4137        final File[] files = dir.listFiles();
4138        if (ArrayUtils.isEmpty(files)) {
4139            Log.d(TAG, "No files in app dir " + dir);
4140            return;
4141        }
4142
4143        if (DEBUG_PACKAGE_SCANNING) {
4144            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4145                    + " flags=0x" + Integer.toHexString(parseFlags));
4146        }
4147
4148        for (File file : files) {
4149            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4150                    && !PackageInstallerService.isStageName(file.getName());
4151            if (!isPackage) {
4152                // Ignore entries which are not packages
4153                continue;
4154            }
4155            try {
4156                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4157                        scanFlags, currentTime, null);
4158            } catch (PackageManagerException e) {
4159                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4160
4161                // Delete invalid userdata apps
4162                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4163                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4164                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4165                    if (file.isDirectory()) {
4166                        FileUtils.deleteContents(file);
4167                    }
4168                    file.delete();
4169                }
4170            }
4171        }
4172    }
4173
4174    private static File getSettingsProblemFile() {
4175        File dataDir = Environment.getDataDirectory();
4176        File systemDir = new File(dataDir, "system");
4177        File fname = new File(systemDir, "uiderrors.txt");
4178        return fname;
4179    }
4180
4181    static void reportSettingsProblem(int priority, String msg) {
4182        logCriticalInfo(priority, msg);
4183    }
4184
4185    static void logCriticalInfo(int priority, String msg) {
4186        Slog.println(priority, TAG, msg);
4187        EventLogTags.writePmCriticalInfo(msg);
4188        try {
4189            File fname = getSettingsProblemFile();
4190            FileOutputStream out = new FileOutputStream(fname, true);
4191            PrintWriter pw = new FastPrintWriter(out);
4192            SimpleDateFormat formatter = new SimpleDateFormat();
4193            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4194            pw.println(dateString + ": " + msg);
4195            pw.close();
4196            FileUtils.setPermissions(
4197                    fname.toString(),
4198                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4199                    -1, -1);
4200        } catch (java.io.IOException e) {
4201        }
4202    }
4203
4204    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4205            PackageParser.Package pkg, File srcFile, int parseFlags)
4206            throws PackageManagerException {
4207        if (ps != null
4208                && ps.codePath.equals(srcFile)
4209                && ps.timeStamp == srcFile.lastModified()
4210                && !isCompatSignatureUpdateNeeded(pkg)
4211                && !isRecoverSignatureUpdateNeeded(pkg)) {
4212            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4213            if (ps.signatures.mSignatures != null
4214                    && ps.signatures.mSignatures.length != 0
4215                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4216                // Optimization: reuse the existing cached certificates
4217                // if the package appears to be unchanged.
4218                pkg.mSignatures = ps.signatures.mSignatures;
4219                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4220                synchronized (mPackages) {
4221                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4222                }
4223                return;
4224            }
4225
4226            Slog.w(TAG, "PackageSetting for " + ps.name
4227                    + " is missing signatures.  Collecting certs again to recover them.");
4228        } else {
4229            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4230        }
4231
4232        try {
4233            pp.collectCertificates(pkg, parseFlags);
4234            pp.collectManifestDigest(pkg);
4235        } catch (PackageParserException e) {
4236            throw PackageManagerException.from(e);
4237        }
4238    }
4239
4240    /*
4241     *  Scan a package and return the newly parsed package.
4242     *  Returns null in case of errors and the error code is stored in mLastScanError
4243     */
4244    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4245            long currentTime, UserHandle user) throws PackageManagerException {
4246        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4247        parseFlags |= mDefParseFlags;
4248        PackageParser pp = new PackageParser();
4249        pp.setSeparateProcesses(mSeparateProcesses);
4250        pp.setOnlyCoreApps(mOnlyCore);
4251        pp.setDisplayMetrics(mMetrics);
4252
4253        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4254            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4255        }
4256
4257        final PackageParser.Package pkg;
4258        try {
4259            pkg = pp.parsePackage(scanFile, parseFlags);
4260        } catch (PackageParserException e) {
4261            throw PackageManagerException.from(e);
4262        }
4263
4264        PackageSetting ps = null;
4265        PackageSetting updatedPkg;
4266        // reader
4267        synchronized (mPackages) {
4268            // Look to see if we already know about this package.
4269            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4270            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4271                // This package has been renamed to its original name.  Let's
4272                // use that.
4273                ps = mSettings.peekPackageLPr(oldName);
4274            }
4275            // If there was no original package, see one for the real package name.
4276            if (ps == null) {
4277                ps = mSettings.peekPackageLPr(pkg.packageName);
4278            }
4279            // Check to see if this package could be hiding/updating a system
4280            // package.  Must look for it either under the original or real
4281            // package name depending on our state.
4282            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4283            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4284        }
4285        boolean updatedPkgBetter = false;
4286        // First check if this is a system package that may involve an update
4287        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4288            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4289            // it needs to drop FLAG_PRIVILEGED.
4290            if (locationIsPrivileged(scanFile)) {
4291                updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4292            } else {
4293                updatedPkg.pkgFlags &= ~ApplicationInfo.FLAG_PRIVILEGED;
4294            }
4295
4296            if (ps != null && !ps.codePath.equals(scanFile)) {
4297                // The path has changed from what was last scanned...  check the
4298                // version of the new path against what we have stored to determine
4299                // what to do.
4300                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4301                if (pkg.mVersionCode <= ps.versionCode) {
4302                    // The system package has been updated and the code path does not match
4303                    // Ignore entry. Skip it.
4304                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4305                            + " ignored: updated version " + ps.versionCode
4306                            + " better than this " + pkg.mVersionCode);
4307                    if (!updatedPkg.codePath.equals(scanFile)) {
4308                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4309                                + ps.name + " changing from " + updatedPkg.codePathString
4310                                + " to " + scanFile);
4311                        updatedPkg.codePath = scanFile;
4312                        updatedPkg.codePathString = scanFile.toString();
4313                    }
4314                    updatedPkg.pkg = pkg;
4315                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4316                } else {
4317                    // The current app on the system partition is better than
4318                    // what we have updated to on the data partition; switch
4319                    // back to the system partition version.
4320                    // At this point, its safely assumed that package installation for
4321                    // apps in system partition will go through. If not there won't be a working
4322                    // version of the app
4323                    // writer
4324                    synchronized (mPackages) {
4325                        // Just remove the loaded entries from package lists.
4326                        mPackages.remove(ps.name);
4327                    }
4328
4329                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4330                            + " reverting from " + ps.codePathString
4331                            + ": new version " + pkg.mVersionCode
4332                            + " better than installed " + ps.versionCode);
4333
4334                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4335                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4336                            getAppDexInstructionSets(ps));
4337                    synchronized (mInstallLock) {
4338                        args.cleanUpResourcesLI();
4339                    }
4340                    synchronized (mPackages) {
4341                        mSettings.enableSystemPackageLPw(ps.name);
4342                    }
4343                    updatedPkgBetter = true;
4344                }
4345            }
4346        }
4347
4348        if (updatedPkg != null) {
4349            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4350            // initially
4351            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4352
4353            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4354            // flag set initially
4355            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4356                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4357            }
4358        }
4359
4360        // Verify certificates against what was last scanned
4361        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4362
4363        /*
4364         * A new system app appeared, but we already had a non-system one of the
4365         * same name installed earlier.
4366         */
4367        boolean shouldHideSystemApp = false;
4368        if (updatedPkg == null && ps != null
4369                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4370            /*
4371             * Check to make sure the signatures match first. If they don't,
4372             * wipe the installed application and its data.
4373             */
4374            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4375                    != PackageManager.SIGNATURE_MATCH) {
4376                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4377                        + " signatures don't match existing userdata copy; removing");
4378                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4379                ps = null;
4380            } else {
4381                /*
4382                 * If the newly-added system app is an older version than the
4383                 * already installed version, hide it. It will be scanned later
4384                 * and re-added like an update.
4385                 */
4386                if (pkg.mVersionCode <= ps.versionCode) {
4387                    shouldHideSystemApp = true;
4388                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4389                            + " but new version " + pkg.mVersionCode + " better than installed "
4390                            + ps.versionCode + "; hiding system");
4391                } else {
4392                    /*
4393                     * The newly found system app is a newer version that the
4394                     * one previously installed. Simply remove the
4395                     * already-installed application and replace it with our own
4396                     * while keeping the application data.
4397                     */
4398                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4399                            + " reverting from " + ps.codePathString + ": new version "
4400                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4401                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4402                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4403                            getAppDexInstructionSets(ps));
4404                    synchronized (mInstallLock) {
4405                        args.cleanUpResourcesLI();
4406                    }
4407                }
4408            }
4409        }
4410
4411        // The apk is forward locked (not public) if its code and resources
4412        // are kept in different files. (except for app in either system or
4413        // vendor path).
4414        // TODO grab this value from PackageSettings
4415        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4416            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4417                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4418            }
4419        }
4420
4421        // TODO: extend to support forward-locked splits
4422        String resourcePath = null;
4423        String baseResourcePath = null;
4424        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4425            if (ps != null && ps.resourcePathString != null) {
4426                resourcePath = ps.resourcePathString;
4427                baseResourcePath = ps.resourcePathString;
4428            } else {
4429                // Should not happen at all. Just log an error.
4430                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4431            }
4432        } else {
4433            resourcePath = pkg.codePath;
4434            baseResourcePath = pkg.baseCodePath;
4435        }
4436
4437        // Set application objects path explicitly.
4438        pkg.applicationInfo.setCodePath(pkg.codePath);
4439        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4440        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4441        pkg.applicationInfo.setResourcePath(resourcePath);
4442        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4443        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4444
4445        // Note that we invoke the following method only if we are about to unpack an application
4446        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4447                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4448
4449        /*
4450         * If the system app should be overridden by a previously installed
4451         * data, hide the system app now and let the /data/app scan pick it up
4452         * again.
4453         */
4454        if (shouldHideSystemApp) {
4455            synchronized (mPackages) {
4456                /*
4457                 * We have to grant systems permissions before we hide, because
4458                 * grantPermissions will assume the package update is trying to
4459                 * expand its permissions.
4460                 */
4461                grantPermissionsLPw(pkg, true, pkg.packageName);
4462                mSettings.disableSystemPackageLPw(pkg.packageName);
4463            }
4464        }
4465
4466        return scannedPkg;
4467    }
4468
4469    private static String fixProcessName(String defProcessName,
4470            String processName, int uid) {
4471        if (processName == null) {
4472            return defProcessName;
4473        }
4474        return processName;
4475    }
4476
4477    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4478            throws PackageManagerException {
4479        if (pkgSetting.signatures.mSignatures != null) {
4480            // Already existing package. Make sure signatures match
4481            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4482                    == PackageManager.SIGNATURE_MATCH;
4483            if (!match) {
4484                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4485                        == PackageManager.SIGNATURE_MATCH;
4486            }
4487            if (!match) {
4488                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4489                        == PackageManager.SIGNATURE_MATCH;
4490            }
4491            if (!match) {
4492                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4493                        + pkg.packageName + " signatures do not match the "
4494                        + "previously installed version; ignoring!");
4495            }
4496        }
4497
4498        // Check for shared user signatures
4499        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4500            // Already existing package. Make sure signatures match
4501            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4502                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4503            if (!match) {
4504                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4505                        == PackageManager.SIGNATURE_MATCH;
4506            }
4507            if (!match) {
4508                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4509                        == PackageManager.SIGNATURE_MATCH;
4510            }
4511            if (!match) {
4512                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4513                        "Package " + pkg.packageName
4514                        + " has no signatures that match those in shared user "
4515                        + pkgSetting.sharedUser.name + "; ignoring!");
4516            }
4517        }
4518    }
4519
4520    /**
4521     * Enforces that only the system UID or root's UID can call a method exposed
4522     * via Binder.
4523     *
4524     * @param message used as message if SecurityException is thrown
4525     * @throws SecurityException if the caller is not system or root
4526     */
4527    private static final void enforceSystemOrRoot(String message) {
4528        final int uid = Binder.getCallingUid();
4529        if (uid != Process.SYSTEM_UID && uid != 0) {
4530            throw new SecurityException(message);
4531        }
4532    }
4533
4534    @Override
4535    public void performBootDexOpt() {
4536        enforceSystemOrRoot("Only the system can request dexopt be performed");
4537
4538        // Before everything else, see whether we need to fstrim.
4539        try {
4540            IMountService ms = PackageHelper.getMountService();
4541            if (ms != null) {
4542                final long interval = android.provider.Settings.Global.getLong(
4543                        mContext.getContentResolver(),
4544                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
4545                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
4546                if (interval > 0) {
4547                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
4548                    if (timeSinceLast > interval) {
4549                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
4550                                + "; running immediately");
4551                        if (!isFirstBoot()) {
4552                            try {
4553                                ActivityManagerNative.getDefault().showBootMessage(
4554                                        mContext.getResources().getString(
4555                                                R.string.android_upgrading_fstrim), true);
4556                            } catch (RemoteException e) {
4557                            }
4558                        }
4559                        ms.runMaintenance();
4560                    }
4561                }
4562            } else {
4563                Slog.e(TAG, "Mount service unavailable!");
4564            }
4565        } catch (RemoteException e) {
4566            // Can't happen; MountService is local
4567        }
4568
4569        final ArraySet<PackageParser.Package> pkgs;
4570        synchronized (mPackages) {
4571            pkgs = mDeferredDexOpt;
4572            mDeferredDexOpt = null;
4573        }
4574
4575        if (pkgs != null) {
4576            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4577            // in case the device runs out of space.
4578            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4579            // Give priority to core apps.
4580            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4581                PackageParser.Package pkg = it.next();
4582                if (pkg.coreApp) {
4583                    if (DEBUG_DEXOPT) {
4584                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4585                    }
4586                    sortedPkgs.add(pkg);
4587                    it.remove();
4588                }
4589            }
4590            // Give priority to system apps that listen for pre boot complete.
4591            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4592            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4593            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4594                PackageParser.Package pkg = it.next();
4595                if (pkgNames.contains(pkg.packageName)) {
4596                    if (DEBUG_DEXOPT) {
4597                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4598                    }
4599                    sortedPkgs.add(pkg);
4600                    it.remove();
4601                }
4602            }
4603            // Give priority to system apps.
4604            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4605                PackageParser.Package pkg = it.next();
4606                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4607                    if (DEBUG_DEXOPT) {
4608                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4609                    }
4610                    sortedPkgs.add(pkg);
4611                    it.remove();
4612                }
4613            }
4614            // Give priority to updated system apps.
4615            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4616                PackageParser.Package pkg = it.next();
4617                if (isUpdatedSystemApp(pkg)) {
4618                    if (DEBUG_DEXOPT) {
4619                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4620                    }
4621                    sortedPkgs.add(pkg);
4622                    it.remove();
4623                }
4624            }
4625            // Give priority to apps that listen for boot complete.
4626            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4627            pkgNames = getPackageNamesForIntent(intent);
4628            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4629                PackageParser.Package pkg = it.next();
4630                if (pkgNames.contains(pkg.packageName)) {
4631                    if (DEBUG_DEXOPT) {
4632                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4633                    }
4634                    sortedPkgs.add(pkg);
4635                    it.remove();
4636                }
4637            }
4638            // Filter out packages that aren't recently used.
4639            filterRecentlyUsedApps(pkgs);
4640            // Add all remaining apps.
4641            for (PackageParser.Package pkg : pkgs) {
4642                if (DEBUG_DEXOPT) {
4643                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4644                }
4645                sortedPkgs.add(pkg);
4646            }
4647
4648            // If we want to be lazy, filter everything that wasn't recently used.
4649            if (mLazyDexOpt) {
4650                filterRecentlyUsedApps(sortedPkgs);
4651            }
4652
4653            int i = 0;
4654            int total = sortedPkgs.size();
4655            File dataDir = Environment.getDataDirectory();
4656            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4657            if (lowThreshold == 0) {
4658                throw new IllegalStateException("Invalid low memory threshold");
4659            }
4660            for (PackageParser.Package pkg : sortedPkgs) {
4661                long usableSpace = dataDir.getUsableSpace();
4662                if (usableSpace < lowThreshold) {
4663                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4664                    break;
4665                }
4666                performBootDexOpt(pkg, ++i, total);
4667            }
4668        }
4669    }
4670
4671    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4672        // Filter out packages that aren't recently used.
4673        //
4674        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4675        // should do a full dexopt.
4676        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4677            int total = pkgs.size();
4678            int skipped = 0;
4679            long now = System.currentTimeMillis();
4680            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4681                PackageParser.Package pkg = i.next();
4682                long then = pkg.mLastPackageUsageTimeInMills;
4683                if (then + mDexOptLRUThresholdInMills < now) {
4684                    if (DEBUG_DEXOPT) {
4685                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4686                              ((then == 0) ? "never" : new Date(then)));
4687                    }
4688                    i.remove();
4689                    skipped++;
4690                }
4691            }
4692            if (DEBUG_DEXOPT) {
4693                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4694            }
4695        }
4696    }
4697
4698    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4699        List<ResolveInfo> ris = null;
4700        try {
4701            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4702                    intent, null, 0, UserHandle.USER_OWNER);
4703        } catch (RemoteException e) {
4704        }
4705        ArraySet<String> pkgNames = new ArraySet<String>();
4706        if (ris != null) {
4707            for (ResolveInfo ri : ris) {
4708                pkgNames.add(ri.activityInfo.packageName);
4709            }
4710        }
4711        return pkgNames;
4712    }
4713
4714    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4715        if (DEBUG_DEXOPT) {
4716            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4717        }
4718        if (!isFirstBoot()) {
4719            try {
4720                ActivityManagerNative.getDefault().showBootMessage(
4721                        mContext.getResources().getString(R.string.android_upgrading_apk,
4722                                curr, total), true);
4723            } catch (RemoteException e) {
4724            }
4725        }
4726        PackageParser.Package p = pkg;
4727        synchronized (mInstallLock) {
4728            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4729                            false /* defer */, true /* include dependencies */);
4730        }
4731    }
4732
4733    @Override
4734    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4735        return performDexOpt(packageName, instructionSet, false);
4736    }
4737
4738    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4739        if (info.primaryCpuAbi == null) {
4740            return getPreferredInstructionSet();
4741        }
4742
4743        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4744    }
4745
4746    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4747        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4748        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4749        if (!dexopt && !updateUsage) {
4750            // We aren't going to dexopt or update usage, so bail early.
4751            return false;
4752        }
4753        PackageParser.Package p;
4754        final String targetInstructionSet;
4755        synchronized (mPackages) {
4756            p = mPackages.get(packageName);
4757            if (p == null) {
4758                return false;
4759            }
4760            if (updateUsage) {
4761                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4762            }
4763            mPackageUsage.write(false);
4764            if (!dexopt) {
4765                // We aren't going to dexopt, so bail early.
4766                return false;
4767            }
4768
4769            targetInstructionSet = instructionSet != null ? instructionSet :
4770                    getPrimaryInstructionSet(p.applicationInfo);
4771            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4772                return false;
4773            }
4774        }
4775
4776        synchronized (mInstallLock) {
4777            final String[] instructionSets = new String[] { targetInstructionSet };
4778            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4779                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4780        }
4781    }
4782
4783    public ArraySet<String> getPackagesThatNeedDexOpt() {
4784        ArraySet<String> pkgs = null;
4785        synchronized (mPackages) {
4786            for (PackageParser.Package p : mPackages.values()) {
4787                if (DEBUG_DEXOPT) {
4788                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4789                }
4790                if (!p.mDexOptPerformed.isEmpty()) {
4791                    continue;
4792                }
4793                if (pkgs == null) {
4794                    pkgs = new ArraySet<String>();
4795                }
4796                pkgs.add(p.packageName);
4797            }
4798        }
4799        return pkgs;
4800    }
4801
4802    public void shutdown() {
4803        mPackageUsage.write(true);
4804    }
4805
4806    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4807             boolean forceDex, boolean defer, ArraySet<String> done) {
4808        for (int i=0; i<libs.size(); i++) {
4809            PackageParser.Package libPkg;
4810            String libName;
4811            synchronized (mPackages) {
4812                libName = libs.get(i);
4813                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4814                if (lib != null && lib.apk != null) {
4815                    libPkg = mPackages.get(lib.apk);
4816                } else {
4817                    libPkg = null;
4818                }
4819            }
4820            if (libPkg != null && !done.contains(libName)) {
4821                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4822            }
4823        }
4824    }
4825
4826    static final int DEX_OPT_SKIPPED = 0;
4827    static final int DEX_OPT_PERFORMED = 1;
4828    static final int DEX_OPT_DEFERRED = 2;
4829    static final int DEX_OPT_FAILED = -1;
4830
4831    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4832            boolean forceDex, boolean defer, ArraySet<String> done) {
4833        final String[] instructionSets = targetInstructionSets != null ?
4834                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4835
4836        if (done != null) {
4837            done.add(pkg.packageName);
4838            if (pkg.usesLibraries != null) {
4839                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4840            }
4841            if (pkg.usesOptionalLibraries != null) {
4842                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4843            }
4844        }
4845
4846        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4847            return DEX_OPT_SKIPPED;
4848        }
4849
4850        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4851
4852        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4853        boolean performedDexOpt = false;
4854        // There are three basic cases here:
4855        // 1.) we need to dexopt, either because we are forced or it is needed
4856        // 2.) we are defering a needed dexopt
4857        // 3.) we are skipping an unneeded dexopt
4858        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4859        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4860            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4861                continue;
4862            }
4863
4864            for (String path : paths) {
4865                try {
4866                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4867                    // patckage or the one we find does not match the image checksum (i.e. it was
4868                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4869                    // odex file and it matches the checksum of the image but not its base address,
4870                    // meaning we need to move it.
4871                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4872                            pkg.packageName, dexCodeInstructionSet, defer);
4873                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4874                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4875                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4876                                + " vmSafeMode=" + vmSafeMode);
4877                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4878                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4879                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4880
4881                        if (ret < 0) {
4882                            // Don't bother running dexopt again if we failed, it will probably
4883                            // just result in an error again. Also, don't bother dexopting for other
4884                            // paths & ISAs.
4885                            return DEX_OPT_FAILED;
4886                        }
4887
4888                        performedDexOpt = true;
4889                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4890                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4891                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4892                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4893                                pkg.packageName, dexCodeInstructionSet);
4894
4895                        if (ret < 0) {
4896                            // Don't bother running patchoat again if we failed, it will probably
4897                            // just result in an error again. Also, don't bother dexopting for other
4898                            // paths & ISAs.
4899                            return DEX_OPT_FAILED;
4900                        }
4901
4902                        performedDexOpt = true;
4903                    }
4904
4905                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4906                    // paths and instruction sets. We'll deal with them all together when we process
4907                    // our list of deferred dexopts.
4908                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4909                        if (mDeferredDexOpt == null) {
4910                            mDeferredDexOpt = new ArraySet<PackageParser.Package>();
4911                        }
4912                        mDeferredDexOpt.add(pkg);
4913                        return DEX_OPT_DEFERRED;
4914                    }
4915                } catch (FileNotFoundException e) {
4916                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4917                    return DEX_OPT_FAILED;
4918                } catch (IOException e) {
4919                    Slog.w(TAG, "IOException reading apk: " + path, e);
4920                    return DEX_OPT_FAILED;
4921                } catch (StaleDexCacheError e) {
4922                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4923                    return DEX_OPT_FAILED;
4924                } catch (Exception e) {
4925                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4926                    return DEX_OPT_FAILED;
4927                }
4928            }
4929
4930            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4931            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4932            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4933            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4934            // it.
4935            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4936        }
4937
4938        // If we've gotten here, we're sure that no error occurred and that we haven't
4939        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4940        // we've skipped all of them because they are up to date. In both cases this
4941        // package doesn't need dexopt any longer.
4942        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4943    }
4944
4945    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4946        if (info.primaryCpuAbi != null) {
4947            if (info.secondaryCpuAbi != null) {
4948                return new String[] {
4949                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4950                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4951            } else {
4952                return new String[] {
4953                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4954            }
4955        }
4956
4957        return new String[] { getPreferredInstructionSet() };
4958    }
4959
4960    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4961        if (ps.primaryCpuAbiString != null) {
4962            if (ps.secondaryCpuAbiString != null) {
4963                return new String[] {
4964                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4965                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4966            } else {
4967                return new String[] {
4968                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4969            }
4970        }
4971
4972        return new String[] { getPreferredInstructionSet() };
4973    }
4974
4975    private static String getPreferredInstructionSet() {
4976        if (sPreferredInstructionSet == null) {
4977            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4978        }
4979
4980        return sPreferredInstructionSet;
4981    }
4982
4983    private static List<String> getAllInstructionSets() {
4984        final String[] allAbis = Build.SUPPORTED_ABIS;
4985        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4986
4987        for (String abi : allAbis) {
4988            final String instructionSet = VMRuntime.getInstructionSet(abi);
4989            if (!allInstructionSets.contains(instructionSet)) {
4990                allInstructionSets.add(instructionSet);
4991            }
4992        }
4993
4994        return allInstructionSets;
4995    }
4996
4997    /**
4998     * Returns the instruction set that should be used to compile dex code. In the presence of
4999     * a native bridge this might be different than the one shared libraries use.
5000     */
5001    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
5002        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
5003        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
5004    }
5005
5006    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
5007        ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length);
5008        for (String instructionSet : instructionSets) {
5009            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
5010        }
5011        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
5012    }
5013
5014    /**
5015     * Returns deduplicated list of supported instructions for dex code.
5016     */
5017    public static String[] getAllDexCodeInstructionSets() {
5018        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
5019        for (int i = 0; i < supportedInstructionSets.length; i++) {
5020            String abi = Build.SUPPORTED_ABIS[i];
5021            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
5022        }
5023        return getDexCodeInstructionSets(supportedInstructionSets);
5024    }
5025
5026    @Override
5027    public void forceDexOpt(String packageName) {
5028        enforceSystemOrRoot("forceDexOpt");
5029
5030        PackageParser.Package pkg;
5031        synchronized (mPackages) {
5032            pkg = mPackages.get(packageName);
5033            if (pkg == null) {
5034                throw new IllegalArgumentException("Missing package: " + packageName);
5035            }
5036        }
5037
5038        synchronized (mInstallLock) {
5039            final String[] instructionSets = new String[] {
5040                    getPrimaryInstructionSet(pkg.applicationInfo) };
5041            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
5042            if (res != DEX_OPT_PERFORMED) {
5043                throw new IllegalStateException("Failed to dexopt: " + res);
5044            }
5045        }
5046    }
5047
5048    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
5049                                boolean forceDex, boolean defer, boolean inclDependencies) {
5050        ArraySet<String> done;
5051        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
5052            done = new ArraySet<String>();
5053            done.add(pkg.packageName);
5054        } else {
5055            done = null;
5056        }
5057        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
5058    }
5059
5060    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5061        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5062            Slog.w(TAG, "Unable to update from " + oldPkg.name
5063                    + " to " + newPkg.packageName
5064                    + ": old package not in system partition");
5065            return false;
5066        } else if (mPackages.get(oldPkg.name) != null) {
5067            Slog.w(TAG, "Unable to update from " + oldPkg.name
5068                    + " to " + newPkg.packageName
5069                    + ": old package still exists");
5070            return false;
5071        }
5072        return true;
5073    }
5074
5075    File getDataPathForUser(int userId) {
5076        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
5077    }
5078
5079    private File getDataPathForPackage(String packageName, int userId) {
5080        /*
5081         * Until we fully support multiple users, return the directory we
5082         * previously would have. The PackageManagerTests will need to be
5083         * revised when this is changed back..
5084         */
5085        if (userId == 0) {
5086            return new File(mAppDataDir, packageName);
5087        } else {
5088            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5089                + File.separator + packageName);
5090        }
5091    }
5092
5093    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5094        int[] users = sUserManager.getUserIds();
5095        int res = mInstaller.install(packageName, uid, uid, seinfo);
5096        if (res < 0) {
5097            return res;
5098        }
5099        for (int user : users) {
5100            if (user != 0) {
5101                res = mInstaller.createUserData(packageName,
5102                        UserHandle.getUid(user, uid), user, seinfo);
5103                if (res < 0) {
5104                    return res;
5105                }
5106            }
5107        }
5108        return res;
5109    }
5110
5111    private int removeDataDirsLI(String packageName) {
5112        int[] users = sUserManager.getUserIds();
5113        int res = 0;
5114        for (int user : users) {
5115            int resInner = mInstaller.remove(packageName, user);
5116            if (resInner < 0) {
5117                res = resInner;
5118            }
5119        }
5120
5121        return res;
5122    }
5123
5124    private int deleteCodeCacheDirsLI(String packageName) {
5125        int[] users = sUserManager.getUserIds();
5126        int res = 0;
5127        for (int user : users) {
5128            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5129            if (resInner < 0) {
5130                res = resInner;
5131            }
5132        }
5133        return res;
5134    }
5135
5136    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5137            PackageParser.Package changingLib) {
5138        if (file.path != null) {
5139            usesLibraryFiles.add(file.path);
5140            return;
5141        }
5142        PackageParser.Package p = mPackages.get(file.apk);
5143        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5144            // If we are doing this while in the middle of updating a library apk,
5145            // then we need to make sure to use that new apk for determining the
5146            // dependencies here.  (We haven't yet finished committing the new apk
5147            // to the package manager state.)
5148            if (p == null || p.packageName.equals(changingLib.packageName)) {
5149                p = changingLib;
5150            }
5151        }
5152        if (p != null) {
5153            usesLibraryFiles.addAll(p.getAllCodePaths());
5154        }
5155    }
5156
5157    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5158            PackageParser.Package changingLib) throws PackageManagerException {
5159        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5160            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5161            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5162            for (int i=0; i<N; i++) {
5163                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5164                if (file == null) {
5165                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5166                            "Package " + pkg.packageName + " requires unavailable shared library "
5167                            + pkg.usesLibraries.get(i) + "; failing!");
5168                }
5169                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5170            }
5171            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5172            for (int i=0; i<N; i++) {
5173                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5174                if (file == null) {
5175                    Slog.w(TAG, "Package " + pkg.packageName
5176                            + " desires unavailable shared library "
5177                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5178                } else {
5179                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5180                }
5181            }
5182            N = usesLibraryFiles.size();
5183            if (N > 0) {
5184                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5185            } else {
5186                pkg.usesLibraryFiles = null;
5187            }
5188        }
5189    }
5190
5191    private static boolean hasString(List<String> list, List<String> which) {
5192        if (list == null) {
5193            return false;
5194        }
5195        for (int i=list.size()-1; i>=0; i--) {
5196            for (int j=which.size()-1; j>=0; j--) {
5197                if (which.get(j).equals(list.get(i))) {
5198                    return true;
5199                }
5200            }
5201        }
5202        return false;
5203    }
5204
5205    private void updateAllSharedLibrariesLPw() {
5206        for (PackageParser.Package pkg : mPackages.values()) {
5207            try {
5208                updateSharedLibrariesLPw(pkg, null);
5209            } catch (PackageManagerException e) {
5210                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5211            }
5212        }
5213    }
5214
5215    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5216            PackageParser.Package changingPkg) {
5217        ArrayList<PackageParser.Package> res = null;
5218        for (PackageParser.Package pkg : mPackages.values()) {
5219            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5220                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5221                if (res == null) {
5222                    res = new ArrayList<PackageParser.Package>();
5223                }
5224                res.add(pkg);
5225                try {
5226                    updateSharedLibrariesLPw(pkg, changingPkg);
5227                } catch (PackageManagerException e) {
5228                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5229                }
5230            }
5231        }
5232        return res;
5233    }
5234
5235    /**
5236     * Derive the value of the {@code cpuAbiOverride} based on the provided
5237     * value and an optional stored value from the package settings.
5238     */
5239    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5240        String cpuAbiOverride = null;
5241
5242        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5243            cpuAbiOverride = null;
5244        } else if (abiOverride != null) {
5245            cpuAbiOverride = abiOverride;
5246        } else if (settings != null) {
5247            cpuAbiOverride = settings.cpuAbiOverrideString;
5248        }
5249
5250        return cpuAbiOverride;
5251    }
5252
5253    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5254            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5255        boolean success = false;
5256        try {
5257            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5258                    currentTime, user);
5259            success = true;
5260            return res;
5261        } finally {
5262            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5263                removeDataDirsLI(pkg.packageName);
5264            }
5265        }
5266    }
5267
5268    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5269            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5270        final File scanFile = new File(pkg.codePath);
5271        if (pkg.applicationInfo.getCodePath() == null ||
5272                pkg.applicationInfo.getResourcePath() == null) {
5273            // Bail out. The resource and code paths haven't been set.
5274            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5275                    "Code and resource paths haven't been set correctly");
5276        }
5277
5278        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5279            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5280        } else {
5281            // Only allow system apps to be flagged as core apps.
5282            pkg.coreApp = false;
5283        }
5284
5285        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5286            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5287        }
5288
5289        if (mCustomResolverComponentName != null &&
5290                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5291            setUpCustomResolverActivity(pkg);
5292        }
5293
5294        if (pkg.packageName.equals("android")) {
5295            synchronized (mPackages) {
5296                if (mAndroidApplication != null) {
5297                    Slog.w(TAG, "*************************************************");
5298                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5299                    Slog.w(TAG, " file=" + scanFile);
5300                    Slog.w(TAG, "*************************************************");
5301                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5302                            "Core android package being redefined.  Skipping.");
5303                }
5304
5305                // Set up information for our fall-back user intent resolution activity.
5306                mPlatformPackage = pkg;
5307                pkg.mVersionCode = mSdkVersion;
5308                mAndroidApplication = pkg.applicationInfo;
5309
5310                if (!mResolverReplaced) {
5311                    mResolveActivity.applicationInfo = mAndroidApplication;
5312                    mResolveActivity.name = ResolverActivity.class.getName();
5313                    mResolveActivity.packageName = mAndroidApplication.packageName;
5314                    mResolveActivity.processName = "system:ui";
5315                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5316                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5317                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5318                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5319                    mResolveActivity.exported = true;
5320                    mResolveActivity.enabled = true;
5321                    mResolveInfo.activityInfo = mResolveActivity;
5322                    mResolveInfo.priority = 0;
5323                    mResolveInfo.preferredOrder = 0;
5324                    mResolveInfo.match = 0;
5325                    mResolveComponentName = new ComponentName(
5326                            mAndroidApplication.packageName, mResolveActivity.name);
5327                }
5328            }
5329        }
5330
5331        if (DEBUG_PACKAGE_SCANNING) {
5332            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5333                Log.d(TAG, "Scanning package " + pkg.packageName);
5334        }
5335
5336        if (mPackages.containsKey(pkg.packageName)
5337                || mSharedLibraries.containsKey(pkg.packageName)) {
5338            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5339                    "Application package " + pkg.packageName
5340                    + " already installed.  Skipping duplicate.");
5341        }
5342
5343        // Initialize package source and resource directories
5344        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5345        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5346
5347        SharedUserSetting suid = null;
5348        PackageSetting pkgSetting = null;
5349
5350        if (!isSystemApp(pkg)) {
5351            // Only system apps can use these features.
5352            pkg.mOriginalPackages = null;
5353            pkg.mRealPackage = null;
5354            pkg.mAdoptPermissions = null;
5355        }
5356
5357        // writer
5358        synchronized (mPackages) {
5359            if (pkg.mSharedUserId != null) {
5360                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5361                if (suid == null) {
5362                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5363                            "Creating application package " + pkg.packageName
5364                            + " for shared user failed");
5365                }
5366                if (DEBUG_PACKAGE_SCANNING) {
5367                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5368                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5369                                + "): packages=" + suid.packages);
5370                }
5371            }
5372
5373            // Check if we are renaming from an original package name.
5374            PackageSetting origPackage = null;
5375            String realName = null;
5376            if (pkg.mOriginalPackages != null) {
5377                // This package may need to be renamed to a previously
5378                // installed name.  Let's check on that...
5379                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5380                if (pkg.mOriginalPackages.contains(renamed)) {
5381                    // This package had originally been installed as the
5382                    // original name, and we have already taken care of
5383                    // transitioning to the new one.  Just update the new
5384                    // one to continue using the old name.
5385                    realName = pkg.mRealPackage;
5386                    if (!pkg.packageName.equals(renamed)) {
5387                        // Callers into this function may have already taken
5388                        // care of renaming the package; only do it here if
5389                        // it is not already done.
5390                        pkg.setPackageName(renamed);
5391                    }
5392
5393                } else {
5394                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5395                        if ((origPackage = mSettings.peekPackageLPr(
5396                                pkg.mOriginalPackages.get(i))) != null) {
5397                            // We do have the package already installed under its
5398                            // original name...  should we use it?
5399                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5400                                // New package is not compatible with original.
5401                                origPackage = null;
5402                                continue;
5403                            } else if (origPackage.sharedUser != null) {
5404                                // Make sure uid is compatible between packages.
5405                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5406                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5407                                            + " to " + pkg.packageName + ": old uid "
5408                                            + origPackage.sharedUser.name
5409                                            + " differs from " + pkg.mSharedUserId);
5410                                    origPackage = null;
5411                                    continue;
5412                                }
5413                            } else {
5414                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5415                                        + pkg.packageName + " to old name " + origPackage.name);
5416                            }
5417                            break;
5418                        }
5419                    }
5420                }
5421            }
5422
5423            if (mTransferedPackages.contains(pkg.packageName)) {
5424                Slog.w(TAG, "Package " + pkg.packageName
5425                        + " was transferred to another, but its .apk remains");
5426            }
5427
5428            // Just create the setting, don't add it yet. For already existing packages
5429            // the PkgSetting exists already and doesn't have to be created.
5430            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5431                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5432                    pkg.applicationInfo.primaryCpuAbi,
5433                    pkg.applicationInfo.secondaryCpuAbi,
5434                    pkg.applicationInfo.flags, user, false);
5435            if (pkgSetting == null) {
5436                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5437                        "Creating application package " + pkg.packageName + " failed");
5438            }
5439
5440            if (pkgSetting.origPackage != null) {
5441                // If we are first transitioning from an original package,
5442                // fix up the new package's name now.  We need to do this after
5443                // looking up the package under its new name, so getPackageLP
5444                // can take care of fiddling things correctly.
5445                pkg.setPackageName(origPackage.name);
5446
5447                // File a report about this.
5448                String msg = "New package " + pkgSetting.realName
5449                        + " renamed to replace old package " + pkgSetting.name;
5450                reportSettingsProblem(Log.WARN, msg);
5451
5452                // Make a note of it.
5453                mTransferedPackages.add(origPackage.name);
5454
5455                // No longer need to retain this.
5456                pkgSetting.origPackage = null;
5457            }
5458
5459            if (realName != null) {
5460                // Make a note of it.
5461                mTransferedPackages.add(pkg.packageName);
5462            }
5463
5464            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5465                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5466            }
5467
5468            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5469                // Check all shared libraries and map to their actual file path.
5470                // We only do this here for apps not on a system dir, because those
5471                // are the only ones that can fail an install due to this.  We
5472                // will take care of the system apps by updating all of their
5473                // library paths after the scan is done.
5474                updateSharedLibrariesLPw(pkg, null);
5475            }
5476
5477            if (mFoundPolicyFile) {
5478                SELinuxMMAC.assignSeinfoValue(pkg);
5479            }
5480
5481            pkg.applicationInfo.uid = pkgSetting.appId;
5482            pkg.mExtras = pkgSetting;
5483            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5484                try {
5485                    verifySignaturesLP(pkgSetting, pkg);
5486                    // We just determined the app is signed correctly, so bring
5487                    // over the latest parsed certs.
5488                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5489                } catch (PackageManagerException e) {
5490                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5491                        throw e;
5492                    }
5493                    // The signature has changed, but this package is in the system
5494                    // image...  let's recover!
5495                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5496                    // However...  if this package is part of a shared user, but it
5497                    // doesn't match the signature of the shared user, let's fail.
5498                    // What this means is that you can't change the signatures
5499                    // associated with an overall shared user, which doesn't seem all
5500                    // that unreasonable.
5501                    if (pkgSetting.sharedUser != null) {
5502                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5503                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5504                            throw new PackageManagerException(
5505                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5506                                            "Signature mismatch for shared user : "
5507                                            + pkgSetting.sharedUser);
5508                        }
5509                    }
5510                    // File a report about this.
5511                    String msg = "System package " + pkg.packageName
5512                        + " signature changed; retaining data.";
5513                    reportSettingsProblem(Log.WARN, msg);
5514                }
5515            } else {
5516                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5517                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5518                            + pkg.packageName + " upgrade keys do not match the "
5519                            + "previously installed version");
5520                } else {
5521                    // We just determined the app is signed correctly, so bring
5522                    // over the latest parsed certs.
5523                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5524                }
5525            }
5526            // Verify that this new package doesn't have any content providers
5527            // that conflict with existing packages.  Only do this if the
5528            // package isn't already installed, since we don't want to break
5529            // things that are installed.
5530            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5531                final int N = pkg.providers.size();
5532                int i;
5533                for (i=0; i<N; i++) {
5534                    PackageParser.Provider p = pkg.providers.get(i);
5535                    if (p.info.authority != null) {
5536                        String names[] = p.info.authority.split(";");
5537                        for (int j = 0; j < names.length; j++) {
5538                            if (mProvidersByAuthority.containsKey(names[j])) {
5539                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5540                                final String otherPackageName =
5541                                        ((other != null && other.getComponentName() != null) ?
5542                                                other.getComponentName().getPackageName() : "?");
5543                                throw new PackageManagerException(
5544                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5545                                                "Can't install because provider name " + names[j]
5546                                                + " (in package " + pkg.applicationInfo.packageName
5547                                                + ") is already used by " + otherPackageName);
5548                            }
5549                        }
5550                    }
5551                }
5552            }
5553
5554            if (pkg.mAdoptPermissions != null) {
5555                // This package wants to adopt ownership of permissions from
5556                // another package.
5557                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5558                    final String origName = pkg.mAdoptPermissions.get(i);
5559                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5560                    if (orig != null) {
5561                        if (verifyPackageUpdateLPr(orig, pkg)) {
5562                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5563                                    + pkg.packageName);
5564                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5565                        }
5566                    }
5567                }
5568            }
5569        }
5570
5571        final String pkgName = pkg.packageName;
5572
5573        final long scanFileTime = scanFile.lastModified();
5574        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5575        pkg.applicationInfo.processName = fixProcessName(
5576                pkg.applicationInfo.packageName,
5577                pkg.applicationInfo.processName,
5578                pkg.applicationInfo.uid);
5579
5580        File dataPath;
5581        if (mPlatformPackage == pkg) {
5582            // The system package is special.
5583            dataPath = new File(Environment.getDataDirectory(), "system");
5584
5585            pkg.applicationInfo.dataDir = dataPath.getPath();
5586
5587        } else {
5588            // This is a normal package, need to make its data directory.
5589            dataPath = getDataPathForPackage(pkg.packageName, 0);
5590
5591            boolean uidError = false;
5592            if (dataPath.exists()) {
5593                int currentUid = 0;
5594                try {
5595                    StructStat stat = Os.stat(dataPath.getPath());
5596                    currentUid = stat.st_uid;
5597                } catch (ErrnoException e) {
5598                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5599                }
5600
5601                // If we have mismatched owners for the data path, we have a problem.
5602                if (currentUid != pkg.applicationInfo.uid) {
5603                    boolean recovered = false;
5604                    if (currentUid == 0) {
5605                        // The directory somehow became owned by root.  Wow.
5606                        // This is probably because the system was stopped while
5607                        // installd was in the middle of messing with its libs
5608                        // directory.  Ask installd to fix that.
5609                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5610                                pkg.applicationInfo.uid);
5611                        if (ret >= 0) {
5612                            recovered = true;
5613                            String msg = "Package " + pkg.packageName
5614                                    + " unexpectedly changed to uid 0; recovered to " +
5615                                    + pkg.applicationInfo.uid;
5616                            reportSettingsProblem(Log.WARN, msg);
5617                        }
5618                    }
5619                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5620                            || (scanFlags&SCAN_BOOTING) != 0)) {
5621                        // If this is a system app, we can at least delete its
5622                        // current data so the application will still work.
5623                        int ret = removeDataDirsLI(pkgName);
5624                        if (ret >= 0) {
5625                            // TODO: Kill the processes first
5626                            // Old data gone!
5627                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5628                                    ? "System package " : "Third party package ";
5629                            String msg = prefix + pkg.packageName
5630                                    + " has changed from uid: "
5631                                    + currentUid + " to "
5632                                    + pkg.applicationInfo.uid + "; old data erased";
5633                            reportSettingsProblem(Log.WARN, msg);
5634                            recovered = true;
5635
5636                            // And now re-install the app.
5637                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5638                                                   pkg.applicationInfo.seinfo);
5639                            if (ret == -1) {
5640                                // Ack should not happen!
5641                                msg = prefix + pkg.packageName
5642                                        + " could not have data directory re-created after delete.";
5643                                reportSettingsProblem(Log.WARN, msg);
5644                                throw new PackageManagerException(
5645                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5646                            }
5647                        }
5648                        if (!recovered) {
5649                            mHasSystemUidErrors = true;
5650                        }
5651                    } else if (!recovered) {
5652                        // If we allow this install to proceed, we will be broken.
5653                        // Abort, abort!
5654                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5655                                "scanPackageLI");
5656                    }
5657                    if (!recovered) {
5658                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5659                            + pkg.applicationInfo.uid + "/fs_"
5660                            + currentUid;
5661                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5662                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5663                        String msg = "Package " + pkg.packageName
5664                                + " has mismatched uid: "
5665                                + currentUid + " on disk, "
5666                                + pkg.applicationInfo.uid + " in settings";
5667                        // writer
5668                        synchronized (mPackages) {
5669                            mSettings.mReadMessages.append(msg);
5670                            mSettings.mReadMessages.append('\n');
5671                            uidError = true;
5672                            if (!pkgSetting.uidError) {
5673                                reportSettingsProblem(Log.ERROR, msg);
5674                            }
5675                        }
5676                    }
5677                }
5678                pkg.applicationInfo.dataDir = dataPath.getPath();
5679                if (mShouldRestoreconData) {
5680                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5681                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5682                                pkg.applicationInfo.uid);
5683                }
5684            } else {
5685                if (DEBUG_PACKAGE_SCANNING) {
5686                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5687                        Log.v(TAG, "Want this data dir: " + dataPath);
5688                }
5689                //invoke installer to do the actual installation
5690                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5691                                           pkg.applicationInfo.seinfo);
5692                if (ret < 0) {
5693                    // Error from installer
5694                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5695                            "Unable to create data dirs [errorCode=" + ret + "]");
5696                }
5697
5698                if (dataPath.exists()) {
5699                    pkg.applicationInfo.dataDir = dataPath.getPath();
5700                } else {
5701                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5702                    pkg.applicationInfo.dataDir = null;
5703                }
5704            }
5705
5706            pkgSetting.uidError = uidError;
5707        }
5708
5709        final String path = scanFile.getPath();
5710        final String codePath = pkg.applicationInfo.getCodePath();
5711        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5712        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5713            setBundledAppAbisAndRoots(pkg, pkgSetting);
5714
5715            // If we haven't found any native libraries for the app, check if it has
5716            // renderscript code. We'll need to force the app to 32 bit if it has
5717            // renderscript bitcode.
5718            if (pkg.applicationInfo.primaryCpuAbi == null
5719                    && pkg.applicationInfo.secondaryCpuAbi == null
5720                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5721                NativeLibraryHelper.Handle handle = null;
5722                try {
5723                    handle = NativeLibraryHelper.Handle.create(scanFile);
5724                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5725                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5726                    }
5727                } catch (IOException ioe) {
5728                    Slog.w(TAG, "Error scanning system app : " + ioe);
5729                } finally {
5730                    IoUtils.closeQuietly(handle);
5731                }
5732            }
5733
5734            setNativeLibraryPaths(pkg);
5735        } else {
5736            // TODO: We can probably be smarter about this stuff. For installed apps,
5737            // we can calculate this information at install time once and for all. For
5738            // system apps, we can probably assume that this information doesn't change
5739            // after the first boot scan. As things stand, we do lots of unnecessary work.
5740
5741            // Give ourselves some initial paths; we'll come back for another
5742            // pass once we've determined ABI below.
5743            setNativeLibraryPaths(pkg);
5744
5745            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5746            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5747            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5748
5749            NativeLibraryHelper.Handle handle = null;
5750            try {
5751                handle = NativeLibraryHelper.Handle.create(scanFile);
5752                // TODO(multiArch): This can be null for apps that didn't go through the
5753                // usual installation process. We can calculate it again, like we
5754                // do during install time.
5755                //
5756                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5757                // unnecessary.
5758                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5759
5760                // Null out the abis so that they can be recalculated.
5761                pkg.applicationInfo.primaryCpuAbi = null;
5762                pkg.applicationInfo.secondaryCpuAbi = null;
5763                if (isMultiArch(pkg.applicationInfo)) {
5764                    // Warn if we've set an abiOverride for multi-lib packages..
5765                    // By definition, we need to copy both 32 and 64 bit libraries for
5766                    // such packages.
5767                    if (pkg.cpuAbiOverride != null
5768                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5769                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5770                    }
5771
5772                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5773                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5774                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5775                        if (isAsec) {
5776                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5777                        } else {
5778                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5779                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5780                                    useIsaSpecificSubdirs);
5781                        }
5782                    }
5783
5784                    maybeThrowExceptionForMultiArchCopy(
5785                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5786
5787                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5788                        if (isAsec) {
5789                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5790                        } else {
5791                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5792                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5793                                    useIsaSpecificSubdirs);
5794                        }
5795                    }
5796
5797                    maybeThrowExceptionForMultiArchCopy(
5798                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5799
5800                    if (abi64 >= 0) {
5801                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5802                    }
5803
5804                    if (abi32 >= 0) {
5805                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5806                        if (abi64 >= 0) {
5807                            pkg.applicationInfo.secondaryCpuAbi = abi;
5808                        } else {
5809                            pkg.applicationInfo.primaryCpuAbi = abi;
5810                        }
5811                    }
5812                } else {
5813                    String[] abiList = (cpuAbiOverride != null) ?
5814                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5815
5816                    // Enable gross and lame hacks for apps that are built with old
5817                    // SDK tools. We must scan their APKs for renderscript bitcode and
5818                    // not launch them if it's present. Don't bother checking on devices
5819                    // that don't have 64 bit support.
5820                    boolean needsRenderScriptOverride = false;
5821                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5822                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5823                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5824                        needsRenderScriptOverride = true;
5825                    }
5826
5827                    final int copyRet;
5828                    if (isAsec) {
5829                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5830                    } else {
5831                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5832                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5833                    }
5834
5835                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5836                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5837                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5838                    }
5839
5840                    if (copyRet >= 0) {
5841                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5842                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5843                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5844                    } else if (needsRenderScriptOverride) {
5845                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5846                    }
5847                }
5848            } catch (IOException ioe) {
5849                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5850            } finally {
5851                IoUtils.closeQuietly(handle);
5852            }
5853
5854            // Now that we've calculated the ABIs and determined if it's an internal app,
5855            // we will go ahead and populate the nativeLibraryPath.
5856            setNativeLibraryPaths(pkg);
5857
5858            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5859            final int[] userIds = sUserManager.getUserIds();
5860            synchronized (mInstallLock) {
5861                // Create a native library symlink only if we have native libraries
5862                // and if the native libraries are 32 bit libraries. We do not provide
5863                // this symlink for 64 bit libraries.
5864                if (pkg.applicationInfo.primaryCpuAbi != null &&
5865                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5866                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5867                    for (int userId : userIds) {
5868                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5869                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5870                                    "Failed linking native library dir (user=" + userId + ")");
5871                        }
5872                    }
5873                }
5874            }
5875        }
5876
5877        // This is a special case for the "system" package, where the ABI is
5878        // dictated by the zygote configuration (and init.rc). We should keep track
5879        // of this ABI so that we can deal with "normal" applications that run under
5880        // the same UID correctly.
5881        if (mPlatformPackage == pkg) {
5882            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5883                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5884        }
5885
5886        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5887        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5888        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5889        // Copy the derived override back to the parsed package, so that we can
5890        // update the package settings accordingly.
5891        pkg.cpuAbiOverride = cpuAbiOverride;
5892
5893        if (DEBUG_ABI_SELECTION) {
5894            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5895                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5896                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5897        }
5898
5899        // Push the derived path down into PackageSettings so we know what to
5900        // clean up at uninstall time.
5901        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5902
5903        if (DEBUG_ABI_SELECTION) {
5904            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5905                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5906                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5907        }
5908
5909        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5910            // We don't do this here during boot because we can do it all
5911            // at once after scanning all existing packages.
5912            //
5913            // We also do this *before* we perform dexopt on this package, so that
5914            // we can avoid redundant dexopts, and also to make sure we've got the
5915            // code and package path correct.
5916            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5917                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5918        }
5919
5920        if ((scanFlags & SCAN_NO_DEX) == 0) {
5921            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5922                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5923                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5924            }
5925        }
5926
5927        if (mFactoryTest && pkg.requestedPermissions.contains(
5928                android.Manifest.permission.FACTORY_TEST)) {
5929            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5930        }
5931
5932        ArrayList<PackageParser.Package> clientLibPkgs = null;
5933
5934        // writer
5935        synchronized (mPackages) {
5936            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5937                // Only system apps can add new shared libraries.
5938                if (pkg.libraryNames != null) {
5939                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5940                        String name = pkg.libraryNames.get(i);
5941                        boolean allowed = false;
5942                        if (isUpdatedSystemApp(pkg)) {
5943                            // New library entries can only be added through the
5944                            // system image.  This is important to get rid of a lot
5945                            // of nasty edge cases: for example if we allowed a non-
5946                            // system update of the app to add a library, then uninstalling
5947                            // the update would make the library go away, and assumptions
5948                            // we made such as through app install filtering would now
5949                            // have allowed apps on the device which aren't compatible
5950                            // with it.  Better to just have the restriction here, be
5951                            // conservative, and create many fewer cases that can negatively
5952                            // impact the user experience.
5953                            final PackageSetting sysPs = mSettings
5954                                    .getDisabledSystemPkgLPr(pkg.packageName);
5955                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5956                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5957                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5958                                        allowed = true;
5959                                        allowed = true;
5960                                        break;
5961                                    }
5962                                }
5963                            }
5964                        } else {
5965                            allowed = true;
5966                        }
5967                        if (allowed) {
5968                            if (!mSharedLibraries.containsKey(name)) {
5969                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5970                            } else if (!name.equals(pkg.packageName)) {
5971                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5972                                        + name + " already exists; skipping");
5973                            }
5974                        } else {
5975                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5976                                    + name + " that is not declared on system image; skipping");
5977                        }
5978                    }
5979                    if ((scanFlags&SCAN_BOOTING) == 0) {
5980                        // If we are not booting, we need to update any applications
5981                        // that are clients of our shared library.  If we are booting,
5982                        // this will all be done once the scan is complete.
5983                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5984                    }
5985                }
5986            }
5987        }
5988
5989        // We also need to dexopt any apps that are dependent on this library.  Note that
5990        // if these fail, we should abort the install since installing the library will
5991        // result in some apps being broken.
5992        if (clientLibPkgs != null) {
5993            if ((scanFlags & SCAN_NO_DEX) == 0) {
5994                for (int i = 0; i < clientLibPkgs.size(); i++) {
5995                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5996                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5997                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5998                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5999                                "scanPackageLI failed to dexopt clientLibPkgs");
6000                    }
6001                }
6002            }
6003        }
6004
6005        // Request the ActivityManager to kill the process(only for existing packages)
6006        // so that we do not end up in a confused state while the user is still using the older
6007        // version of the application while the new one gets installed.
6008        if ((scanFlags & SCAN_REPLACING) != 0) {
6009            killApplication(pkg.applicationInfo.packageName,
6010                        pkg.applicationInfo.uid, "update pkg");
6011        }
6012
6013        // Also need to kill any apps that are dependent on the library.
6014        if (clientLibPkgs != null) {
6015            for (int i=0; i<clientLibPkgs.size(); i++) {
6016                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6017                killApplication(clientPkg.applicationInfo.packageName,
6018                        clientPkg.applicationInfo.uid, "update lib");
6019            }
6020        }
6021
6022        // writer
6023        synchronized (mPackages) {
6024            // We don't expect installation to fail beyond this point
6025
6026            // Add the new setting to mSettings
6027            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6028            // Add the new setting to mPackages
6029            mPackages.put(pkg.applicationInfo.packageName, pkg);
6030            // Make sure we don't accidentally delete its data.
6031            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6032            while (iter.hasNext()) {
6033                PackageCleanItem item = iter.next();
6034                if (pkgName.equals(item.packageName)) {
6035                    iter.remove();
6036                }
6037            }
6038
6039            // Take care of first install / last update times.
6040            if (currentTime != 0) {
6041                if (pkgSetting.firstInstallTime == 0) {
6042                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6043                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6044                    pkgSetting.lastUpdateTime = currentTime;
6045                }
6046            } else if (pkgSetting.firstInstallTime == 0) {
6047                // We need *something*.  Take time time stamp of the file.
6048                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6049            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6050                if (scanFileTime != pkgSetting.timeStamp) {
6051                    // A package on the system image has changed; consider this
6052                    // to be an update.
6053                    pkgSetting.lastUpdateTime = scanFileTime;
6054                }
6055            }
6056
6057            // Add the package's KeySets to the global KeySetManagerService
6058            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6059            try {
6060                // Old KeySetData no longer valid.
6061                ksms.removeAppKeySetDataLPw(pkg.packageName);
6062                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6063                if (pkg.mKeySetMapping != null) {
6064                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
6065                            pkg.mKeySetMapping.entrySet()) {
6066                        if (entry.getValue() != null) {
6067                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
6068                                                          entry.getValue(), entry.getKey());
6069                        }
6070                    }
6071                    if (pkg.mUpgradeKeySets != null) {
6072                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
6073                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
6074                        }
6075                    }
6076                }
6077            } catch (NullPointerException e) {
6078                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6079            } catch (IllegalArgumentException e) {
6080                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6081            }
6082
6083            int N = pkg.providers.size();
6084            StringBuilder r = null;
6085            int i;
6086            for (i=0; i<N; i++) {
6087                PackageParser.Provider p = pkg.providers.get(i);
6088                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6089                        p.info.processName, pkg.applicationInfo.uid);
6090                mProviders.addProvider(p);
6091                p.syncable = p.info.isSyncable;
6092                if (p.info.authority != null) {
6093                    String names[] = p.info.authority.split(";");
6094                    p.info.authority = null;
6095                    for (int j = 0; j < names.length; j++) {
6096                        if (j == 1 && p.syncable) {
6097                            // We only want the first authority for a provider to possibly be
6098                            // syncable, so if we already added this provider using a different
6099                            // authority clear the syncable flag. We copy the provider before
6100                            // changing it because the mProviders object contains a reference
6101                            // to a provider that we don't want to change.
6102                            // Only do this for the second authority since the resulting provider
6103                            // object can be the same for all future authorities for this provider.
6104                            p = new PackageParser.Provider(p);
6105                            p.syncable = false;
6106                        }
6107                        if (!mProvidersByAuthority.containsKey(names[j])) {
6108                            mProvidersByAuthority.put(names[j], p);
6109                            if (p.info.authority == null) {
6110                                p.info.authority = names[j];
6111                            } else {
6112                                p.info.authority = p.info.authority + ";" + names[j];
6113                            }
6114                            if (DEBUG_PACKAGE_SCANNING) {
6115                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6116                                    Log.d(TAG, "Registered content provider: " + names[j]
6117                                            + ", className = " + p.info.name + ", isSyncable = "
6118                                            + p.info.isSyncable);
6119                            }
6120                        } else {
6121                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6122                            Slog.w(TAG, "Skipping provider name " + names[j] +
6123                                    " (in package " + pkg.applicationInfo.packageName +
6124                                    "): name already used by "
6125                                    + ((other != null && other.getComponentName() != null)
6126                                            ? other.getComponentName().getPackageName() : "?"));
6127                        }
6128                    }
6129                }
6130                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6131                    if (r == null) {
6132                        r = new StringBuilder(256);
6133                    } else {
6134                        r.append(' ');
6135                    }
6136                    r.append(p.info.name);
6137                }
6138            }
6139            if (r != null) {
6140                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6141            }
6142
6143            N = pkg.services.size();
6144            r = null;
6145            for (i=0; i<N; i++) {
6146                PackageParser.Service s = pkg.services.get(i);
6147                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6148                        s.info.processName, pkg.applicationInfo.uid);
6149                mServices.addService(s);
6150                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6151                    if (r == null) {
6152                        r = new StringBuilder(256);
6153                    } else {
6154                        r.append(' ');
6155                    }
6156                    r.append(s.info.name);
6157                }
6158            }
6159            if (r != null) {
6160                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6161            }
6162
6163            N = pkg.receivers.size();
6164            r = null;
6165            for (i=0; i<N; i++) {
6166                PackageParser.Activity a = pkg.receivers.get(i);
6167                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6168                        a.info.processName, pkg.applicationInfo.uid);
6169                mReceivers.addActivity(a, "receiver");
6170                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6171                    if (r == null) {
6172                        r = new StringBuilder(256);
6173                    } else {
6174                        r.append(' ');
6175                    }
6176                    r.append(a.info.name);
6177                }
6178            }
6179            if (r != null) {
6180                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6181            }
6182
6183            N = pkg.activities.size();
6184            r = null;
6185            for (i=0; i<N; i++) {
6186                PackageParser.Activity a = pkg.activities.get(i);
6187                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6188                        a.info.processName, pkg.applicationInfo.uid);
6189                mActivities.addActivity(a, "activity");
6190                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6191                    if (r == null) {
6192                        r = new StringBuilder(256);
6193                    } else {
6194                        r.append(' ');
6195                    }
6196                    r.append(a.info.name);
6197                }
6198            }
6199            if (r != null) {
6200                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6201            }
6202
6203            N = pkg.permissionGroups.size();
6204            r = null;
6205            for (i=0; i<N; i++) {
6206                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6207                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6208                if (cur == null) {
6209                    mPermissionGroups.put(pg.info.name, pg);
6210                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6211                        if (r == null) {
6212                            r = new StringBuilder(256);
6213                        } else {
6214                            r.append(' ');
6215                        }
6216                        r.append(pg.info.name);
6217                    }
6218                } else {
6219                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6220                            + pg.info.packageName + " ignored: original from "
6221                            + cur.info.packageName);
6222                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6223                        if (r == null) {
6224                            r = new StringBuilder(256);
6225                        } else {
6226                            r.append(' ');
6227                        }
6228                        r.append("DUP:");
6229                        r.append(pg.info.name);
6230                    }
6231                }
6232            }
6233            if (r != null) {
6234                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6235            }
6236
6237            N = pkg.permissions.size();
6238            r = null;
6239            for (i=0; i<N; i++) {
6240                PackageParser.Permission p = pkg.permissions.get(i);
6241                ArrayMap<String, BasePermission> permissionMap =
6242                        p.tree ? mSettings.mPermissionTrees
6243                        : mSettings.mPermissions;
6244                p.group = mPermissionGroups.get(p.info.group);
6245                if (p.info.group == null || p.group != null) {
6246                    BasePermission bp = permissionMap.get(p.info.name);
6247
6248                    // Allow system apps to redefine non-system permissions
6249                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6250                        final boolean currentOwnerIsSystem = (bp.perm != null
6251                                && isSystemApp(bp.perm.owner));
6252                        if (isSystemApp(p.owner)) {
6253                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6254                                // It's a built-in permission and no owner, take ownership now
6255                                bp.packageSetting = pkgSetting;
6256                                bp.perm = p;
6257                                bp.uid = pkg.applicationInfo.uid;
6258                                bp.sourcePackage = p.info.packageName;
6259                            } else if (!currentOwnerIsSystem) {
6260                                String msg = "New decl " + p.owner + " of permission  "
6261                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6262                                reportSettingsProblem(Log.WARN, msg);
6263                                bp = null;
6264                            }
6265                        }
6266                    }
6267
6268                    if (bp == null) {
6269                        bp = new BasePermission(p.info.name, p.info.packageName,
6270                                BasePermission.TYPE_NORMAL);
6271                        permissionMap.put(p.info.name, bp);
6272                    }
6273
6274                    if (bp.perm == null) {
6275                        if (bp.sourcePackage == null
6276                                || bp.sourcePackage.equals(p.info.packageName)) {
6277                            BasePermission tree = findPermissionTreeLP(p.info.name);
6278                            if (tree == null
6279                                    || tree.sourcePackage.equals(p.info.packageName)) {
6280                                bp.packageSetting = pkgSetting;
6281                                bp.perm = p;
6282                                bp.uid = pkg.applicationInfo.uid;
6283                                bp.sourcePackage = p.info.packageName;
6284                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6285                                    if (r == null) {
6286                                        r = new StringBuilder(256);
6287                                    } else {
6288                                        r.append(' ');
6289                                    }
6290                                    r.append(p.info.name);
6291                                }
6292                            } else {
6293                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6294                                        + p.info.packageName + " ignored: base tree "
6295                                        + tree.name + " is from package "
6296                                        + tree.sourcePackage);
6297                            }
6298                        } else {
6299                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6300                                    + p.info.packageName + " ignored: original from "
6301                                    + bp.sourcePackage);
6302                        }
6303                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6304                        if (r == null) {
6305                            r = new StringBuilder(256);
6306                        } else {
6307                            r.append(' ');
6308                        }
6309                        r.append("DUP:");
6310                        r.append(p.info.name);
6311                    }
6312                    if (bp.perm == p) {
6313                        bp.protectionLevel = p.info.protectionLevel;
6314                    }
6315                } else {
6316                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6317                            + p.info.packageName + " ignored: no group "
6318                            + p.group);
6319                }
6320            }
6321            if (r != null) {
6322                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6323            }
6324
6325            N = pkg.instrumentation.size();
6326            r = null;
6327            for (i=0; i<N; i++) {
6328                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6329                a.info.packageName = pkg.applicationInfo.packageName;
6330                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6331                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6332                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6333                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6334                a.info.dataDir = pkg.applicationInfo.dataDir;
6335
6336                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6337                // need other information about the application, like the ABI and what not ?
6338                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6339                mInstrumentation.put(a.getComponentName(), a);
6340                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6341                    if (r == null) {
6342                        r = new StringBuilder(256);
6343                    } else {
6344                        r.append(' ');
6345                    }
6346                    r.append(a.info.name);
6347                }
6348            }
6349            if (r != null) {
6350                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6351            }
6352
6353            if (pkg.protectedBroadcasts != null) {
6354                N = pkg.protectedBroadcasts.size();
6355                for (i=0; i<N; i++) {
6356                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6357                }
6358            }
6359
6360            pkgSetting.setTimeStamp(scanFileTime);
6361
6362            // Create idmap files for pairs of (packages, overlay packages).
6363            // Note: "android", ie framework-res.apk, is handled by native layers.
6364            if (pkg.mOverlayTarget != null) {
6365                // This is an overlay package.
6366                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6367                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6368                        mOverlays.put(pkg.mOverlayTarget,
6369                                new ArrayMap<String, PackageParser.Package>());
6370                    }
6371                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6372                    map.put(pkg.packageName, pkg);
6373                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6374                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6375                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6376                                "scanPackageLI failed to createIdmap");
6377                    }
6378                }
6379            } else if (mOverlays.containsKey(pkg.packageName) &&
6380                    !pkg.packageName.equals("android")) {
6381                // This is a regular package, with one or more known overlay packages.
6382                createIdmapsForPackageLI(pkg);
6383            }
6384        }
6385
6386        return pkg;
6387    }
6388
6389    /**
6390     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6391     * i.e, so that all packages can be run inside a single process if required.
6392     *
6393     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6394     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6395     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6396     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6397     * updating a package that belongs to a shared user.
6398     *
6399     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6400     * adds unnecessary complexity.
6401     */
6402    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6403            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6404        String requiredInstructionSet = null;
6405        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6406            requiredInstructionSet = VMRuntime.getInstructionSet(
6407                     scannedPackage.applicationInfo.primaryCpuAbi);
6408        }
6409
6410        PackageSetting requirer = null;
6411        for (PackageSetting ps : packagesForUser) {
6412            // If packagesForUser contains scannedPackage, we skip it. This will happen
6413            // when scannedPackage is an update of an existing package. Without this check,
6414            // we will never be able to change the ABI of any package belonging to a shared
6415            // user, even if it's compatible with other packages.
6416            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6417                if (ps.primaryCpuAbiString == null) {
6418                    continue;
6419                }
6420
6421                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6422                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6423                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6424                    // this but there's not much we can do.
6425                    String errorMessage = "Instruction set mismatch, "
6426                            + ((requirer == null) ? "[caller]" : requirer)
6427                            + " requires " + requiredInstructionSet + " whereas " + ps
6428                            + " requires " + instructionSet;
6429                    Slog.w(TAG, errorMessage);
6430                }
6431
6432                if (requiredInstructionSet == null) {
6433                    requiredInstructionSet = instructionSet;
6434                    requirer = ps;
6435                }
6436            }
6437        }
6438
6439        if (requiredInstructionSet != null) {
6440            String adjustedAbi;
6441            if (requirer != null) {
6442                // requirer != null implies that either scannedPackage was null or that scannedPackage
6443                // did not require an ABI, in which case we have to adjust scannedPackage to match
6444                // the ABI of the set (which is the same as requirer's ABI)
6445                adjustedAbi = requirer.primaryCpuAbiString;
6446                if (scannedPackage != null) {
6447                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6448                }
6449            } else {
6450                // requirer == null implies that we're updating all ABIs in the set to
6451                // match scannedPackage.
6452                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6453            }
6454
6455            for (PackageSetting ps : packagesForUser) {
6456                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6457                    if (ps.primaryCpuAbiString != null) {
6458                        continue;
6459                    }
6460
6461                    ps.primaryCpuAbiString = adjustedAbi;
6462                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6463                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6464                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6465
6466                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6467                                deferDexOpt, true) == DEX_OPT_FAILED) {
6468                            ps.primaryCpuAbiString = null;
6469                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6470                            return;
6471                        } else {
6472                            mInstaller.rmdex(ps.codePathString,
6473                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6474                        }
6475                    }
6476                }
6477            }
6478        }
6479    }
6480
6481    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6482        synchronized (mPackages) {
6483            mResolverReplaced = true;
6484            // Set up information for custom user intent resolution activity.
6485            mResolveActivity.applicationInfo = pkg.applicationInfo;
6486            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6487            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6488            mResolveActivity.processName = pkg.applicationInfo.packageName;
6489            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6490            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6491                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6492            mResolveActivity.theme = 0;
6493            mResolveActivity.exported = true;
6494            mResolveActivity.enabled = true;
6495            mResolveInfo.activityInfo = mResolveActivity;
6496            mResolveInfo.priority = 0;
6497            mResolveInfo.preferredOrder = 0;
6498            mResolveInfo.match = 0;
6499            mResolveComponentName = mCustomResolverComponentName;
6500            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6501                    mResolveComponentName);
6502        }
6503    }
6504
6505    private static String calculateBundledApkRoot(final String codePathString) {
6506        final File codePath = new File(codePathString);
6507        final File codeRoot;
6508        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6509            codeRoot = Environment.getRootDirectory();
6510        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6511            codeRoot = Environment.getOemDirectory();
6512        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6513            codeRoot = Environment.getVendorDirectory();
6514        } else {
6515            // Unrecognized code path; take its top real segment as the apk root:
6516            // e.g. /something/app/blah.apk => /something
6517            try {
6518                File f = codePath.getCanonicalFile();
6519                File parent = f.getParentFile();    // non-null because codePath is a file
6520                File tmp;
6521                while ((tmp = parent.getParentFile()) != null) {
6522                    f = parent;
6523                    parent = tmp;
6524                }
6525                codeRoot = f;
6526                Slog.w(TAG, "Unrecognized code path "
6527                        + codePath + " - using " + codeRoot);
6528            } catch (IOException e) {
6529                // Can't canonicalize the code path -- shenanigans?
6530                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6531                return Environment.getRootDirectory().getPath();
6532            }
6533        }
6534        return codeRoot.getPath();
6535    }
6536
6537    /**
6538     * Derive and set the location of native libraries for the given package,
6539     * which varies depending on where and how the package was installed.
6540     */
6541    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6542        final ApplicationInfo info = pkg.applicationInfo;
6543        final String codePath = pkg.codePath;
6544        final File codeFile = new File(codePath);
6545        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6546        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6547
6548        info.nativeLibraryRootDir = null;
6549        info.nativeLibraryRootRequiresIsa = false;
6550        info.nativeLibraryDir = null;
6551        info.secondaryNativeLibraryDir = null;
6552
6553        if (isApkFile(codeFile)) {
6554            // Monolithic install
6555            if (bundledApp) {
6556                // If "/system/lib64/apkname" exists, assume that is the per-package
6557                // native library directory to use; otherwise use "/system/lib/apkname".
6558                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6559                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6560                        getPrimaryInstructionSet(info));
6561
6562                // This is a bundled system app so choose the path based on the ABI.
6563                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6564                // is just the default path.
6565                final String apkName = deriveCodePathName(codePath);
6566                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6567                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6568                        apkName).getAbsolutePath();
6569
6570                if (info.secondaryCpuAbi != null) {
6571                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6572                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6573                            secondaryLibDir, apkName).getAbsolutePath();
6574                }
6575            } else if (asecApp) {
6576                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6577                        .getAbsolutePath();
6578            } else {
6579                final String apkName = deriveCodePathName(codePath);
6580                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6581                        .getAbsolutePath();
6582            }
6583
6584            info.nativeLibraryRootRequiresIsa = false;
6585            info.nativeLibraryDir = info.nativeLibraryRootDir;
6586        } else {
6587            // Cluster install
6588            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6589            info.nativeLibraryRootRequiresIsa = true;
6590
6591            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6592                    getPrimaryInstructionSet(info)).getAbsolutePath();
6593
6594            if (info.secondaryCpuAbi != null) {
6595                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6596                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6597            }
6598        }
6599    }
6600
6601    /**
6602     * Calculate the abis and roots for a bundled app. These can uniquely
6603     * be determined from the contents of the system partition, i.e whether
6604     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6605     * of this information, and instead assume that the system was built
6606     * sensibly.
6607     */
6608    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6609                                           PackageSetting pkgSetting) {
6610        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6611
6612        // If "/system/lib64/apkname" exists, assume that is the per-package
6613        // native library directory to use; otherwise use "/system/lib/apkname".
6614        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6615        setBundledAppAbi(pkg, apkRoot, apkName);
6616        // pkgSetting might be null during rescan following uninstall of updates
6617        // to a bundled app, so accommodate that possibility.  The settings in
6618        // that case will be established later from the parsed package.
6619        //
6620        // If the settings aren't null, sync them up with what we've just derived.
6621        // note that apkRoot isn't stored in the package settings.
6622        if (pkgSetting != null) {
6623            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6624            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6625        }
6626    }
6627
6628    /**
6629     * Deduces the ABI of a bundled app and sets the relevant fields on the
6630     * parsed pkg object.
6631     *
6632     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6633     *        under which system libraries are installed.
6634     * @param apkName the name of the installed package.
6635     */
6636    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6637        final File codeFile = new File(pkg.codePath);
6638
6639        final boolean has64BitLibs;
6640        final boolean has32BitLibs;
6641        if (isApkFile(codeFile)) {
6642            // Monolithic install
6643            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6644            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6645        } else {
6646            // Cluster install
6647            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6648            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6649                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6650                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6651                has64BitLibs = (new File(rootDir, isa)).exists();
6652            } else {
6653                has64BitLibs = false;
6654            }
6655            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6656                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6657                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6658                has32BitLibs = (new File(rootDir, isa)).exists();
6659            } else {
6660                has32BitLibs = false;
6661            }
6662        }
6663
6664        if (has64BitLibs && !has32BitLibs) {
6665            // The package has 64 bit libs, but not 32 bit libs. Its primary
6666            // ABI should be 64 bit. We can safely assume here that the bundled
6667            // native libraries correspond to the most preferred ABI in the list.
6668
6669            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6670            pkg.applicationInfo.secondaryCpuAbi = null;
6671        } else if (has32BitLibs && !has64BitLibs) {
6672            // The package has 32 bit libs but not 64 bit libs. Its primary
6673            // ABI should be 32 bit.
6674
6675            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6676            pkg.applicationInfo.secondaryCpuAbi = null;
6677        } else if (has32BitLibs && has64BitLibs) {
6678            // The application has both 64 and 32 bit bundled libraries. We check
6679            // here that the app declares multiArch support, and warn if it doesn't.
6680            //
6681            // We will be lenient here and record both ABIs. The primary will be the
6682            // ABI that's higher on the list, i.e, a device that's configured to prefer
6683            // 64 bit apps will see a 64 bit primary ABI,
6684
6685            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6686                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6687            }
6688
6689            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6690                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6691                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6692            } else {
6693                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6694                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6695            }
6696        } else {
6697            pkg.applicationInfo.primaryCpuAbi = null;
6698            pkg.applicationInfo.secondaryCpuAbi = null;
6699        }
6700    }
6701
6702    private void killApplication(String pkgName, int appId, String reason) {
6703        // Request the ActivityManager to kill the process(only for existing packages)
6704        // so that we do not end up in a confused state while the user is still using the older
6705        // version of the application while the new one gets installed.
6706        IActivityManager am = ActivityManagerNative.getDefault();
6707        if (am != null) {
6708            try {
6709                am.killApplicationWithAppId(pkgName, appId, reason);
6710            } catch (RemoteException e) {
6711            }
6712        }
6713    }
6714
6715    void removePackageLI(PackageSetting ps, boolean chatty) {
6716        if (DEBUG_INSTALL) {
6717            if (chatty)
6718                Log.d(TAG, "Removing package " + ps.name);
6719        }
6720
6721        // writer
6722        synchronized (mPackages) {
6723            mPackages.remove(ps.name);
6724            final PackageParser.Package pkg = ps.pkg;
6725            if (pkg != null) {
6726                cleanPackageDataStructuresLILPw(pkg, chatty);
6727            }
6728        }
6729    }
6730
6731    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6732        if (DEBUG_INSTALL) {
6733            if (chatty)
6734                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6735        }
6736
6737        // writer
6738        synchronized (mPackages) {
6739            mPackages.remove(pkg.applicationInfo.packageName);
6740            cleanPackageDataStructuresLILPw(pkg, chatty);
6741        }
6742    }
6743
6744    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6745        int N = pkg.providers.size();
6746        StringBuilder r = null;
6747        int i;
6748        for (i=0; i<N; i++) {
6749            PackageParser.Provider p = pkg.providers.get(i);
6750            mProviders.removeProvider(p);
6751            if (p.info.authority == null) {
6752
6753                /* There was another ContentProvider with this authority when
6754                 * this app was installed so this authority is null,
6755                 * Ignore it as we don't have to unregister the provider.
6756                 */
6757                continue;
6758            }
6759            String names[] = p.info.authority.split(";");
6760            for (int j = 0; j < names.length; j++) {
6761                if (mProvidersByAuthority.get(names[j]) == p) {
6762                    mProvidersByAuthority.remove(names[j]);
6763                    if (DEBUG_REMOVE) {
6764                        if (chatty)
6765                            Log.d(TAG, "Unregistered content provider: " + names[j]
6766                                    + ", className = " + p.info.name + ", isSyncable = "
6767                                    + p.info.isSyncable);
6768                    }
6769                }
6770            }
6771            if (DEBUG_REMOVE && chatty) {
6772                if (r == null) {
6773                    r = new StringBuilder(256);
6774                } else {
6775                    r.append(' ');
6776                }
6777                r.append(p.info.name);
6778            }
6779        }
6780        if (r != null) {
6781            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6782        }
6783
6784        N = pkg.services.size();
6785        r = null;
6786        for (i=0; i<N; i++) {
6787            PackageParser.Service s = pkg.services.get(i);
6788            mServices.removeService(s);
6789            if (chatty) {
6790                if (r == null) {
6791                    r = new StringBuilder(256);
6792                } else {
6793                    r.append(' ');
6794                }
6795                r.append(s.info.name);
6796            }
6797        }
6798        if (r != null) {
6799            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6800        }
6801
6802        N = pkg.receivers.size();
6803        r = null;
6804        for (i=0; i<N; i++) {
6805            PackageParser.Activity a = pkg.receivers.get(i);
6806            mReceivers.removeActivity(a, "receiver");
6807            if (DEBUG_REMOVE && chatty) {
6808                if (r == null) {
6809                    r = new StringBuilder(256);
6810                } else {
6811                    r.append(' ');
6812                }
6813                r.append(a.info.name);
6814            }
6815        }
6816        if (r != null) {
6817            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6818        }
6819
6820        N = pkg.activities.size();
6821        r = null;
6822        for (i=0; i<N; i++) {
6823            PackageParser.Activity a = pkg.activities.get(i);
6824            mActivities.removeActivity(a, "activity");
6825            if (DEBUG_REMOVE && chatty) {
6826                if (r == null) {
6827                    r = new StringBuilder(256);
6828                } else {
6829                    r.append(' ');
6830                }
6831                r.append(a.info.name);
6832            }
6833        }
6834        if (r != null) {
6835            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6836        }
6837
6838        N = pkg.permissions.size();
6839        r = null;
6840        for (i=0; i<N; i++) {
6841            PackageParser.Permission p = pkg.permissions.get(i);
6842            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6843            if (bp == null) {
6844                bp = mSettings.mPermissionTrees.get(p.info.name);
6845            }
6846            if (bp != null && bp.perm == p) {
6847                bp.perm = null;
6848                if (DEBUG_REMOVE && chatty) {
6849                    if (r == null) {
6850                        r = new StringBuilder(256);
6851                    } else {
6852                        r.append(' ');
6853                    }
6854                    r.append(p.info.name);
6855                }
6856            }
6857            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6858                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6859                if (appOpPerms != null) {
6860                    appOpPerms.remove(pkg.packageName);
6861                }
6862            }
6863        }
6864        if (r != null) {
6865            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6866        }
6867
6868        N = pkg.requestedPermissions.size();
6869        r = null;
6870        for (i=0; i<N; i++) {
6871            String perm = pkg.requestedPermissions.get(i);
6872            BasePermission bp = mSettings.mPermissions.get(perm);
6873            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6874                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6875                if (appOpPerms != null) {
6876                    appOpPerms.remove(pkg.packageName);
6877                    if (appOpPerms.isEmpty()) {
6878                        mAppOpPermissionPackages.remove(perm);
6879                    }
6880                }
6881            }
6882        }
6883        if (r != null) {
6884            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6885        }
6886
6887        N = pkg.instrumentation.size();
6888        r = null;
6889        for (i=0; i<N; i++) {
6890            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6891            mInstrumentation.remove(a.getComponentName());
6892            if (DEBUG_REMOVE && chatty) {
6893                if (r == null) {
6894                    r = new StringBuilder(256);
6895                } else {
6896                    r.append(' ');
6897                }
6898                r.append(a.info.name);
6899            }
6900        }
6901        if (r != null) {
6902            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6903        }
6904
6905        r = null;
6906        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6907            // Only system apps can hold shared libraries.
6908            if (pkg.libraryNames != null) {
6909                for (i=0; i<pkg.libraryNames.size(); i++) {
6910                    String name = pkg.libraryNames.get(i);
6911                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6912                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6913                        mSharedLibraries.remove(name);
6914                        if (DEBUG_REMOVE && chatty) {
6915                            if (r == null) {
6916                                r = new StringBuilder(256);
6917                            } else {
6918                                r.append(' ');
6919                            }
6920                            r.append(name);
6921                        }
6922                    }
6923                }
6924            }
6925        }
6926        if (r != null) {
6927            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6928        }
6929    }
6930
6931    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6932        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6933            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6934                return true;
6935            }
6936        }
6937        return false;
6938    }
6939
6940    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6941    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6942    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6943
6944    private void updatePermissionsLPw(String changingPkg,
6945            PackageParser.Package pkgInfo, int flags) {
6946        // Make sure there are no dangling permission trees.
6947        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6948        while (it.hasNext()) {
6949            final BasePermission bp = it.next();
6950            if (bp.packageSetting == null) {
6951                // We may not yet have parsed the package, so just see if
6952                // we still know about its settings.
6953                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6954            }
6955            if (bp.packageSetting == null) {
6956                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6957                        + " from package " + bp.sourcePackage);
6958                it.remove();
6959            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6960                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6961                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6962                            + " from package " + bp.sourcePackage);
6963                    flags |= UPDATE_PERMISSIONS_ALL;
6964                    it.remove();
6965                }
6966            }
6967        }
6968
6969        // Make sure all dynamic permissions have been assigned to a package,
6970        // and make sure there are no dangling permissions.
6971        it = mSettings.mPermissions.values().iterator();
6972        while (it.hasNext()) {
6973            final BasePermission bp = it.next();
6974            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6975                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6976                        + bp.name + " pkg=" + bp.sourcePackage
6977                        + " info=" + bp.pendingInfo);
6978                if (bp.packageSetting == null && bp.pendingInfo != null) {
6979                    final BasePermission tree = findPermissionTreeLP(bp.name);
6980                    if (tree != null && tree.perm != null) {
6981                        bp.packageSetting = tree.packageSetting;
6982                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6983                                new PermissionInfo(bp.pendingInfo));
6984                        bp.perm.info.packageName = tree.perm.info.packageName;
6985                        bp.perm.info.name = bp.name;
6986                        bp.uid = tree.uid;
6987                    }
6988                }
6989            }
6990            if (bp.packageSetting == null) {
6991                // We may not yet have parsed the package, so just see if
6992                // we still know about its settings.
6993                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6994            }
6995            if (bp.packageSetting == null) {
6996                Slog.w(TAG, "Removing dangling permission: " + bp.name
6997                        + " from package " + bp.sourcePackage);
6998                it.remove();
6999            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7000                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7001                    Slog.i(TAG, "Removing old permission: " + bp.name
7002                            + " from package " + bp.sourcePackage);
7003                    flags |= UPDATE_PERMISSIONS_ALL;
7004                    it.remove();
7005                }
7006            }
7007        }
7008
7009        // Now update the permissions for all packages, in particular
7010        // replace the granted permissions of the system packages.
7011        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7012            for (PackageParser.Package pkg : mPackages.values()) {
7013                if (pkg != pkgInfo) {
7014                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7015                            changingPkg);
7016                }
7017            }
7018        }
7019
7020        if (pkgInfo != null) {
7021            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7022        }
7023    }
7024
7025    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7026            String packageOfInterest) {
7027        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7028        if (ps == null) {
7029            return;
7030        }
7031        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
7032        ArraySet<String> origPermissions = gp.grantedPermissions;
7033        boolean changedPermission = false;
7034
7035        if (replace) {
7036            ps.permissionsFixed = false;
7037            if (gp == ps) {
7038                origPermissions = new ArraySet<String>(gp.grantedPermissions);
7039                gp.grantedPermissions.clear();
7040                gp.gids = mGlobalGids;
7041            }
7042        }
7043
7044        if (gp.gids == null) {
7045            gp.gids = mGlobalGids;
7046        }
7047
7048        final int N = pkg.requestedPermissions.size();
7049        for (int i=0; i<N; i++) {
7050            final String name = pkg.requestedPermissions.get(i);
7051            final boolean required = pkg.requestedPermissionsRequired.get(i);
7052            final BasePermission bp = mSettings.mPermissions.get(name);
7053            if (DEBUG_INSTALL) {
7054                if (gp != ps) {
7055                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7056                }
7057            }
7058
7059            if (bp == null || bp.packageSetting == null) {
7060                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7061                    Slog.w(TAG, "Unknown permission " + name
7062                            + " in package " + pkg.packageName);
7063                }
7064                continue;
7065            }
7066
7067            final String perm = bp.name;
7068            boolean allowed;
7069            boolean allowedSig = false;
7070            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7071                // Keep track of app op permissions.
7072                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7073                if (pkgs == null) {
7074                    pkgs = new ArraySet<>();
7075                    mAppOpPermissionPackages.put(bp.name, pkgs);
7076                }
7077                pkgs.add(pkg.packageName);
7078            }
7079            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7080            if (level == PermissionInfo.PROTECTION_NORMAL
7081                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
7082                // We grant a normal or dangerous permission if any of the following
7083                // are true:
7084                // 1) The permission is required
7085                // 2) The permission is optional, but was granted in the past
7086                // 3) The permission is optional, but was requested by an
7087                //    app in /system (not /data)
7088                //
7089                // Otherwise, reject the permission.
7090                allowed = (required || origPermissions.contains(perm)
7091                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
7092            } else if (bp.packageSetting == null) {
7093                // This permission is invalid; skip it.
7094                allowed = false;
7095            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
7096                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
7097                if (allowed) {
7098                    allowedSig = true;
7099                }
7100            } else {
7101                allowed = false;
7102            }
7103            if (DEBUG_INSTALL) {
7104                if (gp != ps) {
7105                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7106                }
7107            }
7108            if (allowed) {
7109                if (!isSystemApp(ps) && ps.permissionsFixed) {
7110                    // If this is an existing, non-system package, then
7111                    // we can't add any new permissions to it.
7112                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
7113                        // Except...  if this is a permission that was added
7114                        // to the platform (note: need to only do this when
7115                        // updating the platform).
7116                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
7117                    }
7118                }
7119                if (allowed) {
7120                    if (!gp.grantedPermissions.contains(perm)) {
7121                        changedPermission = true;
7122                        gp.grantedPermissions.add(perm);
7123                        gp.gids = appendInts(gp.gids, bp.gids);
7124                    } else if (!ps.haveGids) {
7125                        gp.gids = appendInts(gp.gids, bp.gids);
7126                    }
7127                } else {
7128                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7129                        Slog.w(TAG, "Not granting permission " + perm
7130                                + " to package " + pkg.packageName
7131                                + " because it was previously installed without");
7132                    }
7133                }
7134            } else {
7135                if (gp.grantedPermissions.remove(perm)) {
7136                    changedPermission = true;
7137                    gp.gids = removeInts(gp.gids, bp.gids);
7138                    Slog.i(TAG, "Un-granting permission " + perm
7139                            + " from package " + pkg.packageName
7140                            + " (protectionLevel=" + bp.protectionLevel
7141                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7142                            + ")");
7143                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7144                    // Don't print warning for app op permissions, since it is fine for them
7145                    // not to be granted, there is a UI for the user to decide.
7146                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7147                        Slog.w(TAG, "Not granting permission " + perm
7148                                + " to package " + pkg.packageName
7149                                + " (protectionLevel=" + bp.protectionLevel
7150                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7151                                + ")");
7152                    }
7153                }
7154            }
7155        }
7156
7157        if ((changedPermission || replace) && !ps.permissionsFixed &&
7158                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7159            // This is the first that we have heard about this package, so the
7160            // permissions we have now selected are fixed until explicitly
7161            // changed.
7162            ps.permissionsFixed = true;
7163        }
7164        ps.haveGids = true;
7165    }
7166
7167    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7168        boolean allowed = false;
7169        final int NP = PackageParser.NEW_PERMISSIONS.length;
7170        for (int ip=0; ip<NP; ip++) {
7171            final PackageParser.NewPermissionInfo npi
7172                    = PackageParser.NEW_PERMISSIONS[ip];
7173            if (npi.name.equals(perm)
7174                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7175                allowed = true;
7176                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7177                        + pkg.packageName);
7178                break;
7179            }
7180        }
7181        return allowed;
7182    }
7183
7184    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7185                                          BasePermission bp, ArraySet<String> origPermissions) {
7186        boolean allowed;
7187        allowed = (compareSignatures(
7188                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7189                        == PackageManager.SIGNATURE_MATCH)
7190                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7191                        == PackageManager.SIGNATURE_MATCH);
7192        if (!allowed && (bp.protectionLevel
7193                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7194            if (isSystemApp(pkg)) {
7195                // For updated system applications, a system permission
7196                // is granted only if it had been defined by the original application.
7197                if (isUpdatedSystemApp(pkg)) {
7198                    final PackageSetting sysPs = mSettings
7199                            .getDisabledSystemPkgLPr(pkg.packageName);
7200                    final GrantedPermissions origGp = sysPs.sharedUser != null
7201                            ? sysPs.sharedUser : sysPs;
7202
7203                    if (origGp.grantedPermissions.contains(perm)) {
7204                        // If the original was granted this permission, we take
7205                        // that grant decision as read and propagate it to the
7206                        // update.
7207                        if (sysPs.isPrivileged()) {
7208                            allowed = true;
7209                        }
7210                    } else {
7211                        // The system apk may have been updated with an older
7212                        // version of the one on the data partition, but which
7213                        // granted a new system permission that it didn't have
7214                        // before.  In this case we do want to allow the app to
7215                        // now get the new permission if the ancestral apk is
7216                        // privileged to get it.
7217                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7218                            for (int j=0;
7219                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7220                                if (perm.equals(
7221                                        sysPs.pkg.requestedPermissions.get(j))) {
7222                                    allowed = true;
7223                                    break;
7224                                }
7225                            }
7226                        }
7227                    }
7228                } else {
7229                    allowed = isPrivilegedApp(pkg);
7230                }
7231            }
7232        }
7233        if (!allowed && (bp.protectionLevel
7234                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7235            // For development permissions, a development permission
7236            // is granted only if it was already granted.
7237            allowed = origPermissions.contains(perm);
7238        }
7239        return allowed;
7240    }
7241
7242    final class ActivityIntentResolver
7243            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7244        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7245                boolean defaultOnly, int userId) {
7246            if (!sUserManager.exists(userId)) return null;
7247            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7248            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7249        }
7250
7251        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7252                int userId) {
7253            if (!sUserManager.exists(userId)) return null;
7254            mFlags = flags;
7255            return super.queryIntent(intent, resolvedType,
7256                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7257        }
7258
7259        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7260                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7261            if (!sUserManager.exists(userId)) return null;
7262            if (packageActivities == null) {
7263                return null;
7264            }
7265            mFlags = flags;
7266            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7267            final int N = packageActivities.size();
7268            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7269                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7270
7271            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7272            for (int i = 0; i < N; ++i) {
7273                intentFilters = packageActivities.get(i).intents;
7274                if (intentFilters != null && intentFilters.size() > 0) {
7275                    PackageParser.ActivityIntentInfo[] array =
7276                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7277                    intentFilters.toArray(array);
7278                    listCut.add(array);
7279                }
7280            }
7281            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7282        }
7283
7284        public final void addActivity(PackageParser.Activity a, String type) {
7285            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7286            mActivities.put(a.getComponentName(), a);
7287            if (DEBUG_SHOW_INFO)
7288                Log.v(
7289                TAG, "  " + type + " " +
7290                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7291            if (DEBUG_SHOW_INFO)
7292                Log.v(TAG, "    Class=" + a.info.name);
7293            final int NI = a.intents.size();
7294            for (int j=0; j<NI; j++) {
7295                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7296                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7297                    intent.setPriority(0);
7298                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7299                            + a.className + " with priority > 0, forcing to 0");
7300                }
7301                if (DEBUG_SHOW_INFO) {
7302                    Log.v(TAG, "    IntentFilter:");
7303                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7304                }
7305                if (!intent.debugCheck()) {
7306                    Log.w(TAG, "==> For Activity " + a.info.name);
7307                }
7308                addFilter(intent);
7309            }
7310        }
7311
7312        public final void removeActivity(PackageParser.Activity a, String type) {
7313            mActivities.remove(a.getComponentName());
7314            if (DEBUG_SHOW_INFO) {
7315                Log.v(TAG, "  " + type + " "
7316                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7317                                : a.info.name) + ":");
7318                Log.v(TAG, "    Class=" + a.info.name);
7319            }
7320            final int NI = a.intents.size();
7321            for (int j=0; j<NI; j++) {
7322                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7323                if (DEBUG_SHOW_INFO) {
7324                    Log.v(TAG, "    IntentFilter:");
7325                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7326                }
7327                removeFilter(intent);
7328            }
7329        }
7330
7331        @Override
7332        protected boolean allowFilterResult(
7333                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7334            ActivityInfo filterAi = filter.activity.info;
7335            for (int i=dest.size()-1; i>=0; i--) {
7336                ActivityInfo destAi = dest.get(i).activityInfo;
7337                if (destAi.name == filterAi.name
7338                        && destAi.packageName == filterAi.packageName) {
7339                    return false;
7340                }
7341            }
7342            return true;
7343        }
7344
7345        @Override
7346        protected ActivityIntentInfo[] newArray(int size) {
7347            return new ActivityIntentInfo[size];
7348        }
7349
7350        @Override
7351        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7352            if (!sUserManager.exists(userId)) return true;
7353            PackageParser.Package p = filter.activity.owner;
7354            if (p != null) {
7355                PackageSetting ps = (PackageSetting)p.mExtras;
7356                if (ps != null) {
7357                    // System apps are never considered stopped for purposes of
7358                    // filtering, because there may be no way for the user to
7359                    // actually re-launch them.
7360                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7361                            && ps.getStopped(userId);
7362                }
7363            }
7364            return false;
7365        }
7366
7367        @Override
7368        protected boolean isPackageForFilter(String packageName,
7369                PackageParser.ActivityIntentInfo info) {
7370            return packageName.equals(info.activity.owner.packageName);
7371        }
7372
7373        @Override
7374        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7375                int match, int userId) {
7376            if (!sUserManager.exists(userId)) return null;
7377            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7378                return null;
7379            }
7380            final PackageParser.Activity activity = info.activity;
7381            if (mSafeMode && (activity.info.applicationInfo.flags
7382                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7383                return null;
7384            }
7385            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7386            if (ps == null) {
7387                return null;
7388            }
7389            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7390                    ps.readUserState(userId), userId);
7391            if (ai == null) {
7392                return null;
7393            }
7394            final ResolveInfo res = new ResolveInfo();
7395            res.activityInfo = ai;
7396            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7397                res.filter = info;
7398            }
7399            res.priority = info.getPriority();
7400            res.preferredOrder = activity.owner.mPreferredOrder;
7401            //System.out.println("Result: " + res.activityInfo.className +
7402            //                   " = " + res.priority);
7403            res.match = match;
7404            res.isDefault = info.hasDefault;
7405            res.labelRes = info.labelRes;
7406            res.nonLocalizedLabel = info.nonLocalizedLabel;
7407            if (userNeedsBadging(userId)) {
7408                res.noResourceId = true;
7409            } else {
7410                res.icon = info.icon;
7411            }
7412            res.system = isSystemApp(res.activityInfo.applicationInfo);
7413            return res;
7414        }
7415
7416        @Override
7417        protected void sortResults(List<ResolveInfo> results) {
7418            Collections.sort(results, mResolvePrioritySorter);
7419        }
7420
7421        @Override
7422        protected void dumpFilter(PrintWriter out, String prefix,
7423                PackageParser.ActivityIntentInfo filter) {
7424            out.print(prefix); out.print(
7425                    Integer.toHexString(System.identityHashCode(filter.activity)));
7426                    out.print(' ');
7427                    filter.activity.printComponentShortName(out);
7428                    out.print(" filter ");
7429                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7430        }
7431
7432        @Override
7433        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7434            return filter.activity;
7435        }
7436
7437        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7438            PackageParser.Activity activity = (PackageParser.Activity)label;
7439            out.print(prefix); out.print(
7440                    Integer.toHexString(System.identityHashCode(activity)));
7441                    out.print(' ');
7442                    activity.printComponentShortName(out);
7443            if (count > 1) {
7444                out.print(" ("); out.print(count); out.print(" filters)");
7445            }
7446            out.println();
7447        }
7448
7449//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7450//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7451//            final List<ResolveInfo> retList = Lists.newArrayList();
7452//            while (i.hasNext()) {
7453//                final ResolveInfo resolveInfo = i.next();
7454//                if (isEnabledLP(resolveInfo.activityInfo)) {
7455//                    retList.add(resolveInfo);
7456//                }
7457//            }
7458//            return retList;
7459//        }
7460
7461        // Keys are String (activity class name), values are Activity.
7462        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7463                = new ArrayMap<ComponentName, PackageParser.Activity>();
7464        private int mFlags;
7465    }
7466
7467    private final class ServiceIntentResolver
7468            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7469        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7470                boolean defaultOnly, int userId) {
7471            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7472            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7473        }
7474
7475        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7476                int userId) {
7477            if (!sUserManager.exists(userId)) return null;
7478            mFlags = flags;
7479            return super.queryIntent(intent, resolvedType,
7480                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7481        }
7482
7483        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7484                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7485            if (!sUserManager.exists(userId)) return null;
7486            if (packageServices == null) {
7487                return null;
7488            }
7489            mFlags = flags;
7490            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7491            final int N = packageServices.size();
7492            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7493                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7494
7495            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7496            for (int i = 0; i < N; ++i) {
7497                intentFilters = packageServices.get(i).intents;
7498                if (intentFilters != null && intentFilters.size() > 0) {
7499                    PackageParser.ServiceIntentInfo[] array =
7500                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7501                    intentFilters.toArray(array);
7502                    listCut.add(array);
7503                }
7504            }
7505            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7506        }
7507
7508        public final void addService(PackageParser.Service s) {
7509            mServices.put(s.getComponentName(), s);
7510            if (DEBUG_SHOW_INFO) {
7511                Log.v(TAG, "  "
7512                        + (s.info.nonLocalizedLabel != null
7513                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7514                Log.v(TAG, "    Class=" + s.info.name);
7515            }
7516            final int NI = s.intents.size();
7517            int j;
7518            for (j=0; j<NI; j++) {
7519                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7520                if (DEBUG_SHOW_INFO) {
7521                    Log.v(TAG, "    IntentFilter:");
7522                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7523                }
7524                if (!intent.debugCheck()) {
7525                    Log.w(TAG, "==> For Service " + s.info.name);
7526                }
7527                addFilter(intent);
7528            }
7529        }
7530
7531        public final void removeService(PackageParser.Service s) {
7532            mServices.remove(s.getComponentName());
7533            if (DEBUG_SHOW_INFO) {
7534                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7535                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7536                Log.v(TAG, "    Class=" + s.info.name);
7537            }
7538            final int NI = s.intents.size();
7539            int j;
7540            for (j=0; j<NI; j++) {
7541                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7542                if (DEBUG_SHOW_INFO) {
7543                    Log.v(TAG, "    IntentFilter:");
7544                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7545                }
7546                removeFilter(intent);
7547            }
7548        }
7549
7550        @Override
7551        protected boolean allowFilterResult(
7552                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7553            ServiceInfo filterSi = filter.service.info;
7554            for (int i=dest.size()-1; i>=0; i--) {
7555                ServiceInfo destAi = dest.get(i).serviceInfo;
7556                if (destAi.name == filterSi.name
7557                        && destAi.packageName == filterSi.packageName) {
7558                    return false;
7559                }
7560            }
7561            return true;
7562        }
7563
7564        @Override
7565        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7566            return new PackageParser.ServiceIntentInfo[size];
7567        }
7568
7569        @Override
7570        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7571            if (!sUserManager.exists(userId)) return true;
7572            PackageParser.Package p = filter.service.owner;
7573            if (p != null) {
7574                PackageSetting ps = (PackageSetting)p.mExtras;
7575                if (ps != null) {
7576                    // System apps are never considered stopped for purposes of
7577                    // filtering, because there may be no way for the user to
7578                    // actually re-launch them.
7579                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7580                            && ps.getStopped(userId);
7581                }
7582            }
7583            return false;
7584        }
7585
7586        @Override
7587        protected boolean isPackageForFilter(String packageName,
7588                PackageParser.ServiceIntentInfo info) {
7589            return packageName.equals(info.service.owner.packageName);
7590        }
7591
7592        @Override
7593        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7594                int match, int userId) {
7595            if (!sUserManager.exists(userId)) return null;
7596            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7597            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7598                return null;
7599            }
7600            final PackageParser.Service service = info.service;
7601            if (mSafeMode && (service.info.applicationInfo.flags
7602                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7603                return null;
7604            }
7605            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7606            if (ps == null) {
7607                return null;
7608            }
7609            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7610                    ps.readUserState(userId), userId);
7611            if (si == null) {
7612                return null;
7613            }
7614            final ResolveInfo res = new ResolveInfo();
7615            res.serviceInfo = si;
7616            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7617                res.filter = filter;
7618            }
7619            res.priority = info.getPriority();
7620            res.preferredOrder = service.owner.mPreferredOrder;
7621            //System.out.println("Result: " + res.activityInfo.className +
7622            //                   " = " + res.priority);
7623            res.match = match;
7624            res.isDefault = info.hasDefault;
7625            res.labelRes = info.labelRes;
7626            res.nonLocalizedLabel = info.nonLocalizedLabel;
7627            res.icon = info.icon;
7628            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7629            return res;
7630        }
7631
7632        @Override
7633        protected void sortResults(List<ResolveInfo> results) {
7634            Collections.sort(results, mResolvePrioritySorter);
7635        }
7636
7637        @Override
7638        protected void dumpFilter(PrintWriter out, String prefix,
7639                PackageParser.ServiceIntentInfo filter) {
7640            out.print(prefix); out.print(
7641                    Integer.toHexString(System.identityHashCode(filter.service)));
7642                    out.print(' ');
7643                    filter.service.printComponentShortName(out);
7644                    out.print(" filter ");
7645                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7646        }
7647
7648        @Override
7649        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7650            return filter.service;
7651        }
7652
7653        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7654            PackageParser.Service service = (PackageParser.Service)label;
7655            out.print(prefix); out.print(
7656                    Integer.toHexString(System.identityHashCode(service)));
7657                    out.print(' ');
7658                    service.printComponentShortName(out);
7659            if (count > 1) {
7660                out.print(" ("); out.print(count); out.print(" filters)");
7661            }
7662            out.println();
7663        }
7664
7665//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7666//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7667//            final List<ResolveInfo> retList = Lists.newArrayList();
7668//            while (i.hasNext()) {
7669//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7670//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7671//                    retList.add(resolveInfo);
7672//                }
7673//            }
7674//            return retList;
7675//        }
7676
7677        // Keys are String (activity class name), values are Activity.
7678        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7679                = new ArrayMap<ComponentName, PackageParser.Service>();
7680        private int mFlags;
7681    };
7682
7683    private final class ProviderIntentResolver
7684            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7685        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7686                boolean defaultOnly, int userId) {
7687            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7688            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7689        }
7690
7691        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7692                int userId) {
7693            if (!sUserManager.exists(userId))
7694                return null;
7695            mFlags = flags;
7696            return super.queryIntent(intent, resolvedType,
7697                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7698        }
7699
7700        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7701                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7702            if (!sUserManager.exists(userId))
7703                return null;
7704            if (packageProviders == null) {
7705                return null;
7706            }
7707            mFlags = flags;
7708            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7709            final int N = packageProviders.size();
7710            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7711                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7712
7713            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7714            for (int i = 0; i < N; ++i) {
7715                intentFilters = packageProviders.get(i).intents;
7716                if (intentFilters != null && intentFilters.size() > 0) {
7717                    PackageParser.ProviderIntentInfo[] array =
7718                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7719                    intentFilters.toArray(array);
7720                    listCut.add(array);
7721                }
7722            }
7723            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7724        }
7725
7726        public final void addProvider(PackageParser.Provider p) {
7727            if (mProviders.containsKey(p.getComponentName())) {
7728                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7729                return;
7730            }
7731
7732            mProviders.put(p.getComponentName(), p);
7733            if (DEBUG_SHOW_INFO) {
7734                Log.v(TAG, "  "
7735                        + (p.info.nonLocalizedLabel != null
7736                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7737                Log.v(TAG, "    Class=" + p.info.name);
7738            }
7739            final int NI = p.intents.size();
7740            int j;
7741            for (j = 0; j < NI; j++) {
7742                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7743                if (DEBUG_SHOW_INFO) {
7744                    Log.v(TAG, "    IntentFilter:");
7745                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7746                }
7747                if (!intent.debugCheck()) {
7748                    Log.w(TAG, "==> For Provider " + p.info.name);
7749                }
7750                addFilter(intent);
7751            }
7752        }
7753
7754        public final void removeProvider(PackageParser.Provider p) {
7755            mProviders.remove(p.getComponentName());
7756            if (DEBUG_SHOW_INFO) {
7757                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7758                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7759                Log.v(TAG, "    Class=" + p.info.name);
7760            }
7761            final int NI = p.intents.size();
7762            int j;
7763            for (j = 0; j < NI; j++) {
7764                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7765                if (DEBUG_SHOW_INFO) {
7766                    Log.v(TAG, "    IntentFilter:");
7767                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7768                }
7769                removeFilter(intent);
7770            }
7771        }
7772
7773        @Override
7774        protected boolean allowFilterResult(
7775                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7776            ProviderInfo filterPi = filter.provider.info;
7777            for (int i = dest.size() - 1; i >= 0; i--) {
7778                ProviderInfo destPi = dest.get(i).providerInfo;
7779                if (destPi.name == filterPi.name
7780                        && destPi.packageName == filterPi.packageName) {
7781                    return false;
7782                }
7783            }
7784            return true;
7785        }
7786
7787        @Override
7788        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7789            return new PackageParser.ProviderIntentInfo[size];
7790        }
7791
7792        @Override
7793        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7794            if (!sUserManager.exists(userId))
7795                return true;
7796            PackageParser.Package p = filter.provider.owner;
7797            if (p != null) {
7798                PackageSetting ps = (PackageSetting) p.mExtras;
7799                if (ps != null) {
7800                    // System apps are never considered stopped for purposes of
7801                    // filtering, because there may be no way for the user to
7802                    // actually re-launch them.
7803                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7804                            && ps.getStopped(userId);
7805                }
7806            }
7807            return false;
7808        }
7809
7810        @Override
7811        protected boolean isPackageForFilter(String packageName,
7812                PackageParser.ProviderIntentInfo info) {
7813            return packageName.equals(info.provider.owner.packageName);
7814        }
7815
7816        @Override
7817        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7818                int match, int userId) {
7819            if (!sUserManager.exists(userId))
7820                return null;
7821            final PackageParser.ProviderIntentInfo info = filter;
7822            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7823                return null;
7824            }
7825            final PackageParser.Provider provider = info.provider;
7826            if (mSafeMode && (provider.info.applicationInfo.flags
7827                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7828                return null;
7829            }
7830            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7831            if (ps == null) {
7832                return null;
7833            }
7834            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7835                    ps.readUserState(userId), userId);
7836            if (pi == null) {
7837                return null;
7838            }
7839            final ResolveInfo res = new ResolveInfo();
7840            res.providerInfo = pi;
7841            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7842                res.filter = filter;
7843            }
7844            res.priority = info.getPriority();
7845            res.preferredOrder = provider.owner.mPreferredOrder;
7846            res.match = match;
7847            res.isDefault = info.hasDefault;
7848            res.labelRes = info.labelRes;
7849            res.nonLocalizedLabel = info.nonLocalizedLabel;
7850            res.icon = info.icon;
7851            res.system = isSystemApp(res.providerInfo.applicationInfo);
7852            return res;
7853        }
7854
7855        @Override
7856        protected void sortResults(List<ResolveInfo> results) {
7857            Collections.sort(results, mResolvePrioritySorter);
7858        }
7859
7860        @Override
7861        protected void dumpFilter(PrintWriter out, String prefix,
7862                PackageParser.ProviderIntentInfo filter) {
7863            out.print(prefix);
7864            out.print(
7865                    Integer.toHexString(System.identityHashCode(filter.provider)));
7866            out.print(' ');
7867            filter.provider.printComponentShortName(out);
7868            out.print(" filter ");
7869            out.println(Integer.toHexString(System.identityHashCode(filter)));
7870        }
7871
7872        @Override
7873        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7874            return filter.provider;
7875        }
7876
7877        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7878            PackageParser.Provider provider = (PackageParser.Provider)label;
7879            out.print(prefix); out.print(
7880                    Integer.toHexString(System.identityHashCode(provider)));
7881                    out.print(' ');
7882                    provider.printComponentShortName(out);
7883            if (count > 1) {
7884                out.print(" ("); out.print(count); out.print(" filters)");
7885            }
7886            out.println();
7887        }
7888
7889        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7890                = new ArrayMap<ComponentName, PackageParser.Provider>();
7891        private int mFlags;
7892    };
7893
7894    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7895            new Comparator<ResolveInfo>() {
7896        public int compare(ResolveInfo r1, ResolveInfo r2) {
7897            int v1 = r1.priority;
7898            int v2 = r2.priority;
7899            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7900            if (v1 != v2) {
7901                return (v1 > v2) ? -1 : 1;
7902            }
7903            v1 = r1.preferredOrder;
7904            v2 = r2.preferredOrder;
7905            if (v1 != v2) {
7906                return (v1 > v2) ? -1 : 1;
7907            }
7908            if (r1.isDefault != r2.isDefault) {
7909                return r1.isDefault ? -1 : 1;
7910            }
7911            v1 = r1.match;
7912            v2 = r2.match;
7913            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7914            if (v1 != v2) {
7915                return (v1 > v2) ? -1 : 1;
7916            }
7917            if (r1.system != r2.system) {
7918                return r1.system ? -1 : 1;
7919            }
7920            return 0;
7921        }
7922    };
7923
7924    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7925            new Comparator<ProviderInfo>() {
7926        public int compare(ProviderInfo p1, ProviderInfo p2) {
7927            final int v1 = p1.initOrder;
7928            final int v2 = p2.initOrder;
7929            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7930        }
7931    };
7932
7933    static final void sendPackageBroadcast(String action, String pkg,
7934            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7935            int[] userIds) {
7936        IActivityManager am = ActivityManagerNative.getDefault();
7937        if (am != null) {
7938            try {
7939                if (userIds == null) {
7940                    userIds = am.getRunningUserIds();
7941                }
7942                for (int id : userIds) {
7943                    final Intent intent = new Intent(action,
7944                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7945                    if (extras != null) {
7946                        intent.putExtras(extras);
7947                    }
7948                    if (targetPkg != null) {
7949                        intent.setPackage(targetPkg);
7950                    }
7951                    // Modify the UID when posting to other users
7952                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7953                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7954                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7955                        intent.putExtra(Intent.EXTRA_UID, uid);
7956                    }
7957                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7958                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7959                    if (DEBUG_BROADCASTS) {
7960                        RuntimeException here = new RuntimeException("here");
7961                        here.fillInStackTrace();
7962                        Slog.d(TAG, "Sending to user " + id + ": "
7963                                + intent.toShortString(false, true, false, false)
7964                                + " " + intent.getExtras(), here);
7965                    }
7966                    am.broadcastIntent(null, intent, null, finishedReceiver,
7967                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7968                            finishedReceiver != null, false, id);
7969                }
7970            } catch (RemoteException ex) {
7971            }
7972        }
7973    }
7974
7975    /**
7976     * Check if the external storage media is available. This is true if there
7977     * is a mounted external storage medium or if the external storage is
7978     * emulated.
7979     */
7980    private boolean isExternalMediaAvailable() {
7981        return mMediaMounted || Environment.isExternalStorageEmulated();
7982    }
7983
7984    @Override
7985    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7986        // writer
7987        synchronized (mPackages) {
7988            if (!isExternalMediaAvailable()) {
7989                // If the external storage is no longer mounted at this point,
7990                // the caller may not have been able to delete all of this
7991                // packages files and can not delete any more.  Bail.
7992                return null;
7993            }
7994            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7995            if (lastPackage != null) {
7996                pkgs.remove(lastPackage);
7997            }
7998            if (pkgs.size() > 0) {
7999                return pkgs.get(0);
8000            }
8001        }
8002        return null;
8003    }
8004
8005    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8006        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8007                userId, andCode ? 1 : 0, packageName);
8008        if (mSystemReady) {
8009            msg.sendToTarget();
8010        } else {
8011            if (mPostSystemReadyMessages == null) {
8012                mPostSystemReadyMessages = new ArrayList<>();
8013            }
8014            mPostSystemReadyMessages.add(msg);
8015        }
8016    }
8017
8018    void startCleaningPackages() {
8019        // reader
8020        synchronized (mPackages) {
8021            if (!isExternalMediaAvailable()) {
8022                return;
8023            }
8024            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8025                return;
8026            }
8027        }
8028        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8029        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8030        IActivityManager am = ActivityManagerNative.getDefault();
8031        if (am != null) {
8032            try {
8033                am.startService(null, intent, null, UserHandle.USER_OWNER);
8034            } catch (RemoteException e) {
8035            }
8036        }
8037    }
8038
8039    @Override
8040    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8041            int installFlags, String installerPackageName, VerificationParams verificationParams,
8042            String packageAbiOverride) {
8043        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
8044                packageAbiOverride, UserHandle.getCallingUserId());
8045    }
8046
8047    @Override
8048    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8049            int installFlags, String installerPackageName, VerificationParams verificationParams,
8050            String packageAbiOverride, int userId) {
8051        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8052
8053        final int callingUid = Binder.getCallingUid();
8054        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8055
8056        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8057            try {
8058                if (observer != null) {
8059                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8060                }
8061            } catch (RemoteException re) {
8062            }
8063            return;
8064        }
8065
8066        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8067            installFlags |= PackageManager.INSTALL_FROM_ADB;
8068
8069        } else {
8070            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8071            // about installerPackageName.
8072
8073            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8074            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8075        }
8076
8077        UserHandle user;
8078        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8079            user = UserHandle.ALL;
8080        } else {
8081            user = new UserHandle(userId);
8082        }
8083
8084        verificationParams.setInstallerUid(callingUid);
8085
8086        final File originFile = new File(originPath);
8087        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8088
8089        final Message msg = mHandler.obtainMessage(INIT_COPY);
8090        msg.obj = new InstallParams(origin, observer, installFlags,
8091                installerPackageName, verificationParams, user, packageAbiOverride);
8092        mHandler.sendMessage(msg);
8093    }
8094
8095    void installStage(String packageName, File stagedDir, String stagedCid,
8096            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8097            String installerPackageName, int installerUid, UserHandle user) {
8098        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8099                params.referrerUri, installerUid, null);
8100
8101        final OriginInfo origin;
8102        if (stagedDir != null) {
8103            origin = OriginInfo.fromStagedFile(stagedDir);
8104        } else {
8105            origin = OriginInfo.fromStagedContainer(stagedCid);
8106        }
8107
8108        final Message msg = mHandler.obtainMessage(INIT_COPY);
8109        msg.obj = new InstallParams(origin, observer, params.installFlags,
8110                installerPackageName, verifParams, user, params.abiOverride);
8111        mHandler.sendMessage(msg);
8112    }
8113
8114    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8115        Bundle extras = new Bundle(1);
8116        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8117
8118        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8119                packageName, extras, null, null, new int[] {userId});
8120        try {
8121            IActivityManager am = ActivityManagerNative.getDefault();
8122            final boolean isSystem =
8123                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8124            if (isSystem && am.isUserRunning(userId, false)) {
8125                // The just-installed/enabled app is bundled on the system, so presumed
8126                // to be able to run automatically without needing an explicit launch.
8127                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8128                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8129                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8130                        .setPackage(packageName);
8131                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8132                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8133            }
8134        } catch (RemoteException e) {
8135            // shouldn't happen
8136            Slog.w(TAG, "Unable to bootstrap installed package", e);
8137        }
8138    }
8139
8140    @Override
8141    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8142            int userId) {
8143        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8144        PackageSetting pkgSetting;
8145        final int uid = Binder.getCallingUid();
8146        enforceCrossUserPermission(uid, userId, true, true,
8147                "setApplicationHiddenSetting for user " + userId);
8148
8149        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8150            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8151            return false;
8152        }
8153
8154        long callingId = Binder.clearCallingIdentity();
8155        try {
8156            boolean sendAdded = false;
8157            boolean sendRemoved = false;
8158            // writer
8159            synchronized (mPackages) {
8160                pkgSetting = mSettings.mPackages.get(packageName);
8161                if (pkgSetting == null) {
8162                    return false;
8163                }
8164                if (pkgSetting.getHidden(userId) != hidden) {
8165                    pkgSetting.setHidden(hidden, userId);
8166                    mSettings.writePackageRestrictionsLPr(userId);
8167                    if (hidden) {
8168                        sendRemoved = true;
8169                    } else {
8170                        sendAdded = true;
8171                    }
8172                }
8173            }
8174            if (sendAdded) {
8175                sendPackageAddedForUser(packageName, pkgSetting, userId);
8176                return true;
8177            }
8178            if (sendRemoved) {
8179                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8180                        "hiding pkg");
8181                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8182            }
8183        } finally {
8184            Binder.restoreCallingIdentity(callingId);
8185        }
8186        return false;
8187    }
8188
8189    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8190            int userId) {
8191        final PackageRemovedInfo info = new PackageRemovedInfo();
8192        info.removedPackage = packageName;
8193        info.removedUsers = new int[] {userId};
8194        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8195        info.sendBroadcast(false, false, false);
8196    }
8197
8198    /**
8199     * Returns true if application is not found or there was an error. Otherwise it returns
8200     * the hidden state of the package for the given user.
8201     */
8202    @Override
8203    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8204        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8205        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8206                false, "getApplicationHidden for user " + userId);
8207        PackageSetting pkgSetting;
8208        long callingId = Binder.clearCallingIdentity();
8209        try {
8210            // writer
8211            synchronized (mPackages) {
8212                pkgSetting = mSettings.mPackages.get(packageName);
8213                if (pkgSetting == null) {
8214                    return true;
8215                }
8216                return pkgSetting.getHidden(userId);
8217            }
8218        } finally {
8219            Binder.restoreCallingIdentity(callingId);
8220        }
8221    }
8222
8223    /**
8224     * @hide
8225     */
8226    @Override
8227    public int installExistingPackageAsUser(String packageName, int userId) {
8228        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8229                null);
8230        PackageSetting pkgSetting;
8231        final int uid = Binder.getCallingUid();
8232        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8233                + userId);
8234        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8235            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8236        }
8237
8238        long callingId = Binder.clearCallingIdentity();
8239        try {
8240            boolean sendAdded = false;
8241            Bundle extras = new Bundle(1);
8242
8243            // writer
8244            synchronized (mPackages) {
8245                pkgSetting = mSettings.mPackages.get(packageName);
8246                if (pkgSetting == null) {
8247                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8248                }
8249                if (!pkgSetting.getInstalled(userId)) {
8250                    pkgSetting.setInstalled(true, userId);
8251                    pkgSetting.setHidden(false, userId);
8252                    mSettings.writePackageRestrictionsLPr(userId);
8253                    sendAdded = true;
8254                }
8255            }
8256
8257            if (sendAdded) {
8258                sendPackageAddedForUser(packageName, pkgSetting, userId);
8259            }
8260        } finally {
8261            Binder.restoreCallingIdentity(callingId);
8262        }
8263
8264        return PackageManager.INSTALL_SUCCEEDED;
8265    }
8266
8267    boolean isUserRestricted(int userId, String restrictionKey) {
8268        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8269        if (restrictions.getBoolean(restrictionKey, false)) {
8270            Log.w(TAG, "User is restricted: " + restrictionKey);
8271            return true;
8272        }
8273        return false;
8274    }
8275
8276    @Override
8277    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8278        mContext.enforceCallingOrSelfPermission(
8279                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8280                "Only package verification agents can verify applications");
8281
8282        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8283        final PackageVerificationResponse response = new PackageVerificationResponse(
8284                verificationCode, Binder.getCallingUid());
8285        msg.arg1 = id;
8286        msg.obj = response;
8287        mHandler.sendMessage(msg);
8288    }
8289
8290    @Override
8291    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8292            long millisecondsToDelay) {
8293        mContext.enforceCallingOrSelfPermission(
8294                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8295                "Only package verification agents can extend verification timeouts");
8296
8297        final PackageVerificationState state = mPendingVerification.get(id);
8298        final PackageVerificationResponse response = new PackageVerificationResponse(
8299                verificationCodeAtTimeout, Binder.getCallingUid());
8300
8301        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8302            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8303        }
8304        if (millisecondsToDelay < 0) {
8305            millisecondsToDelay = 0;
8306        }
8307        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8308                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8309            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8310        }
8311
8312        if ((state != null) && !state.timeoutExtended()) {
8313            state.extendTimeout();
8314
8315            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8316            msg.arg1 = id;
8317            msg.obj = response;
8318            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8319        }
8320    }
8321
8322    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8323            int verificationCode, UserHandle user) {
8324        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8325        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8326        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8327        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8328        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8329
8330        mContext.sendBroadcastAsUser(intent, user,
8331                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8332    }
8333
8334    private ComponentName matchComponentForVerifier(String packageName,
8335            List<ResolveInfo> receivers) {
8336        ActivityInfo targetReceiver = null;
8337
8338        final int NR = receivers.size();
8339        for (int i = 0; i < NR; i++) {
8340            final ResolveInfo info = receivers.get(i);
8341            if (info.activityInfo == null) {
8342                continue;
8343            }
8344
8345            if (packageName.equals(info.activityInfo.packageName)) {
8346                targetReceiver = info.activityInfo;
8347                break;
8348            }
8349        }
8350
8351        if (targetReceiver == null) {
8352            return null;
8353        }
8354
8355        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8356    }
8357
8358    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8359            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8360        if (pkgInfo.verifiers.length == 0) {
8361            return null;
8362        }
8363
8364        final int N = pkgInfo.verifiers.length;
8365        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8366        for (int i = 0; i < N; i++) {
8367            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8368
8369            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8370                    receivers);
8371            if (comp == null) {
8372                continue;
8373            }
8374
8375            final int verifierUid = getUidForVerifier(verifierInfo);
8376            if (verifierUid == -1) {
8377                continue;
8378            }
8379
8380            if (DEBUG_VERIFY) {
8381                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8382                        + " with the correct signature");
8383            }
8384            sufficientVerifiers.add(comp);
8385            verificationState.addSufficientVerifier(verifierUid);
8386        }
8387
8388        return sufficientVerifiers;
8389    }
8390
8391    private int getUidForVerifier(VerifierInfo verifierInfo) {
8392        synchronized (mPackages) {
8393            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8394            if (pkg == null) {
8395                return -1;
8396            } else if (pkg.mSignatures.length != 1) {
8397                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8398                        + " has more than one signature; ignoring");
8399                return -1;
8400            }
8401
8402            /*
8403             * If the public key of the package's signature does not match
8404             * our expected public key, then this is a different package and
8405             * we should skip.
8406             */
8407
8408            final byte[] expectedPublicKey;
8409            try {
8410                final Signature verifierSig = pkg.mSignatures[0];
8411                final PublicKey publicKey = verifierSig.getPublicKey();
8412                expectedPublicKey = publicKey.getEncoded();
8413            } catch (CertificateException e) {
8414                return -1;
8415            }
8416
8417            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8418
8419            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8420                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8421                        + " does not have the expected public key; ignoring");
8422                return -1;
8423            }
8424
8425            return pkg.applicationInfo.uid;
8426        }
8427    }
8428
8429    @Override
8430    public void finishPackageInstall(int token) {
8431        enforceSystemOrRoot("Only the system is allowed to finish installs");
8432
8433        if (DEBUG_INSTALL) {
8434            Slog.v(TAG, "BM finishing package install for " + token);
8435        }
8436
8437        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8438        mHandler.sendMessage(msg);
8439    }
8440
8441    /**
8442     * Get the verification agent timeout.
8443     *
8444     * @return verification timeout in milliseconds
8445     */
8446    private long getVerificationTimeout() {
8447        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8448                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8449                DEFAULT_VERIFICATION_TIMEOUT);
8450    }
8451
8452    /**
8453     * Get the default verification agent response code.
8454     *
8455     * @return default verification response code
8456     */
8457    private int getDefaultVerificationResponse() {
8458        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8459                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8460                DEFAULT_VERIFICATION_RESPONSE);
8461    }
8462
8463    /**
8464     * Check whether or not package verification has been enabled.
8465     *
8466     * @return true if verification should be performed
8467     */
8468    private boolean isVerificationEnabled(int userId, int installFlags) {
8469        if (!DEFAULT_VERIFY_ENABLE) {
8470            return false;
8471        }
8472
8473        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8474
8475        // Check if installing from ADB
8476        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8477            // Do not run verification in a test harness environment
8478            if (ActivityManager.isRunningInTestHarness()) {
8479                return false;
8480            }
8481            if (ensureVerifyAppsEnabled) {
8482                return true;
8483            }
8484            // Check if the developer does not want package verification for ADB installs
8485            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8486                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8487                return false;
8488            }
8489        }
8490
8491        if (ensureVerifyAppsEnabled) {
8492            return true;
8493        }
8494
8495        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8496                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8497    }
8498
8499    /**
8500     * Get the "allow unknown sources" setting.
8501     *
8502     * @return the current "allow unknown sources" setting
8503     */
8504    private int getUnknownSourcesSettings() {
8505        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8506                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8507                -1);
8508    }
8509
8510    @Override
8511    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8512        final int uid = Binder.getCallingUid();
8513        // writer
8514        synchronized (mPackages) {
8515            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8516            if (targetPackageSetting == null) {
8517                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8518            }
8519
8520            PackageSetting installerPackageSetting;
8521            if (installerPackageName != null) {
8522                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8523                if (installerPackageSetting == null) {
8524                    throw new IllegalArgumentException("Unknown installer package: "
8525                            + installerPackageName);
8526                }
8527            } else {
8528                installerPackageSetting = null;
8529            }
8530
8531            Signature[] callerSignature;
8532            Object obj = mSettings.getUserIdLPr(uid);
8533            if (obj != null) {
8534                if (obj instanceof SharedUserSetting) {
8535                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8536                } else if (obj instanceof PackageSetting) {
8537                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8538                } else {
8539                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8540                }
8541            } else {
8542                throw new SecurityException("Unknown calling uid " + uid);
8543            }
8544
8545            // Verify: can't set installerPackageName to a package that is
8546            // not signed with the same cert as the caller.
8547            if (installerPackageSetting != null) {
8548                if (compareSignatures(callerSignature,
8549                        installerPackageSetting.signatures.mSignatures)
8550                        != PackageManager.SIGNATURE_MATCH) {
8551                    throw new SecurityException(
8552                            "Caller does not have same cert as new installer package "
8553                            + installerPackageName);
8554                }
8555            }
8556
8557            // Verify: if target already has an installer package, it must
8558            // be signed with the same cert as the caller.
8559            if (targetPackageSetting.installerPackageName != null) {
8560                PackageSetting setting = mSettings.mPackages.get(
8561                        targetPackageSetting.installerPackageName);
8562                // If the currently set package isn't valid, then it's always
8563                // okay to change it.
8564                if (setting != null) {
8565                    if (compareSignatures(callerSignature,
8566                            setting.signatures.mSignatures)
8567                            != PackageManager.SIGNATURE_MATCH) {
8568                        throw new SecurityException(
8569                                "Caller does not have same cert as old installer package "
8570                                + targetPackageSetting.installerPackageName);
8571                    }
8572                }
8573            }
8574
8575            // Okay!
8576            targetPackageSetting.installerPackageName = installerPackageName;
8577            scheduleWriteSettingsLocked();
8578        }
8579    }
8580
8581    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8582        // Queue up an async operation since the package installation may take a little while.
8583        mHandler.post(new Runnable() {
8584            public void run() {
8585                mHandler.removeCallbacks(this);
8586                 // Result object to be returned
8587                PackageInstalledInfo res = new PackageInstalledInfo();
8588                res.returnCode = currentStatus;
8589                res.uid = -1;
8590                res.pkg = null;
8591                res.removedInfo = new PackageRemovedInfo();
8592                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8593                    args.doPreInstall(res.returnCode);
8594                    synchronized (mInstallLock) {
8595                        installPackageLI(args, res);
8596                    }
8597                    args.doPostInstall(res.returnCode, res.uid);
8598                }
8599
8600                // A restore should be performed at this point if (a) the install
8601                // succeeded, (b) the operation is not an update, and (c) the new
8602                // package has not opted out of backup participation.
8603                final boolean update = res.removedInfo.removedPackage != null;
8604                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8605                boolean doRestore = !update
8606                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8607
8608                // Set up the post-install work request bookkeeping.  This will be used
8609                // and cleaned up by the post-install event handling regardless of whether
8610                // there's a restore pass performed.  Token values are >= 1.
8611                int token;
8612                if (mNextInstallToken < 0) mNextInstallToken = 1;
8613                token = mNextInstallToken++;
8614
8615                PostInstallData data = new PostInstallData(args, res);
8616                mRunningInstalls.put(token, data);
8617                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8618
8619                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8620                    // Pass responsibility to the Backup Manager.  It will perform a
8621                    // restore if appropriate, then pass responsibility back to the
8622                    // Package Manager to run the post-install observer callbacks
8623                    // and broadcasts.
8624                    IBackupManager bm = IBackupManager.Stub.asInterface(
8625                            ServiceManager.getService(Context.BACKUP_SERVICE));
8626                    if (bm != null) {
8627                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8628                                + " to BM for possible restore");
8629                        try {
8630                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8631                        } catch (RemoteException e) {
8632                            // can't happen; the backup manager is local
8633                        } catch (Exception e) {
8634                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8635                            doRestore = false;
8636                        }
8637                    } else {
8638                        Slog.e(TAG, "Backup Manager not found!");
8639                        doRestore = false;
8640                    }
8641                }
8642
8643                if (!doRestore) {
8644                    // No restore possible, or the Backup Manager was mysteriously not
8645                    // available -- just fire the post-install work request directly.
8646                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8647                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8648                    mHandler.sendMessage(msg);
8649                }
8650            }
8651        });
8652    }
8653
8654    private abstract class HandlerParams {
8655        private static final int MAX_RETRIES = 4;
8656
8657        /**
8658         * Number of times startCopy() has been attempted and had a non-fatal
8659         * error.
8660         */
8661        private int mRetries = 0;
8662
8663        /** User handle for the user requesting the information or installation. */
8664        private final UserHandle mUser;
8665
8666        HandlerParams(UserHandle user) {
8667            mUser = user;
8668        }
8669
8670        UserHandle getUser() {
8671            return mUser;
8672        }
8673
8674        final boolean startCopy() {
8675            boolean res;
8676            try {
8677                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8678
8679                if (++mRetries > MAX_RETRIES) {
8680                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8681                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8682                    handleServiceError();
8683                    return false;
8684                } else {
8685                    handleStartCopy();
8686                    res = true;
8687                }
8688            } catch (RemoteException e) {
8689                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8690                mHandler.sendEmptyMessage(MCS_RECONNECT);
8691                res = false;
8692            }
8693            handleReturnCode();
8694            return res;
8695        }
8696
8697        final void serviceError() {
8698            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8699            handleServiceError();
8700            handleReturnCode();
8701        }
8702
8703        abstract void handleStartCopy() throws RemoteException;
8704        abstract void handleServiceError();
8705        abstract void handleReturnCode();
8706    }
8707
8708    class MeasureParams extends HandlerParams {
8709        private final PackageStats mStats;
8710        private boolean mSuccess;
8711
8712        private final IPackageStatsObserver mObserver;
8713
8714        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8715            super(new UserHandle(stats.userHandle));
8716            mObserver = observer;
8717            mStats = stats;
8718        }
8719
8720        @Override
8721        public String toString() {
8722            return "MeasureParams{"
8723                + Integer.toHexString(System.identityHashCode(this))
8724                + " " + mStats.packageName + "}";
8725        }
8726
8727        @Override
8728        void handleStartCopy() throws RemoteException {
8729            synchronized (mInstallLock) {
8730                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8731            }
8732
8733            if (mSuccess) {
8734                final boolean mounted;
8735                if (Environment.isExternalStorageEmulated()) {
8736                    mounted = true;
8737                } else {
8738                    final String status = Environment.getExternalStorageState();
8739                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8740                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8741                }
8742
8743                if (mounted) {
8744                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8745
8746                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8747                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8748
8749                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8750                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8751
8752                    // Always subtract cache size, since it's a subdirectory
8753                    mStats.externalDataSize -= mStats.externalCacheSize;
8754
8755                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8756                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8757
8758                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8759                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8760                }
8761            }
8762        }
8763
8764        @Override
8765        void handleReturnCode() {
8766            if (mObserver != null) {
8767                try {
8768                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8769                } catch (RemoteException e) {
8770                    Slog.i(TAG, "Observer no longer exists.");
8771                }
8772            }
8773        }
8774
8775        @Override
8776        void handleServiceError() {
8777            Slog.e(TAG, "Could not measure application " + mStats.packageName
8778                            + " external storage");
8779        }
8780    }
8781
8782    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8783            throws RemoteException {
8784        long result = 0;
8785        for (File path : paths) {
8786            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8787        }
8788        return result;
8789    }
8790
8791    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8792        for (File path : paths) {
8793            try {
8794                mcs.clearDirectory(path.getAbsolutePath());
8795            } catch (RemoteException e) {
8796            }
8797        }
8798    }
8799
8800    static class OriginInfo {
8801        /**
8802         * Location where install is coming from, before it has been
8803         * copied/renamed into place. This could be a single monolithic APK
8804         * file, or a cluster directory. This location may be untrusted.
8805         */
8806        final File file;
8807        final String cid;
8808
8809        /**
8810         * Flag indicating that {@link #file} or {@link #cid} has already been
8811         * staged, meaning downstream users don't need to defensively copy the
8812         * contents.
8813         */
8814        final boolean staged;
8815
8816        /**
8817         * Flag indicating that {@link #file} or {@link #cid} is an already
8818         * installed app that is being moved.
8819         */
8820        final boolean existing;
8821
8822        final String resolvedPath;
8823        final File resolvedFile;
8824
8825        static OriginInfo fromNothing() {
8826            return new OriginInfo(null, null, false, false);
8827        }
8828
8829        static OriginInfo fromUntrustedFile(File file) {
8830            return new OriginInfo(file, null, false, false);
8831        }
8832
8833        static OriginInfo fromExistingFile(File file) {
8834            return new OriginInfo(file, null, false, true);
8835        }
8836
8837        static OriginInfo fromStagedFile(File file) {
8838            return new OriginInfo(file, null, true, false);
8839        }
8840
8841        static OriginInfo fromStagedContainer(String cid) {
8842            return new OriginInfo(null, cid, true, false);
8843        }
8844
8845        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8846            this.file = file;
8847            this.cid = cid;
8848            this.staged = staged;
8849            this.existing = existing;
8850
8851            if (cid != null) {
8852                resolvedPath = PackageHelper.getSdDir(cid);
8853                resolvedFile = new File(resolvedPath);
8854            } else if (file != null) {
8855                resolvedPath = file.getAbsolutePath();
8856                resolvedFile = file;
8857            } else {
8858                resolvedPath = null;
8859                resolvedFile = null;
8860            }
8861        }
8862    }
8863
8864    class InstallParams extends HandlerParams {
8865        final OriginInfo origin;
8866        final IPackageInstallObserver2 observer;
8867        int installFlags;
8868        final String installerPackageName;
8869        final VerificationParams verificationParams;
8870        private InstallArgs mArgs;
8871        private int mRet;
8872        final String packageAbiOverride;
8873
8874        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8875                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8876                String packageAbiOverride) {
8877            super(user);
8878            this.origin = origin;
8879            this.observer = observer;
8880            this.installFlags = installFlags;
8881            this.installerPackageName = installerPackageName;
8882            this.verificationParams = verificationParams;
8883            this.packageAbiOverride = packageAbiOverride;
8884        }
8885
8886        @Override
8887        public String toString() {
8888            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8889                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8890        }
8891
8892        public ManifestDigest getManifestDigest() {
8893            if (verificationParams == null) {
8894                return null;
8895            }
8896            return verificationParams.getManifestDigest();
8897        }
8898
8899        private int installLocationPolicy(PackageInfoLite pkgLite) {
8900            String packageName = pkgLite.packageName;
8901            int installLocation = pkgLite.installLocation;
8902            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8903            // reader
8904            synchronized (mPackages) {
8905                PackageParser.Package pkg = mPackages.get(packageName);
8906                if (pkg != null) {
8907                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8908                        // Check for downgrading.
8909                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8910                            try {
8911                                checkDowngrade(pkg, pkgLite);
8912                            } catch (PackageManagerException e) {
8913                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8914                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8915                            }
8916                        }
8917                        // Check for updated system application.
8918                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8919                            if (onSd) {
8920                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8921                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8922                            }
8923                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8924                        } else {
8925                            if (onSd) {
8926                                // Install flag overrides everything.
8927                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8928                            }
8929                            // If current upgrade specifies particular preference
8930                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8931                                // Application explicitly specified internal.
8932                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8933                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8934                                // App explictly prefers external. Let policy decide
8935                            } else {
8936                                // Prefer previous location
8937                                if (isExternal(pkg)) {
8938                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8939                                }
8940                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8941                            }
8942                        }
8943                    } else {
8944                        // Invalid install. Return error code
8945                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8946                    }
8947                }
8948            }
8949            // All the special cases have been taken care of.
8950            // Return result based on recommended install location.
8951            if (onSd) {
8952                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8953            }
8954            return pkgLite.recommendedInstallLocation;
8955        }
8956
8957        /*
8958         * Invoke remote method to get package information and install
8959         * location values. Override install location based on default
8960         * policy if needed and then create install arguments based
8961         * on the install location.
8962         */
8963        public void handleStartCopy() throws RemoteException {
8964            int ret = PackageManager.INSTALL_SUCCEEDED;
8965
8966            // If we're already staged, we've firmly committed to an install location
8967            if (origin.staged) {
8968                if (origin.file != null) {
8969                    installFlags |= PackageManager.INSTALL_INTERNAL;
8970                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8971                } else if (origin.cid != null) {
8972                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8973                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8974                } else {
8975                    throw new IllegalStateException("Invalid stage location");
8976                }
8977            }
8978
8979            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8980            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8981
8982            PackageInfoLite pkgLite = null;
8983
8984            if (onInt && onSd) {
8985                // Check if both bits are set.
8986                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8987                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8988            } else {
8989                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8990                        packageAbiOverride);
8991
8992                /*
8993                 * If we have too little free space, try to free cache
8994                 * before giving up.
8995                 */
8996                if (!origin.staged && pkgLite.recommendedInstallLocation
8997                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8998                    // TODO: focus freeing disk space on the target device
8999                    final StorageManager storage = StorageManager.from(mContext);
9000                    final long lowThreshold = storage.getStorageLowBytes(
9001                            Environment.getDataDirectory());
9002
9003                    final long sizeBytes = mContainerService.calculateInstalledSize(
9004                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9005
9006                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9007                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9008                                installFlags, packageAbiOverride);
9009                    }
9010
9011                    /*
9012                     * The cache free must have deleted the file we
9013                     * downloaded to install.
9014                     *
9015                     * TODO: fix the "freeCache" call to not delete
9016                     *       the file we care about.
9017                     */
9018                    if (pkgLite.recommendedInstallLocation
9019                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9020                        pkgLite.recommendedInstallLocation
9021                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9022                    }
9023                }
9024            }
9025
9026            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9027                int loc = pkgLite.recommendedInstallLocation;
9028                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9029                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9030                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9031                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9032                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9033                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9034                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9035                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9036                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9037                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9038                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9039                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9040                } else {
9041                    // Override with defaults if needed.
9042                    loc = installLocationPolicy(pkgLite);
9043                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9044                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9045                    } else if (!onSd && !onInt) {
9046                        // Override install location with flags
9047                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9048                            // Set the flag to install on external media.
9049                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9050                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9051                        } else {
9052                            // Make sure the flag for installing on external
9053                            // media is unset
9054                            installFlags |= PackageManager.INSTALL_INTERNAL;
9055                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9056                        }
9057                    }
9058                }
9059            }
9060
9061            final InstallArgs args = createInstallArgs(this);
9062            mArgs = args;
9063
9064            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9065                 /*
9066                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9067                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9068                 */
9069                int userIdentifier = getUser().getIdentifier();
9070                if (userIdentifier == UserHandle.USER_ALL
9071                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9072                    userIdentifier = UserHandle.USER_OWNER;
9073                }
9074
9075                /*
9076                 * Determine if we have any installed package verifiers. If we
9077                 * do, then we'll defer to them to verify the packages.
9078                 */
9079                final int requiredUid = mRequiredVerifierPackage == null ? -1
9080                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9081                if (!origin.existing && requiredUid != -1
9082                        && isVerificationEnabled(userIdentifier, installFlags)) {
9083                    final Intent verification = new Intent(
9084                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9085                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9086                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9087                            PACKAGE_MIME_TYPE);
9088                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9089
9090                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9091                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9092                            0 /* TODO: Which userId? */);
9093
9094                    if (DEBUG_VERIFY) {
9095                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9096                                + verification.toString() + " with " + pkgLite.verifiers.length
9097                                + " optional verifiers");
9098                    }
9099
9100                    final int verificationId = mPendingVerificationToken++;
9101
9102                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9103
9104                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9105                            installerPackageName);
9106
9107                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9108                            installFlags);
9109
9110                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9111                            pkgLite.packageName);
9112
9113                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9114                            pkgLite.versionCode);
9115
9116                    if (verificationParams != null) {
9117                        if (verificationParams.getVerificationURI() != null) {
9118                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9119                                 verificationParams.getVerificationURI());
9120                        }
9121                        if (verificationParams.getOriginatingURI() != null) {
9122                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9123                                  verificationParams.getOriginatingURI());
9124                        }
9125                        if (verificationParams.getReferrer() != null) {
9126                            verification.putExtra(Intent.EXTRA_REFERRER,
9127                                  verificationParams.getReferrer());
9128                        }
9129                        if (verificationParams.getOriginatingUid() >= 0) {
9130                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9131                                  verificationParams.getOriginatingUid());
9132                        }
9133                        if (verificationParams.getInstallerUid() >= 0) {
9134                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9135                                  verificationParams.getInstallerUid());
9136                        }
9137                    }
9138
9139                    final PackageVerificationState verificationState = new PackageVerificationState(
9140                            requiredUid, args);
9141
9142                    mPendingVerification.append(verificationId, verificationState);
9143
9144                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9145                            receivers, verificationState);
9146
9147                    /*
9148                     * If any sufficient verifiers were listed in the package
9149                     * manifest, attempt to ask them.
9150                     */
9151                    if (sufficientVerifiers != null) {
9152                        final int N = sufficientVerifiers.size();
9153                        if (N == 0) {
9154                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9155                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9156                        } else {
9157                            for (int i = 0; i < N; i++) {
9158                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9159
9160                                final Intent sufficientIntent = new Intent(verification);
9161                                sufficientIntent.setComponent(verifierComponent);
9162
9163                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9164                            }
9165                        }
9166                    }
9167
9168                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9169                            mRequiredVerifierPackage, receivers);
9170                    if (ret == PackageManager.INSTALL_SUCCEEDED
9171                            && mRequiredVerifierPackage != null) {
9172                        /*
9173                         * Send the intent to the required verification agent,
9174                         * but only start the verification timeout after the
9175                         * target BroadcastReceivers have run.
9176                         */
9177                        verification.setComponent(requiredVerifierComponent);
9178                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9179                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9180                                new BroadcastReceiver() {
9181                                    @Override
9182                                    public void onReceive(Context context, Intent intent) {
9183                                        final Message msg = mHandler
9184                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9185                                        msg.arg1 = verificationId;
9186                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9187                                    }
9188                                }, null, 0, null, null);
9189
9190                        /*
9191                         * We don't want the copy to proceed until verification
9192                         * succeeds, so null out this field.
9193                         */
9194                        mArgs = null;
9195                    }
9196                } else {
9197                    /*
9198                     * No package verification is enabled, so immediately start
9199                     * the remote call to initiate copy using temporary file.
9200                     */
9201                    ret = args.copyApk(mContainerService, true);
9202                }
9203            }
9204
9205            mRet = ret;
9206        }
9207
9208        @Override
9209        void handleReturnCode() {
9210            // If mArgs is null, then MCS couldn't be reached. When it
9211            // reconnects, it will try again to install. At that point, this
9212            // will succeed.
9213            if (mArgs != null) {
9214                processPendingInstall(mArgs, mRet);
9215            }
9216        }
9217
9218        @Override
9219        void handleServiceError() {
9220            mArgs = createInstallArgs(this);
9221            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9222        }
9223
9224        public boolean isForwardLocked() {
9225            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9226        }
9227    }
9228
9229    /**
9230     * Used during creation of InstallArgs
9231     *
9232     * @param installFlags package installation flags
9233     * @return true if should be installed on external storage
9234     */
9235    private static boolean installOnSd(int installFlags) {
9236        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9237            return false;
9238        }
9239        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9240            return true;
9241        }
9242        return false;
9243    }
9244
9245    /**
9246     * Used during creation of InstallArgs
9247     *
9248     * @param installFlags package installation flags
9249     * @return true if should be installed as forward locked
9250     */
9251    private static boolean installForwardLocked(int installFlags) {
9252        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9253    }
9254
9255    private InstallArgs createInstallArgs(InstallParams params) {
9256        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9257            return new AsecInstallArgs(params);
9258        } else {
9259            return new FileInstallArgs(params);
9260        }
9261    }
9262
9263    /**
9264     * Create args that describe an existing installed package. Typically used
9265     * when cleaning up old installs, or used as a move source.
9266     */
9267    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9268            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9269        final boolean isInAsec;
9270        if (installOnSd(installFlags)) {
9271            /* Apps on SD card are always in ASEC containers. */
9272            isInAsec = true;
9273        } else if (installForwardLocked(installFlags)
9274                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9275            /*
9276             * Forward-locked apps are only in ASEC containers if they're the
9277             * new style
9278             */
9279            isInAsec = true;
9280        } else {
9281            isInAsec = false;
9282        }
9283
9284        if (isInAsec) {
9285            return new AsecInstallArgs(codePath, instructionSets,
9286                    installOnSd(installFlags), installForwardLocked(installFlags));
9287        } else {
9288            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9289                    instructionSets);
9290        }
9291    }
9292
9293    static abstract class InstallArgs {
9294        /** @see InstallParams#origin */
9295        final OriginInfo origin;
9296
9297        final IPackageInstallObserver2 observer;
9298        // Always refers to PackageManager flags only
9299        final int installFlags;
9300        final String installerPackageName;
9301        final ManifestDigest manifestDigest;
9302        final UserHandle user;
9303        final String abiOverride;
9304
9305        // The list of instruction sets supported by this app. This is currently
9306        // only used during the rmdex() phase to clean up resources. We can get rid of this
9307        // if we move dex files under the common app path.
9308        /* nullable */ String[] instructionSets;
9309
9310        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9311                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9312                String[] instructionSets, String abiOverride) {
9313            this.origin = origin;
9314            this.installFlags = installFlags;
9315            this.observer = observer;
9316            this.installerPackageName = installerPackageName;
9317            this.manifestDigest = manifestDigest;
9318            this.user = user;
9319            this.instructionSets = instructionSets;
9320            this.abiOverride = abiOverride;
9321        }
9322
9323        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9324        abstract int doPreInstall(int status);
9325
9326        /**
9327         * Rename package into final resting place. All paths on the given
9328         * scanned package should be updated to reflect the rename.
9329         */
9330        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9331        abstract int doPostInstall(int status, int uid);
9332
9333        /** @see PackageSettingBase#codePathString */
9334        abstract String getCodePath();
9335        /** @see PackageSettingBase#resourcePathString */
9336        abstract String getResourcePath();
9337        abstract String getLegacyNativeLibraryPath();
9338
9339        // Need installer lock especially for dex file removal.
9340        abstract void cleanUpResourcesLI();
9341        abstract boolean doPostDeleteLI(boolean delete);
9342        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9343
9344        /**
9345         * Called before the source arguments are copied. This is used mostly
9346         * for MoveParams when it needs to read the source file to put it in the
9347         * destination.
9348         */
9349        int doPreCopy() {
9350            return PackageManager.INSTALL_SUCCEEDED;
9351        }
9352
9353        /**
9354         * Called after the source arguments are copied. This is used mostly for
9355         * MoveParams when it needs to read the source file to put it in the
9356         * destination.
9357         *
9358         * @return
9359         */
9360        int doPostCopy(int uid) {
9361            return PackageManager.INSTALL_SUCCEEDED;
9362        }
9363
9364        protected boolean isFwdLocked() {
9365            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9366        }
9367
9368        protected boolean isExternal() {
9369            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9370        }
9371
9372        UserHandle getUser() {
9373            return user;
9374        }
9375    }
9376
9377    /**
9378     * Logic to handle installation of non-ASEC applications, including copying
9379     * and renaming logic.
9380     */
9381    class FileInstallArgs extends InstallArgs {
9382        private File codeFile;
9383        private File resourceFile;
9384        private File legacyNativeLibraryPath;
9385
9386        // Example topology:
9387        // /data/app/com.example/base.apk
9388        // /data/app/com.example/split_foo.apk
9389        // /data/app/com.example/lib/arm/libfoo.so
9390        // /data/app/com.example/lib/arm64/libfoo.so
9391        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9392
9393        /** New install */
9394        FileInstallArgs(InstallParams params) {
9395            super(params.origin, params.observer, params.installFlags,
9396                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9397                    null /* instruction sets */, params.packageAbiOverride);
9398            if (isFwdLocked()) {
9399                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9400            }
9401        }
9402
9403        /** Existing install */
9404        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9405                String[] instructionSets) {
9406            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9407            this.codeFile = (codePath != null) ? new File(codePath) : null;
9408            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9409            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9410                    new File(legacyNativeLibraryPath) : null;
9411        }
9412
9413        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9414            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9415                    isFwdLocked(), abiOverride);
9416
9417            final StorageManager storage = StorageManager.from(mContext);
9418            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9419        }
9420
9421        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9422            if (origin.staged) {
9423                Slog.d(TAG, origin.file + " already staged; skipping copy");
9424                codeFile = origin.file;
9425                resourceFile = origin.file;
9426                return PackageManager.INSTALL_SUCCEEDED;
9427            }
9428
9429            try {
9430                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9431                codeFile = tempDir;
9432                resourceFile = tempDir;
9433            } catch (IOException e) {
9434                Slog.w(TAG, "Failed to create copy file: " + e);
9435                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9436            }
9437
9438            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9439                @Override
9440                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9441                    if (!FileUtils.isValidExtFilename(name)) {
9442                        throw new IllegalArgumentException("Invalid filename: " + name);
9443                    }
9444                    try {
9445                        final File file = new File(codeFile, name);
9446                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9447                                O_RDWR | O_CREAT, 0644);
9448                        Os.chmod(file.getAbsolutePath(), 0644);
9449                        return new ParcelFileDescriptor(fd);
9450                    } catch (ErrnoException e) {
9451                        throw new RemoteException("Failed to open: " + e.getMessage());
9452                    }
9453                }
9454            };
9455
9456            int ret = PackageManager.INSTALL_SUCCEEDED;
9457            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9458            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9459                Slog.e(TAG, "Failed to copy package");
9460                return ret;
9461            }
9462
9463            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9464            NativeLibraryHelper.Handle handle = null;
9465            try {
9466                handle = NativeLibraryHelper.Handle.create(codeFile);
9467                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9468                        abiOverride);
9469            } catch (IOException e) {
9470                Slog.e(TAG, "Copying native libraries failed", e);
9471                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9472            } finally {
9473                IoUtils.closeQuietly(handle);
9474            }
9475
9476            return ret;
9477        }
9478
9479        int doPreInstall(int status) {
9480            if (status != PackageManager.INSTALL_SUCCEEDED) {
9481                cleanUp();
9482            }
9483            return status;
9484        }
9485
9486        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9487            if (status != PackageManager.INSTALL_SUCCEEDED) {
9488                cleanUp();
9489                return false;
9490            } else {
9491                final File beforeCodeFile = codeFile;
9492                final File afterCodeFile = getNextCodePath(pkg.packageName);
9493
9494                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9495                try {
9496                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9497                } catch (ErrnoException e) {
9498                    Slog.d(TAG, "Failed to rename", e);
9499                    return false;
9500                }
9501
9502                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9503                    Slog.d(TAG, "Failed to restorecon");
9504                    return false;
9505                }
9506
9507                // Reflect the rename internally
9508                codeFile = afterCodeFile;
9509                resourceFile = afterCodeFile;
9510
9511                // Reflect the rename in scanned details
9512                pkg.codePath = afterCodeFile.getAbsolutePath();
9513                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9514                        pkg.baseCodePath);
9515                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9516                        pkg.splitCodePaths);
9517
9518                // Reflect the rename in app info
9519                pkg.applicationInfo.setCodePath(pkg.codePath);
9520                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9521                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9522                pkg.applicationInfo.setResourcePath(pkg.codePath);
9523                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9524                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9525
9526                return true;
9527            }
9528        }
9529
9530        int doPostInstall(int status, int uid) {
9531            if (status != PackageManager.INSTALL_SUCCEEDED) {
9532                cleanUp();
9533            }
9534            return status;
9535        }
9536
9537        @Override
9538        String getCodePath() {
9539            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9540        }
9541
9542        @Override
9543        String getResourcePath() {
9544            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9545        }
9546
9547        @Override
9548        String getLegacyNativeLibraryPath() {
9549            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9550        }
9551
9552        private boolean cleanUp() {
9553            if (codeFile == null || !codeFile.exists()) {
9554                return false;
9555            }
9556
9557            if (codeFile.isDirectory()) {
9558                FileUtils.deleteContents(codeFile);
9559            }
9560            codeFile.delete();
9561
9562            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9563                resourceFile.delete();
9564            }
9565
9566            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9567                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9568                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9569                }
9570                legacyNativeLibraryPath.delete();
9571            }
9572
9573            return true;
9574        }
9575
9576        void cleanUpResourcesLI() {
9577            // Try enumerating all code paths before deleting
9578            List<String> allCodePaths = Collections.EMPTY_LIST;
9579            if (codeFile != null && codeFile.exists()) {
9580                try {
9581                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9582                    allCodePaths = pkg.getAllCodePaths();
9583                } catch (PackageParserException e) {
9584                    // Ignored; we tried our best
9585                }
9586            }
9587
9588            cleanUp();
9589
9590            if (!allCodePaths.isEmpty()) {
9591                if (instructionSets == null) {
9592                    throw new IllegalStateException("instructionSet == null");
9593                }
9594                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9595                for (String codePath : allCodePaths) {
9596                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9597                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9598                        if (retCode < 0) {
9599                            Slog.w(TAG, "Couldn't remove dex file for package: "
9600                                    + " at location " + codePath + ", retcode=" + retCode);
9601                            // we don't consider this to be a failure of the core package deletion
9602                        }
9603                    }
9604                }
9605            }
9606        }
9607
9608        boolean doPostDeleteLI(boolean delete) {
9609            // XXX err, shouldn't we respect the delete flag?
9610            cleanUpResourcesLI();
9611            return true;
9612        }
9613    }
9614
9615    private boolean isAsecExternal(String cid) {
9616        final String asecPath = PackageHelper.getSdFilesystem(cid);
9617        return !asecPath.startsWith(mAsecInternalPath);
9618    }
9619
9620    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9621            PackageManagerException {
9622        if (copyRet < 0) {
9623            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9624                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9625                throw new PackageManagerException(copyRet, message);
9626            }
9627        }
9628    }
9629
9630    /**
9631     * Extract the MountService "container ID" from the full code path of an
9632     * .apk.
9633     */
9634    static String cidFromCodePath(String fullCodePath) {
9635        int eidx = fullCodePath.lastIndexOf("/");
9636        String subStr1 = fullCodePath.substring(0, eidx);
9637        int sidx = subStr1.lastIndexOf("/");
9638        return subStr1.substring(sidx+1, eidx);
9639    }
9640
9641    /**
9642     * Logic to handle installation of ASEC applications, including copying and
9643     * renaming logic.
9644     */
9645    class AsecInstallArgs extends InstallArgs {
9646        static final String RES_FILE_NAME = "pkg.apk";
9647        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9648
9649        String cid;
9650        String packagePath;
9651        String resourcePath;
9652        String legacyNativeLibraryDir;
9653
9654        /** New install */
9655        AsecInstallArgs(InstallParams params) {
9656            super(params.origin, params.observer, params.installFlags,
9657                    params.installerPackageName, params.getManifestDigest(),
9658                    params.getUser(), null /* instruction sets */,
9659                    params.packageAbiOverride);
9660        }
9661
9662        /** Existing install */
9663        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9664                        boolean isExternal, boolean isForwardLocked) {
9665            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9666                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9667                    instructionSets, null);
9668            // Hackily pretend we're still looking at a full code path
9669            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9670                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9671            }
9672
9673            // Extract cid from fullCodePath
9674            int eidx = fullCodePath.lastIndexOf("/");
9675            String subStr1 = fullCodePath.substring(0, eidx);
9676            int sidx = subStr1.lastIndexOf("/");
9677            cid = subStr1.substring(sidx+1, eidx);
9678            setMountPath(subStr1);
9679        }
9680
9681        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9682            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9683                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9684                    instructionSets, null);
9685            this.cid = cid;
9686            setMountPath(PackageHelper.getSdDir(cid));
9687        }
9688
9689        void createCopyFile() {
9690            cid = mInstallerService.allocateExternalStageCidLegacy();
9691        }
9692
9693        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9694            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9695                    abiOverride);
9696
9697            final File target;
9698            if (isExternal()) {
9699                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9700            } else {
9701                target = Environment.getDataDirectory();
9702            }
9703
9704            final StorageManager storage = StorageManager.from(mContext);
9705            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9706        }
9707
9708        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9709            if (origin.staged) {
9710                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9711                cid = origin.cid;
9712                setMountPath(PackageHelper.getSdDir(cid));
9713                return PackageManager.INSTALL_SUCCEEDED;
9714            }
9715
9716            if (temp) {
9717                createCopyFile();
9718            } else {
9719                /*
9720                 * Pre-emptively destroy the container since it's destroyed if
9721                 * copying fails due to it existing anyway.
9722                 */
9723                PackageHelper.destroySdDir(cid);
9724            }
9725
9726            final String newMountPath = imcs.copyPackageToContainer(
9727                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9728                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9729
9730            if (newMountPath != null) {
9731                setMountPath(newMountPath);
9732                return PackageManager.INSTALL_SUCCEEDED;
9733            } else {
9734                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9735            }
9736        }
9737
9738        @Override
9739        String getCodePath() {
9740            return packagePath;
9741        }
9742
9743        @Override
9744        String getResourcePath() {
9745            return resourcePath;
9746        }
9747
9748        @Override
9749        String getLegacyNativeLibraryPath() {
9750            return legacyNativeLibraryDir;
9751        }
9752
9753        int doPreInstall(int status) {
9754            if (status != PackageManager.INSTALL_SUCCEEDED) {
9755                // Destroy container
9756                PackageHelper.destroySdDir(cid);
9757            } else {
9758                boolean mounted = PackageHelper.isContainerMounted(cid);
9759                if (!mounted) {
9760                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9761                            Process.SYSTEM_UID);
9762                    if (newMountPath != null) {
9763                        setMountPath(newMountPath);
9764                    } else {
9765                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9766                    }
9767                }
9768            }
9769            return status;
9770        }
9771
9772        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9773            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9774            String newMountPath = null;
9775            if (PackageHelper.isContainerMounted(cid)) {
9776                // Unmount the container
9777                if (!PackageHelper.unMountSdDir(cid)) {
9778                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9779                    return false;
9780                }
9781            }
9782            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9783                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9784                        " which might be stale. Will try to clean up.");
9785                // Clean up the stale container and proceed to recreate.
9786                if (!PackageHelper.destroySdDir(newCacheId)) {
9787                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9788                    return false;
9789                }
9790                // Successfully cleaned up stale container. Try to rename again.
9791                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9792                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9793                            + " inspite of cleaning it up.");
9794                    return false;
9795                }
9796            }
9797            if (!PackageHelper.isContainerMounted(newCacheId)) {
9798                Slog.w(TAG, "Mounting container " + newCacheId);
9799                newMountPath = PackageHelper.mountSdDir(newCacheId,
9800                        getEncryptKey(), Process.SYSTEM_UID);
9801            } else {
9802                newMountPath = PackageHelper.getSdDir(newCacheId);
9803            }
9804            if (newMountPath == null) {
9805                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9806                return false;
9807            }
9808            Log.i(TAG, "Succesfully renamed " + cid +
9809                    " to " + newCacheId +
9810                    " at new path: " + newMountPath);
9811            cid = newCacheId;
9812
9813            final File beforeCodeFile = new File(packagePath);
9814            setMountPath(newMountPath);
9815            final File afterCodeFile = new File(packagePath);
9816
9817            // Reflect the rename in scanned details
9818            pkg.codePath = afterCodeFile.getAbsolutePath();
9819            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9820                    pkg.baseCodePath);
9821            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9822                    pkg.splitCodePaths);
9823
9824            // Reflect the rename in app info
9825            pkg.applicationInfo.setCodePath(pkg.codePath);
9826            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9827            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9828            pkg.applicationInfo.setResourcePath(pkg.codePath);
9829            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9830            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9831
9832            return true;
9833        }
9834
9835        private void setMountPath(String mountPath) {
9836            final File mountFile = new File(mountPath);
9837
9838            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9839            if (monolithicFile.exists()) {
9840                packagePath = monolithicFile.getAbsolutePath();
9841                if (isFwdLocked()) {
9842                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9843                } else {
9844                    resourcePath = packagePath;
9845                }
9846            } else {
9847                packagePath = mountFile.getAbsolutePath();
9848                resourcePath = packagePath;
9849            }
9850
9851            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9852        }
9853
9854        int doPostInstall(int status, int uid) {
9855            if (status != PackageManager.INSTALL_SUCCEEDED) {
9856                cleanUp();
9857            } else {
9858                final int groupOwner;
9859                final String protectedFile;
9860                if (isFwdLocked()) {
9861                    groupOwner = UserHandle.getSharedAppGid(uid);
9862                    protectedFile = RES_FILE_NAME;
9863                } else {
9864                    groupOwner = -1;
9865                    protectedFile = null;
9866                }
9867
9868                if (uid < Process.FIRST_APPLICATION_UID
9869                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9870                    Slog.e(TAG, "Failed to finalize " + cid);
9871                    PackageHelper.destroySdDir(cid);
9872                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9873                }
9874
9875                boolean mounted = PackageHelper.isContainerMounted(cid);
9876                if (!mounted) {
9877                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9878                }
9879            }
9880            return status;
9881        }
9882
9883        private void cleanUp() {
9884            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9885
9886            // Destroy secure container
9887            PackageHelper.destroySdDir(cid);
9888        }
9889
9890        private List<String> getAllCodePaths() {
9891            final File codeFile = new File(getCodePath());
9892            if (codeFile != null && codeFile.exists()) {
9893                try {
9894                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9895                    return pkg.getAllCodePaths();
9896                } catch (PackageParserException e) {
9897                    // Ignored; we tried our best
9898                }
9899            }
9900            return Collections.EMPTY_LIST;
9901        }
9902
9903        void cleanUpResourcesLI() {
9904            // Enumerate all code paths before deleting
9905            cleanUpResourcesLI(getAllCodePaths());
9906        }
9907
9908        private void cleanUpResourcesLI(List<String> allCodePaths) {
9909            cleanUp();
9910
9911            if (!allCodePaths.isEmpty()) {
9912                if (instructionSets == null) {
9913                    throw new IllegalStateException("instructionSet == null");
9914                }
9915                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9916                for (String codePath : allCodePaths) {
9917                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9918                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9919                        if (retCode < 0) {
9920                            Slog.w(TAG, "Couldn't remove dex file for package: "
9921                                    + " at location " + codePath + ", retcode=" + retCode);
9922                            // we don't consider this to be a failure of the core package deletion
9923                        }
9924                    }
9925                }
9926            }
9927        }
9928
9929        boolean matchContainer(String app) {
9930            if (cid.startsWith(app)) {
9931                return true;
9932            }
9933            return false;
9934        }
9935
9936        String getPackageName() {
9937            return getAsecPackageName(cid);
9938        }
9939
9940        boolean doPostDeleteLI(boolean delete) {
9941            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9942            final List<String> allCodePaths = getAllCodePaths();
9943            boolean mounted = PackageHelper.isContainerMounted(cid);
9944            if (mounted) {
9945                // Unmount first
9946                if (PackageHelper.unMountSdDir(cid)) {
9947                    mounted = false;
9948                }
9949            }
9950            if (!mounted && delete) {
9951                cleanUpResourcesLI(allCodePaths);
9952            }
9953            return !mounted;
9954        }
9955
9956        @Override
9957        int doPreCopy() {
9958            if (isFwdLocked()) {
9959                if (!PackageHelper.fixSdPermissions(cid,
9960                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9961                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9962                }
9963            }
9964
9965            return PackageManager.INSTALL_SUCCEEDED;
9966        }
9967
9968        @Override
9969        int doPostCopy(int uid) {
9970            if (isFwdLocked()) {
9971                if (uid < Process.FIRST_APPLICATION_UID
9972                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9973                                RES_FILE_NAME)) {
9974                    Slog.e(TAG, "Failed to finalize " + cid);
9975                    PackageHelper.destroySdDir(cid);
9976                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9977                }
9978            }
9979
9980            return PackageManager.INSTALL_SUCCEEDED;
9981        }
9982    }
9983
9984    static String getAsecPackageName(String packageCid) {
9985        int idx = packageCid.lastIndexOf("-");
9986        if (idx == -1) {
9987            return packageCid;
9988        }
9989        return packageCid.substring(0, idx);
9990    }
9991
9992    // Utility method used to create code paths based on package name and available index.
9993    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9994        String idxStr = "";
9995        int idx = 1;
9996        // Fall back to default value of idx=1 if prefix is not
9997        // part of oldCodePath
9998        if (oldCodePath != null) {
9999            String subStr = oldCodePath;
10000            // Drop the suffix right away
10001            if (suffix != null && subStr.endsWith(suffix)) {
10002                subStr = subStr.substring(0, subStr.length() - suffix.length());
10003            }
10004            // If oldCodePath already contains prefix find out the
10005            // ending index to either increment or decrement.
10006            int sidx = subStr.lastIndexOf(prefix);
10007            if (sidx != -1) {
10008                subStr = subStr.substring(sidx + prefix.length());
10009                if (subStr != null) {
10010                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10011                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10012                    }
10013                    try {
10014                        idx = Integer.parseInt(subStr);
10015                        if (idx <= 1) {
10016                            idx++;
10017                        } else {
10018                            idx--;
10019                        }
10020                    } catch(NumberFormatException e) {
10021                    }
10022                }
10023            }
10024        }
10025        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10026        return prefix + idxStr;
10027    }
10028
10029    private File getNextCodePath(String packageName) {
10030        int suffix = 1;
10031        File result;
10032        do {
10033            result = new File(mAppInstallDir, packageName + "-" + suffix);
10034            suffix++;
10035        } while (result.exists());
10036        return result;
10037    }
10038
10039    // Utility method used to ignore ADD/REMOVE events
10040    // by directory observer.
10041    private static boolean ignoreCodePath(String fullPathStr) {
10042        String apkName = deriveCodePathName(fullPathStr);
10043        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
10044        if (idx != -1 && ((idx+1) < apkName.length())) {
10045            // Make sure the package ends with a numeral
10046            String version = apkName.substring(idx+1);
10047            try {
10048                Integer.parseInt(version);
10049                return true;
10050            } catch (NumberFormatException e) {}
10051        }
10052        return false;
10053    }
10054
10055    // Utility method that returns the relative package path with respect
10056    // to the installation directory. Like say for /data/data/com.test-1.apk
10057    // string com.test-1 is returned.
10058    static String deriveCodePathName(String codePath) {
10059        if (codePath == null) {
10060            return null;
10061        }
10062        final File codeFile = new File(codePath);
10063        final String name = codeFile.getName();
10064        if (codeFile.isDirectory()) {
10065            return name;
10066        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10067            final int lastDot = name.lastIndexOf('.');
10068            return name.substring(0, lastDot);
10069        } else {
10070            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10071            return null;
10072        }
10073    }
10074
10075    class PackageInstalledInfo {
10076        String name;
10077        int uid;
10078        // The set of users that originally had this package installed.
10079        int[] origUsers;
10080        // The set of users that now have this package installed.
10081        int[] newUsers;
10082        PackageParser.Package pkg;
10083        int returnCode;
10084        String returnMsg;
10085        PackageRemovedInfo removedInfo;
10086
10087        public void setError(int code, String msg) {
10088            returnCode = code;
10089            returnMsg = msg;
10090            Slog.w(TAG, msg);
10091        }
10092
10093        public void setError(String msg, PackageParserException e) {
10094            returnCode = e.error;
10095            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10096            Slog.w(TAG, msg, e);
10097        }
10098
10099        public void setError(String msg, PackageManagerException e) {
10100            returnCode = e.error;
10101            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10102            Slog.w(TAG, msg, e);
10103        }
10104
10105        // In some error cases we want to convey more info back to the observer
10106        String origPackage;
10107        String origPermission;
10108    }
10109
10110    /*
10111     * Install a non-existing package.
10112     */
10113    private void installNewPackageLI(PackageParser.Package pkg,
10114            int parseFlags, int scanFlags, UserHandle user,
10115            String installerPackageName, PackageInstalledInfo res) {
10116        // Remember this for later, in case we need to rollback this install
10117        String pkgName = pkg.packageName;
10118
10119        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10120        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10121        synchronized(mPackages) {
10122            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10123                // A package with the same name is already installed, though
10124                // it has been renamed to an older name.  The package we
10125                // are trying to install should be installed as an update to
10126                // the existing one, but that has not been requested, so bail.
10127                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10128                        + " without first uninstalling package running as "
10129                        + mSettings.mRenamedPackages.get(pkgName));
10130                return;
10131            }
10132            if (mPackages.containsKey(pkgName)) {
10133                // Don't allow installation over an existing package with the same name.
10134                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10135                        + " without first uninstalling.");
10136                return;
10137            }
10138        }
10139
10140        try {
10141            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10142                    System.currentTimeMillis(), user);
10143
10144            updateSettingsLI(newPackage, installerPackageName, null, null, res);
10145            // delete the partially installed application. the data directory will have to be
10146            // restored if it was already existing
10147            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10148                // remove package from internal structures.  Note that we want deletePackageX to
10149                // delete the package data and cache directories that it created in
10150                // scanPackageLocked, unless those directories existed before we even tried to
10151                // install.
10152                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10153                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10154                                res.removedInfo, true);
10155            }
10156
10157        } catch (PackageManagerException e) {
10158            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10159        }
10160    }
10161
10162    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10163        // Upgrade keysets are being used.  Determine if new package has a superset of the
10164        // required keys.
10165        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10166        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10167        for (int i = 0; i < upgradeKeySets.length; i++) {
10168            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10169            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10170                return true;
10171            }
10172        }
10173        return false;
10174    }
10175
10176    private void replacePackageLI(PackageParser.Package pkg,
10177            int parseFlags, int scanFlags, UserHandle user,
10178            String installerPackageName, PackageInstalledInfo res) {
10179        PackageParser.Package oldPackage;
10180        String pkgName = pkg.packageName;
10181        int[] allUsers;
10182        boolean[] perUserInstalled;
10183
10184        // First find the old package info and check signatures
10185        synchronized(mPackages) {
10186            oldPackage = mPackages.get(pkgName);
10187            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10188            PackageSetting ps = mSettings.mPackages.get(pkgName);
10189            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10190                // default to original signature matching
10191                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10192                    != PackageManager.SIGNATURE_MATCH) {
10193                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10194                            "New package has a different signature: " + pkgName);
10195                    return;
10196                }
10197            } else {
10198                if(!checkUpgradeKeySetLP(ps, pkg)) {
10199                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10200                            "New package not signed by keys specified by upgrade-keysets: "
10201                            + pkgName);
10202                    return;
10203                }
10204            }
10205
10206            // In case of rollback, remember per-user/profile install state
10207            allUsers = sUserManager.getUserIds();
10208            perUserInstalled = new boolean[allUsers.length];
10209            for (int i = 0; i < allUsers.length; i++) {
10210                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10211            }
10212        }
10213
10214        boolean sysPkg = (isSystemApp(oldPackage));
10215        if (sysPkg) {
10216            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10217                    user, allUsers, perUserInstalled, installerPackageName, res);
10218        } else {
10219            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10220                    user, allUsers, perUserInstalled, installerPackageName, res);
10221        }
10222    }
10223
10224    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10225            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10226            int[] allUsers, boolean[] perUserInstalled,
10227            String installerPackageName, PackageInstalledInfo res) {
10228        String pkgName = deletedPackage.packageName;
10229        boolean deletedPkg = true;
10230        boolean updatedSettings = false;
10231
10232        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10233                + deletedPackage);
10234        long origUpdateTime;
10235        if (pkg.mExtras != null) {
10236            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10237        } else {
10238            origUpdateTime = 0;
10239        }
10240
10241        // First delete the existing package while retaining the data directory
10242        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10243                res.removedInfo, true)) {
10244            // If the existing package wasn't successfully deleted
10245            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10246            deletedPkg = false;
10247        } else {
10248            // Successfully deleted the old package; proceed with replace.
10249
10250            // If deleted package lived in a container, give users a chance to
10251            // relinquish resources before killing.
10252            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
10253                if (DEBUG_INSTALL) {
10254                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10255                }
10256                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10257                final ArrayList<String> pkgList = new ArrayList<String>(1);
10258                pkgList.add(deletedPackage.applicationInfo.packageName);
10259                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10260            }
10261
10262            deleteCodeCacheDirsLI(pkgName);
10263            try {
10264                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10265                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10266                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10267                updatedSettings = true;
10268            } catch (PackageManagerException e) {
10269                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10270            }
10271        }
10272
10273        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10274            // remove package from internal structures.  Note that we want deletePackageX to
10275            // delete the package data and cache directories that it created in
10276            // scanPackageLocked, unless those directories existed before we even tried to
10277            // install.
10278            if(updatedSettings) {
10279                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10280                deletePackageLI(
10281                        pkgName, null, true, allUsers, perUserInstalled,
10282                        PackageManager.DELETE_KEEP_DATA,
10283                                res.removedInfo, true);
10284            }
10285            // Since we failed to install the new package we need to restore the old
10286            // package that we deleted.
10287            if (deletedPkg) {
10288                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10289                File restoreFile = new File(deletedPackage.codePath);
10290                // Parse old package
10291                boolean oldOnSd = isExternal(deletedPackage);
10292                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10293                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10294                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10295                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10296                try {
10297                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10298                } catch (PackageManagerException e) {
10299                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10300                            + e.getMessage());
10301                    return;
10302                }
10303                // Restore of old package succeeded. Update permissions.
10304                // writer
10305                synchronized (mPackages) {
10306                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10307                            UPDATE_PERMISSIONS_ALL);
10308                    // can downgrade to reader
10309                    mSettings.writeLPr();
10310                }
10311                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10312            }
10313        }
10314    }
10315
10316    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10317            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10318            int[] allUsers, boolean[] perUserInstalled,
10319            String installerPackageName, PackageInstalledInfo res) {
10320        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10321                + ", old=" + deletedPackage);
10322        boolean disabledSystem = false;
10323        boolean updatedSettings = false;
10324        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10325        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10326            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10327        }
10328        String packageName = deletedPackage.packageName;
10329        if (packageName == null) {
10330            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10331                    "Attempt to delete null packageName.");
10332            return;
10333        }
10334        PackageParser.Package oldPkg;
10335        PackageSetting oldPkgSetting;
10336        // reader
10337        synchronized (mPackages) {
10338            oldPkg = mPackages.get(packageName);
10339            oldPkgSetting = mSettings.mPackages.get(packageName);
10340            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10341                    (oldPkgSetting == null)) {
10342                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10343                        "Couldn't find package:" + packageName + " information");
10344                return;
10345            }
10346        }
10347
10348        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10349
10350        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10351        res.removedInfo.removedPackage = packageName;
10352        // Remove existing system package
10353        removePackageLI(oldPkgSetting, true);
10354        // writer
10355        synchronized (mPackages) {
10356            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10357            if (!disabledSystem && deletedPackage != null) {
10358                // We didn't need to disable the .apk as a current system package,
10359                // which means we are replacing another update that is already
10360                // installed.  We need to make sure to delete the older one's .apk.
10361                res.removedInfo.args = createInstallArgsForExisting(0,
10362                        deletedPackage.applicationInfo.getCodePath(),
10363                        deletedPackage.applicationInfo.getResourcePath(),
10364                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10365                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10366            } else {
10367                res.removedInfo.args = null;
10368            }
10369        }
10370
10371        // Successfully disabled the old package. Now proceed with re-installation
10372        deleteCodeCacheDirsLI(packageName);
10373
10374        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10375        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10376
10377        PackageParser.Package newPackage = null;
10378        try {
10379            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10380            if (newPackage.mExtras != null) {
10381                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10382                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10383                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10384
10385                // is the update attempting to change shared user? that isn't going to work...
10386                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10387                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10388                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10389                            + " to " + newPkgSetting.sharedUser);
10390                    updatedSettings = true;
10391                }
10392            }
10393
10394            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10395                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10396                updatedSettings = true;
10397            }
10398
10399        } catch (PackageManagerException e) {
10400            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10401        }
10402
10403        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10404            // Re installation failed. Restore old information
10405            // Remove new pkg information
10406            if (newPackage != null) {
10407                removeInstalledPackageLI(newPackage, true);
10408            }
10409            // Add back the old system package
10410            try {
10411                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10412            } catch (PackageManagerException e) {
10413                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10414            }
10415            // Restore the old system information in Settings
10416            synchronized (mPackages) {
10417                if (disabledSystem) {
10418                    mSettings.enableSystemPackageLPw(packageName);
10419                }
10420                if (updatedSettings) {
10421                    mSettings.setInstallerPackageName(packageName,
10422                            oldPkgSetting.installerPackageName);
10423                }
10424                mSettings.writeLPr();
10425            }
10426        }
10427    }
10428
10429    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10430            int[] allUsers, boolean[] perUserInstalled,
10431            PackageInstalledInfo res) {
10432        String pkgName = newPackage.packageName;
10433        synchronized (mPackages) {
10434            //write settings. the installStatus will be incomplete at this stage.
10435            //note that the new package setting would have already been
10436            //added to mPackages. It hasn't been persisted yet.
10437            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10438            mSettings.writeLPr();
10439        }
10440
10441        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10442
10443        synchronized (mPackages) {
10444            updatePermissionsLPw(newPackage.packageName, newPackage,
10445                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10446                            ? UPDATE_PERMISSIONS_ALL : 0));
10447            // For system-bundled packages, we assume that installing an upgraded version
10448            // of the package implies that the user actually wants to run that new code,
10449            // so we enable the package.
10450            if (isSystemApp(newPackage)) {
10451                // NB: implicit assumption that system package upgrades apply to all users
10452                if (DEBUG_INSTALL) {
10453                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10454                }
10455                PackageSetting ps = mSettings.mPackages.get(pkgName);
10456                if (ps != null) {
10457                    if (res.origUsers != null) {
10458                        for (int userHandle : res.origUsers) {
10459                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10460                                    userHandle, installerPackageName);
10461                        }
10462                    }
10463                    // Also convey the prior install/uninstall state
10464                    if (allUsers != null && perUserInstalled != null) {
10465                        for (int i = 0; i < allUsers.length; i++) {
10466                            if (DEBUG_INSTALL) {
10467                                Slog.d(TAG, "    user " + allUsers[i]
10468                                        + " => " + perUserInstalled[i]);
10469                            }
10470                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10471                        }
10472                        // these install state changes will be persisted in the
10473                        // upcoming call to mSettings.writeLPr().
10474                    }
10475                }
10476            }
10477            res.name = pkgName;
10478            res.uid = newPackage.applicationInfo.uid;
10479            res.pkg = newPackage;
10480            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10481            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10482            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10483            //to update install status
10484            mSettings.writeLPr();
10485        }
10486    }
10487
10488    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10489        final int installFlags = args.installFlags;
10490        String installerPackageName = args.installerPackageName;
10491        File tmpPackageFile = new File(args.getCodePath());
10492        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10493        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10494        boolean replace = false;
10495        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10496        // Result object to be returned
10497        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10498
10499        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10500        // Retrieve PackageSettings and parse package
10501        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10502                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10503                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10504        PackageParser pp = new PackageParser();
10505        pp.setSeparateProcesses(mSeparateProcesses);
10506        pp.setDisplayMetrics(mMetrics);
10507
10508        final PackageParser.Package pkg;
10509        try {
10510            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10511        } catch (PackageParserException e) {
10512            res.setError("Failed parse during installPackageLI", e);
10513            return;
10514        }
10515
10516        // Mark that we have an install time CPU ABI override.
10517        pkg.cpuAbiOverride = args.abiOverride;
10518
10519        String pkgName = res.name = pkg.packageName;
10520        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10521            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10522                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10523                return;
10524            }
10525        }
10526
10527        try {
10528            pp.collectCertificates(pkg, parseFlags);
10529            pp.collectManifestDigest(pkg);
10530        } catch (PackageParserException e) {
10531            res.setError("Failed collect during installPackageLI", e);
10532            return;
10533        }
10534
10535        /* If the installer passed in a manifest digest, compare it now. */
10536        if (args.manifestDigest != null) {
10537            if (DEBUG_INSTALL) {
10538                final String parsedManifest = pkg.manifestDigest == null ? "null"
10539                        : pkg.manifestDigest.toString();
10540                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10541                        + parsedManifest);
10542            }
10543
10544            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10545                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10546                return;
10547            }
10548        } else if (DEBUG_INSTALL) {
10549            final String parsedManifest = pkg.manifestDigest == null
10550                    ? "null" : pkg.manifestDigest.toString();
10551            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10552        }
10553
10554        // Get rid of all references to package scan path via parser.
10555        pp = null;
10556        String oldCodePath = null;
10557        boolean systemApp = false;
10558        synchronized (mPackages) {
10559            // Check if installing already existing package
10560            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10561                String oldName = mSettings.mRenamedPackages.get(pkgName);
10562                if (pkg.mOriginalPackages != null
10563                        && pkg.mOriginalPackages.contains(oldName)
10564                        && mPackages.containsKey(oldName)) {
10565                    // This package is derived from an original package,
10566                    // and this device has been updating from that original
10567                    // name.  We must continue using the original name, so
10568                    // rename the new package here.
10569                    pkg.setPackageName(oldName);
10570                    pkgName = pkg.packageName;
10571                    replace = true;
10572                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10573                            + oldName + " pkgName=" + pkgName);
10574                } else if (mPackages.containsKey(pkgName)) {
10575                    // This package, under its official name, already exists
10576                    // on the device; we should replace it.
10577                    replace = true;
10578                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10579                }
10580            }
10581
10582            PackageSetting ps = mSettings.mPackages.get(pkgName);
10583            if (ps != null) {
10584                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10585
10586                // Quick sanity check that we're signed correctly if updating;
10587                // we'll check this again later when scanning, but we want to
10588                // bail early here before tripping over redefined permissions.
10589                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10590                    try {
10591                        verifySignaturesLP(ps, pkg);
10592                    } catch (PackageManagerException e) {
10593                        res.setError(e.error, e.getMessage());
10594                        return;
10595                    }
10596                } else {
10597                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10598                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10599                                + pkg.packageName + " upgrade keys do not match the "
10600                                + "previously installed version");
10601                        return;
10602                    }
10603                }
10604
10605                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10606                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10607                    systemApp = (ps.pkg.applicationInfo.flags &
10608                            ApplicationInfo.FLAG_SYSTEM) != 0;
10609                }
10610                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10611            }
10612
10613            // Check whether the newly-scanned package wants to define an already-defined perm
10614            int N = pkg.permissions.size();
10615            for (int i = N-1; i >= 0; i--) {
10616                PackageParser.Permission perm = pkg.permissions.get(i);
10617                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10618                if (bp != null) {
10619                    // If the defining package is signed with our cert, it's okay.  This
10620                    // also includes the "updating the same package" case, of course.
10621                    // "updating same package" could also involve key-rotation.
10622                    final boolean sigsOk;
10623                    if (!bp.sourcePackage.equals(pkg.packageName)
10624                            || !(bp.packageSetting instanceof PackageSetting)
10625                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10626                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10627                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10628                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10629                    } else {
10630                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10631                    }
10632                    if (!sigsOk) {
10633                        // If the owning package is the system itself, we log but allow
10634                        // install to proceed; we fail the install on all other permission
10635                        // redefinitions.
10636                        if (!bp.sourcePackage.equals("android")) {
10637                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10638                                    + pkg.packageName + " attempting to redeclare permission "
10639                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10640                            res.origPermission = perm.info.name;
10641                            res.origPackage = bp.sourcePackage;
10642                            return;
10643                        } else {
10644                            Slog.w(TAG, "Package " + pkg.packageName
10645                                    + " attempting to redeclare system permission "
10646                                    + perm.info.name + "; ignoring new declaration");
10647                            pkg.permissions.remove(i);
10648                        }
10649                    }
10650                }
10651            }
10652
10653        }
10654
10655        if (systemApp && onSd) {
10656            // Disable updates to system apps on sdcard
10657            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10658                    "Cannot install updates to system apps on sdcard");
10659            return;
10660        }
10661
10662        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10663            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10664            return;
10665        }
10666
10667        if (replace) {
10668            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10669                    installerPackageName, res);
10670        } else {
10671            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10672                    args.user, installerPackageName, res);
10673        }
10674        synchronized (mPackages) {
10675            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10676            if (ps != null) {
10677                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10678            }
10679        }
10680    }
10681
10682    private static boolean isForwardLocked(PackageParser.Package pkg) {
10683        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10684    }
10685
10686    private static boolean isForwardLocked(ApplicationInfo info) {
10687        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10688    }
10689
10690    private boolean isForwardLocked(PackageSetting ps) {
10691        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10692    }
10693
10694    private static boolean isMultiArch(PackageSetting ps) {
10695        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10696    }
10697
10698    private static boolean isMultiArch(ApplicationInfo info) {
10699        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10700    }
10701
10702    private static boolean isExternal(PackageParser.Package pkg) {
10703        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10704    }
10705
10706    private static boolean isExternal(PackageSetting ps) {
10707        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10708    }
10709
10710    private static boolean isExternal(ApplicationInfo info) {
10711        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10712    }
10713
10714    private static boolean isSystemApp(PackageParser.Package pkg) {
10715        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10716    }
10717
10718    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10719        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10720    }
10721
10722    private static boolean isSystemApp(ApplicationInfo info) {
10723        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10724    }
10725
10726    private static boolean isSystemApp(PackageSetting ps) {
10727        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10728    }
10729
10730    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10731        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10732    }
10733
10734    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10735        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10736    }
10737
10738    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10739        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10740    }
10741
10742    private int packageFlagsToInstallFlags(PackageSetting ps) {
10743        int installFlags = 0;
10744        if (isExternal(ps)) {
10745            installFlags |= PackageManager.INSTALL_EXTERNAL;
10746        }
10747        if (isForwardLocked(ps)) {
10748            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10749        }
10750        return installFlags;
10751    }
10752
10753    private void deleteTempPackageFiles() {
10754        final FilenameFilter filter = new FilenameFilter() {
10755            public boolean accept(File dir, String name) {
10756                return name.startsWith("vmdl") && name.endsWith(".tmp");
10757            }
10758        };
10759        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10760            file.delete();
10761        }
10762    }
10763
10764    @Override
10765    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10766            int flags) {
10767        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10768                flags);
10769    }
10770
10771    @Override
10772    public void deletePackage(final String packageName,
10773            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10774        mContext.enforceCallingOrSelfPermission(
10775                android.Manifest.permission.DELETE_PACKAGES, null);
10776        final int uid = Binder.getCallingUid();
10777        if (UserHandle.getUserId(uid) != userId) {
10778            mContext.enforceCallingPermission(
10779                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10780                    "deletePackage for user " + userId);
10781        }
10782        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10783            try {
10784                observer.onPackageDeleted(packageName,
10785                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10786            } catch (RemoteException re) {
10787            }
10788            return;
10789        }
10790
10791        boolean uninstallBlocked = false;
10792        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10793            int[] users = sUserManager.getUserIds();
10794            for (int i = 0; i < users.length; ++i) {
10795                if (getBlockUninstallForUser(packageName, users[i])) {
10796                    uninstallBlocked = true;
10797                    break;
10798                }
10799            }
10800        } else {
10801            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10802        }
10803        if (uninstallBlocked) {
10804            try {
10805                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10806                        null);
10807            } catch (RemoteException re) {
10808            }
10809            return;
10810        }
10811
10812        if (DEBUG_REMOVE) {
10813            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10814        }
10815        // Queue up an async operation since the package deletion may take a little while.
10816        mHandler.post(new Runnable() {
10817            public void run() {
10818                mHandler.removeCallbacks(this);
10819                final int returnCode = deletePackageX(packageName, userId, flags);
10820                if (observer != null) {
10821                    try {
10822                        observer.onPackageDeleted(packageName, returnCode, null);
10823                    } catch (RemoteException e) {
10824                        Log.i(TAG, "Observer no longer exists.");
10825                    } //end catch
10826                } //end if
10827            } //end run
10828        });
10829    }
10830
10831    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10832        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10833                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10834        try {
10835            if (dpm != null) {
10836                if (dpm.isDeviceOwner(packageName)) {
10837                    return true;
10838                }
10839                int[] users;
10840                if (userId == UserHandle.USER_ALL) {
10841                    users = sUserManager.getUserIds();
10842                } else {
10843                    users = new int[]{userId};
10844                }
10845                for (int i = 0; i < users.length; ++i) {
10846                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10847                        return true;
10848                    }
10849                }
10850            }
10851        } catch (RemoteException e) {
10852        }
10853        return false;
10854    }
10855
10856    /**
10857     *  This method is an internal method that could be get invoked either
10858     *  to delete an installed package or to clean up a failed installation.
10859     *  After deleting an installed package, a broadcast is sent to notify any
10860     *  listeners that the package has been installed. For cleaning up a failed
10861     *  installation, the broadcast is not necessary since the package's
10862     *  installation wouldn't have sent the initial broadcast either
10863     *  The key steps in deleting a package are
10864     *  deleting the package information in internal structures like mPackages,
10865     *  deleting the packages base directories through installd
10866     *  updating mSettings to reflect current status
10867     *  persisting settings for later use
10868     *  sending a broadcast if necessary
10869     */
10870    private int deletePackageX(String packageName, int userId, int flags) {
10871        final PackageRemovedInfo info = new PackageRemovedInfo();
10872        final boolean res;
10873
10874        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10875                ? UserHandle.ALL : new UserHandle(userId);
10876
10877        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10878            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10879            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10880        }
10881
10882        boolean removedForAllUsers = false;
10883        boolean systemUpdate = false;
10884
10885        // for the uninstall-updates case and restricted profiles, remember the per-
10886        // userhandle installed state
10887        int[] allUsers;
10888        boolean[] perUserInstalled;
10889        synchronized (mPackages) {
10890            PackageSetting ps = mSettings.mPackages.get(packageName);
10891            allUsers = sUserManager.getUserIds();
10892            perUserInstalled = new boolean[allUsers.length];
10893            for (int i = 0; i < allUsers.length; i++) {
10894                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10895            }
10896        }
10897
10898        synchronized (mInstallLock) {
10899            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10900            res = deletePackageLI(packageName, removeForUser,
10901                    true, allUsers, perUserInstalled,
10902                    flags | REMOVE_CHATTY, info, true);
10903            systemUpdate = info.isRemovedPackageSystemUpdate;
10904            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10905                removedForAllUsers = true;
10906            }
10907            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10908                    + " removedForAllUsers=" + removedForAllUsers);
10909        }
10910
10911        if (res) {
10912            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10913
10914            // If the removed package was a system update, the old system package
10915            // was re-enabled; we need to broadcast this information
10916            if (systemUpdate) {
10917                Bundle extras = new Bundle(1);
10918                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10919                        ? info.removedAppId : info.uid);
10920                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10921
10922                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10923                        extras, null, null, null);
10924                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10925                        extras, null, null, null);
10926                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10927                        null, packageName, null, null);
10928            }
10929        }
10930        // Force a gc here.
10931        Runtime.getRuntime().gc();
10932        // Delete the resources here after sending the broadcast to let
10933        // other processes clean up before deleting resources.
10934        if (info.args != null) {
10935            synchronized (mInstallLock) {
10936                info.args.doPostDeleteLI(true);
10937            }
10938        }
10939
10940        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10941    }
10942
10943    static class PackageRemovedInfo {
10944        String removedPackage;
10945        int uid = -1;
10946        int removedAppId = -1;
10947        int[] removedUsers = null;
10948        boolean isRemovedPackageSystemUpdate = false;
10949        // Clean up resources deleted packages.
10950        InstallArgs args = null;
10951
10952        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10953            Bundle extras = new Bundle(1);
10954            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10955            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10956            if (replacing) {
10957                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10958            }
10959            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10960            if (removedPackage != null) {
10961                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10962                        extras, null, null, removedUsers);
10963                if (fullRemove && !replacing) {
10964                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10965                            extras, null, null, removedUsers);
10966                }
10967            }
10968            if (removedAppId >= 0) {
10969                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10970                        removedUsers);
10971            }
10972        }
10973    }
10974
10975    /*
10976     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10977     * flag is not set, the data directory is removed as well.
10978     * make sure this flag is set for partially installed apps. If not its meaningless to
10979     * delete a partially installed application.
10980     */
10981    private void removePackageDataLI(PackageSetting ps,
10982            int[] allUserHandles, boolean[] perUserInstalled,
10983            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10984        String packageName = ps.name;
10985        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10986        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10987        // Retrieve object to delete permissions for shared user later on
10988        final PackageSetting deletedPs;
10989        // reader
10990        synchronized (mPackages) {
10991            deletedPs = mSettings.mPackages.get(packageName);
10992            if (outInfo != null) {
10993                outInfo.removedPackage = packageName;
10994                outInfo.removedUsers = deletedPs != null
10995                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10996                        : null;
10997            }
10998        }
10999        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11000            removeDataDirsLI(packageName);
11001            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11002        }
11003        // writer
11004        synchronized (mPackages) {
11005            if (deletedPs != null) {
11006                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11007                    if (outInfo != null) {
11008                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11009                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11010                    }
11011                    if (deletedPs != null) {
11012                        updatePermissionsLPw(deletedPs.name, null, 0);
11013                        if (deletedPs.sharedUser != null) {
11014                            // remove permissions associated with package
11015                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
11016                        }
11017                    }
11018                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11019                }
11020                // make sure to preserve per-user disabled state if this removal was just
11021                // a downgrade of a system app to the factory package
11022                if (allUserHandles != null && perUserInstalled != null) {
11023                    if (DEBUG_REMOVE) {
11024                        Slog.d(TAG, "Propagating install state across downgrade");
11025                    }
11026                    for (int i = 0; i < allUserHandles.length; i++) {
11027                        if (DEBUG_REMOVE) {
11028                            Slog.d(TAG, "    user " + allUserHandles[i]
11029                                    + " => " + perUserInstalled[i]);
11030                        }
11031                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11032                    }
11033                }
11034            }
11035            // can downgrade to reader
11036            if (writeSettings) {
11037                // Save settings now
11038                mSettings.writeLPr();
11039            }
11040        }
11041        if (outInfo != null) {
11042            // A user ID was deleted here. Go through all users and remove it
11043            // from KeyStore.
11044            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11045        }
11046    }
11047
11048    static boolean locationIsPrivileged(File path) {
11049        try {
11050            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11051                    .getCanonicalPath();
11052            return path.getCanonicalPath().startsWith(privilegedAppDir);
11053        } catch (IOException e) {
11054            Slog.e(TAG, "Unable to access code path " + path);
11055        }
11056        return false;
11057    }
11058
11059    /*
11060     * Tries to delete system package.
11061     */
11062    private boolean deleteSystemPackageLI(PackageSetting newPs,
11063            int[] allUserHandles, boolean[] perUserInstalled,
11064            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11065        final boolean applyUserRestrictions
11066                = (allUserHandles != null) && (perUserInstalled != null);
11067        PackageSetting disabledPs = null;
11068        // Confirm if the system package has been updated
11069        // An updated system app can be deleted. This will also have to restore
11070        // the system pkg from system partition
11071        // reader
11072        synchronized (mPackages) {
11073            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11074        }
11075        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11076                + " disabledPs=" + disabledPs);
11077        if (disabledPs == null) {
11078            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11079            return false;
11080        } else if (DEBUG_REMOVE) {
11081            Slog.d(TAG, "Deleting system pkg from data partition");
11082        }
11083        if (DEBUG_REMOVE) {
11084            if (applyUserRestrictions) {
11085                Slog.d(TAG, "Remembering install states:");
11086                for (int i = 0; i < allUserHandles.length; i++) {
11087                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11088                }
11089            }
11090        }
11091        // Delete the updated package
11092        outInfo.isRemovedPackageSystemUpdate = true;
11093        if (disabledPs.versionCode < newPs.versionCode) {
11094            // Delete data for downgrades
11095            flags &= ~PackageManager.DELETE_KEEP_DATA;
11096        } else {
11097            // Preserve data by setting flag
11098            flags |= PackageManager.DELETE_KEEP_DATA;
11099        }
11100        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11101                allUserHandles, perUserInstalled, outInfo, writeSettings);
11102        if (!ret) {
11103            return false;
11104        }
11105        // writer
11106        synchronized (mPackages) {
11107            // Reinstate the old system package
11108            mSettings.enableSystemPackageLPw(newPs.name);
11109            // Remove any native libraries from the upgraded package.
11110            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11111        }
11112        // Install the system package
11113        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11114        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11115        if (locationIsPrivileged(disabledPs.codePath)) {
11116            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11117        }
11118
11119        final PackageParser.Package newPkg;
11120        try {
11121            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11122        } catch (PackageManagerException e) {
11123            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11124            return false;
11125        }
11126
11127        // writer
11128        synchronized (mPackages) {
11129            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11130            updatePermissionsLPw(newPkg.packageName, newPkg,
11131                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11132            if (applyUserRestrictions) {
11133                if (DEBUG_REMOVE) {
11134                    Slog.d(TAG, "Propagating install state across reinstall");
11135                }
11136                for (int i = 0; i < allUserHandles.length; i++) {
11137                    if (DEBUG_REMOVE) {
11138                        Slog.d(TAG, "    user " + allUserHandles[i]
11139                                + " => " + perUserInstalled[i]);
11140                    }
11141                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11142                }
11143                // Regardless of writeSettings we need to ensure that this restriction
11144                // state propagation is persisted
11145                mSettings.writeAllUsersPackageRestrictionsLPr();
11146            }
11147            // can downgrade to reader here
11148            if (writeSettings) {
11149                mSettings.writeLPr();
11150            }
11151        }
11152        return true;
11153    }
11154
11155    private boolean deleteInstalledPackageLI(PackageSetting ps,
11156            boolean deleteCodeAndResources, int flags,
11157            int[] allUserHandles, boolean[] perUserInstalled,
11158            PackageRemovedInfo outInfo, boolean writeSettings) {
11159        if (outInfo != null) {
11160            outInfo.uid = ps.appId;
11161        }
11162
11163        // Delete package data from internal structures and also remove data if flag is set
11164        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11165
11166        // Delete application code and resources
11167        if (deleteCodeAndResources && (outInfo != null)) {
11168            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11169                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11170                    getAppDexInstructionSets(ps));
11171            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11172        }
11173        return true;
11174    }
11175
11176    @Override
11177    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11178            int userId) {
11179        mContext.enforceCallingOrSelfPermission(
11180                android.Manifest.permission.DELETE_PACKAGES, null);
11181        synchronized (mPackages) {
11182            PackageSetting ps = mSettings.mPackages.get(packageName);
11183            if (ps == null) {
11184                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11185                return false;
11186            }
11187            if (!ps.getInstalled(userId)) {
11188                // Can't block uninstall for an app that is not installed or enabled.
11189                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11190                return false;
11191            }
11192            ps.setBlockUninstall(blockUninstall, userId);
11193            mSettings.writePackageRestrictionsLPr(userId);
11194        }
11195        return true;
11196    }
11197
11198    @Override
11199    public boolean getBlockUninstallForUser(String packageName, int userId) {
11200        synchronized (mPackages) {
11201            PackageSetting ps = mSettings.mPackages.get(packageName);
11202            if (ps == null) {
11203                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11204                return false;
11205            }
11206            return ps.getBlockUninstall(userId);
11207        }
11208    }
11209
11210    /*
11211     * This method handles package deletion in general
11212     */
11213    private boolean deletePackageLI(String packageName, UserHandle user,
11214            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11215            int flags, PackageRemovedInfo outInfo,
11216            boolean writeSettings) {
11217        if (packageName == null) {
11218            Slog.w(TAG, "Attempt to delete null packageName.");
11219            return false;
11220        }
11221        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11222        PackageSetting ps;
11223        boolean dataOnly = false;
11224        int removeUser = -1;
11225        int appId = -1;
11226        synchronized (mPackages) {
11227            ps = mSettings.mPackages.get(packageName);
11228            if (ps == null) {
11229                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11230                return false;
11231            }
11232            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11233                    && user.getIdentifier() != UserHandle.USER_ALL) {
11234                // The caller is asking that the package only be deleted for a single
11235                // user.  To do this, we just mark its uninstalled state and delete
11236                // its data.  If this is a system app, we only allow this to happen if
11237                // they have set the special DELETE_SYSTEM_APP which requests different
11238                // semantics than normal for uninstalling system apps.
11239                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11240                ps.setUserState(user.getIdentifier(),
11241                        COMPONENT_ENABLED_STATE_DEFAULT,
11242                        false, //installed
11243                        true,  //stopped
11244                        true,  //notLaunched
11245                        false, //hidden
11246                        null, null, null,
11247                        false // blockUninstall
11248                        );
11249                if (!isSystemApp(ps)) {
11250                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11251                        // Other user still have this package installed, so all
11252                        // we need to do is clear this user's data and save that
11253                        // it is uninstalled.
11254                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11255                        removeUser = user.getIdentifier();
11256                        appId = ps.appId;
11257                        mSettings.writePackageRestrictionsLPr(removeUser);
11258                    } else {
11259                        // We need to set it back to 'installed' so the uninstall
11260                        // broadcasts will be sent correctly.
11261                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11262                        ps.setInstalled(true, user.getIdentifier());
11263                    }
11264                } else {
11265                    // This is a system app, so we assume that the
11266                    // other users still have this package installed, so all
11267                    // we need to do is clear this user's data and save that
11268                    // it is uninstalled.
11269                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11270                    removeUser = user.getIdentifier();
11271                    appId = ps.appId;
11272                    mSettings.writePackageRestrictionsLPr(removeUser);
11273                }
11274            }
11275        }
11276
11277        if (removeUser >= 0) {
11278            // From above, we determined that we are deleting this only
11279            // for a single user.  Continue the work here.
11280            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11281            if (outInfo != null) {
11282                outInfo.removedPackage = packageName;
11283                outInfo.removedAppId = appId;
11284                outInfo.removedUsers = new int[] {removeUser};
11285            }
11286            mInstaller.clearUserData(packageName, removeUser);
11287            removeKeystoreDataIfNeeded(removeUser, appId);
11288            schedulePackageCleaning(packageName, removeUser, false);
11289            return true;
11290        }
11291
11292        if (dataOnly) {
11293            // Delete application data first
11294            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11295            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11296            return true;
11297        }
11298
11299        boolean ret = false;
11300        if (isSystemApp(ps)) {
11301            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11302            // When an updated system application is deleted we delete the existing resources as well and
11303            // fall back to existing code in system partition
11304            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11305                    flags, outInfo, writeSettings);
11306        } else {
11307            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11308            // Kill application pre-emptively especially for apps on sd.
11309            killApplication(packageName, ps.appId, "uninstall pkg");
11310            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11311                    allUserHandles, perUserInstalled,
11312                    outInfo, writeSettings);
11313        }
11314
11315        return ret;
11316    }
11317
11318    private final class ClearStorageConnection implements ServiceConnection {
11319        IMediaContainerService mContainerService;
11320
11321        @Override
11322        public void onServiceConnected(ComponentName name, IBinder service) {
11323            synchronized (this) {
11324                mContainerService = IMediaContainerService.Stub.asInterface(service);
11325                notifyAll();
11326            }
11327        }
11328
11329        @Override
11330        public void onServiceDisconnected(ComponentName name) {
11331        }
11332    }
11333
11334    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11335        final boolean mounted;
11336        if (Environment.isExternalStorageEmulated()) {
11337            mounted = true;
11338        } else {
11339            final String status = Environment.getExternalStorageState();
11340
11341            mounted = status.equals(Environment.MEDIA_MOUNTED)
11342                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11343        }
11344
11345        if (!mounted) {
11346            return;
11347        }
11348
11349        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11350        int[] users;
11351        if (userId == UserHandle.USER_ALL) {
11352            users = sUserManager.getUserIds();
11353        } else {
11354            users = new int[] { userId };
11355        }
11356        final ClearStorageConnection conn = new ClearStorageConnection();
11357        if (mContext.bindServiceAsUser(
11358                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11359            try {
11360                for (int curUser : users) {
11361                    long timeout = SystemClock.uptimeMillis() + 5000;
11362                    synchronized (conn) {
11363                        long now = SystemClock.uptimeMillis();
11364                        while (conn.mContainerService == null && now < timeout) {
11365                            try {
11366                                conn.wait(timeout - now);
11367                            } catch (InterruptedException e) {
11368                            }
11369                        }
11370                    }
11371                    if (conn.mContainerService == null) {
11372                        return;
11373                    }
11374
11375                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11376                    clearDirectory(conn.mContainerService,
11377                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11378                    if (allData) {
11379                        clearDirectory(conn.mContainerService,
11380                                userEnv.buildExternalStorageAppDataDirs(packageName));
11381                        clearDirectory(conn.mContainerService,
11382                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11383                    }
11384                }
11385            } finally {
11386                mContext.unbindService(conn);
11387            }
11388        }
11389    }
11390
11391    @Override
11392    public void clearApplicationUserData(final String packageName,
11393            final IPackageDataObserver observer, final int userId) {
11394        mContext.enforceCallingOrSelfPermission(
11395                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11396        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11397        // Queue up an async operation since the package deletion may take a little while.
11398        mHandler.post(new Runnable() {
11399            public void run() {
11400                mHandler.removeCallbacks(this);
11401                final boolean succeeded;
11402                synchronized (mInstallLock) {
11403                    succeeded = clearApplicationUserDataLI(packageName, userId);
11404                }
11405                clearExternalStorageDataSync(packageName, userId, true);
11406                if (succeeded) {
11407                    // invoke DeviceStorageMonitor's update method to clear any notifications
11408                    DeviceStorageMonitorInternal
11409                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11410                    if (dsm != null) {
11411                        dsm.checkMemory();
11412                    }
11413                }
11414                if(observer != null) {
11415                    try {
11416                        observer.onRemoveCompleted(packageName, succeeded);
11417                    } catch (RemoteException e) {
11418                        Log.i(TAG, "Observer no longer exists.");
11419                    }
11420                } //end if observer
11421            } //end run
11422        });
11423    }
11424
11425    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11426        if (packageName == null) {
11427            Slog.w(TAG, "Attempt to delete null packageName.");
11428            return false;
11429        }
11430
11431        // Try finding details about the requested package
11432        PackageParser.Package pkg;
11433        synchronized (mPackages) {
11434            pkg = mPackages.get(packageName);
11435            if (pkg == null) {
11436                final PackageSetting ps = mSettings.mPackages.get(packageName);
11437                if (ps != null) {
11438                    pkg = ps.pkg;
11439                }
11440            }
11441        }
11442
11443        if (pkg == null) {
11444            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11445        }
11446
11447        // Always delete data directories for package, even if we found no other
11448        // record of app. This helps users recover from UID mismatches without
11449        // resorting to a full data wipe.
11450        int retCode = mInstaller.clearUserData(packageName, userId);
11451        if (retCode < 0) {
11452            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11453            return false;
11454        }
11455
11456        if (pkg == null) {
11457            return false;
11458        }
11459
11460        if (pkg != null && pkg.applicationInfo != null) {
11461            final int appId = pkg.applicationInfo.uid;
11462            removeKeystoreDataIfNeeded(userId, appId);
11463        }
11464
11465        // Create a native library symlink only if we have native libraries
11466        // and if the native libraries are 32 bit libraries. We do not provide
11467        // this symlink for 64 bit libraries.
11468        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11469                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11470            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11471            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11472                Slog.w(TAG, "Failed linking native library dir");
11473                return false;
11474            }
11475        }
11476
11477        return true;
11478    }
11479
11480    /**
11481     * Remove entries from the keystore daemon. Will only remove it if the
11482     * {@code appId} is valid.
11483     */
11484    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11485        if (appId < 0) {
11486            return;
11487        }
11488
11489        final KeyStore keyStore = KeyStore.getInstance();
11490        if (keyStore != null) {
11491            if (userId == UserHandle.USER_ALL) {
11492                for (final int individual : sUserManager.getUserIds()) {
11493                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11494                }
11495            } else {
11496                keyStore.clearUid(UserHandle.getUid(userId, appId));
11497            }
11498        } else {
11499            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11500        }
11501    }
11502
11503    @Override
11504    public void deleteApplicationCacheFiles(final String packageName,
11505            final IPackageDataObserver observer) {
11506        mContext.enforceCallingOrSelfPermission(
11507                android.Manifest.permission.DELETE_CACHE_FILES, null);
11508        // Queue up an async operation since the package deletion may take a little while.
11509        final int userId = UserHandle.getCallingUserId();
11510        mHandler.post(new Runnable() {
11511            public void run() {
11512                mHandler.removeCallbacks(this);
11513                final boolean succeded;
11514                synchronized (mInstallLock) {
11515                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11516                }
11517                clearExternalStorageDataSync(packageName, userId, false);
11518                if(observer != null) {
11519                    try {
11520                        observer.onRemoveCompleted(packageName, succeded);
11521                    } catch (RemoteException e) {
11522                        Log.i(TAG, "Observer no longer exists.");
11523                    }
11524                } //end if observer
11525            } //end run
11526        });
11527    }
11528
11529    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11530        if (packageName == null) {
11531            Slog.w(TAG, "Attempt to delete null packageName.");
11532            return false;
11533        }
11534        PackageParser.Package p;
11535        synchronized (mPackages) {
11536            p = mPackages.get(packageName);
11537        }
11538        if (p == null) {
11539            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11540            return false;
11541        }
11542        final ApplicationInfo applicationInfo = p.applicationInfo;
11543        if (applicationInfo == null) {
11544            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11545            return false;
11546        }
11547        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11548        if (retCode < 0) {
11549            Slog.w(TAG, "Couldn't remove cache files for package: "
11550                       + packageName + " u" + userId);
11551            return false;
11552        }
11553        return true;
11554    }
11555
11556    @Override
11557    public void getPackageSizeInfo(final String packageName, int userHandle,
11558            final IPackageStatsObserver observer) {
11559        mContext.enforceCallingOrSelfPermission(
11560                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11561        if (packageName == null) {
11562            throw new IllegalArgumentException("Attempt to get size of null packageName");
11563        }
11564
11565        PackageStats stats = new PackageStats(packageName, userHandle);
11566
11567        /*
11568         * Queue up an async operation since the package measurement may take a
11569         * little while.
11570         */
11571        Message msg = mHandler.obtainMessage(INIT_COPY);
11572        msg.obj = new MeasureParams(stats, observer);
11573        mHandler.sendMessage(msg);
11574    }
11575
11576    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11577            PackageStats pStats) {
11578        if (packageName == null) {
11579            Slog.w(TAG, "Attempt to get size of null packageName.");
11580            return false;
11581        }
11582        PackageParser.Package p;
11583        boolean dataOnly = false;
11584        String libDirRoot = null;
11585        String asecPath = null;
11586        PackageSetting ps = null;
11587        synchronized (mPackages) {
11588            p = mPackages.get(packageName);
11589            ps = mSettings.mPackages.get(packageName);
11590            if(p == null) {
11591                dataOnly = true;
11592                if((ps == null) || (ps.pkg == null)) {
11593                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11594                    return false;
11595                }
11596                p = ps.pkg;
11597            }
11598            if (ps != null) {
11599                libDirRoot = ps.legacyNativeLibraryPathString;
11600            }
11601            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11602                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11603                if (secureContainerId != null) {
11604                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11605                }
11606            }
11607        }
11608        String publicSrcDir = null;
11609        if(!dataOnly) {
11610            final ApplicationInfo applicationInfo = p.applicationInfo;
11611            if (applicationInfo == null) {
11612                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11613                return false;
11614            }
11615            if (isForwardLocked(p)) {
11616                publicSrcDir = applicationInfo.getBaseResourcePath();
11617            }
11618        }
11619        // TODO: extend to measure size of split APKs
11620        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11621        // not just the first level.
11622        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11623        // just the primary.
11624        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11625        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11626                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11627        if (res < 0) {
11628            return false;
11629        }
11630
11631        // Fix-up for forward-locked applications in ASEC containers.
11632        if (!isExternal(p)) {
11633            pStats.codeSize += pStats.externalCodeSize;
11634            pStats.externalCodeSize = 0L;
11635        }
11636
11637        return true;
11638    }
11639
11640
11641    @Override
11642    public void addPackageToPreferred(String packageName) {
11643        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11644    }
11645
11646    @Override
11647    public void removePackageFromPreferred(String packageName) {
11648        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11649    }
11650
11651    @Override
11652    public List<PackageInfo> getPreferredPackages(int flags) {
11653        return new ArrayList<PackageInfo>();
11654    }
11655
11656    private int getUidTargetSdkVersionLockedLPr(int uid) {
11657        Object obj = mSettings.getUserIdLPr(uid);
11658        if (obj instanceof SharedUserSetting) {
11659            final SharedUserSetting sus = (SharedUserSetting) obj;
11660            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11661            final Iterator<PackageSetting> it = sus.packages.iterator();
11662            while (it.hasNext()) {
11663                final PackageSetting ps = it.next();
11664                if (ps.pkg != null) {
11665                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11666                    if (v < vers) vers = v;
11667                }
11668            }
11669            return vers;
11670        } else if (obj instanceof PackageSetting) {
11671            final PackageSetting ps = (PackageSetting) obj;
11672            if (ps.pkg != null) {
11673                return ps.pkg.applicationInfo.targetSdkVersion;
11674            }
11675        }
11676        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11677    }
11678
11679    @Override
11680    public void addPreferredActivity(IntentFilter filter, int match,
11681            ComponentName[] set, ComponentName activity, int userId) {
11682        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11683                "Adding preferred");
11684    }
11685
11686    private void addPreferredActivityInternal(IntentFilter filter, int match,
11687            ComponentName[] set, ComponentName activity, boolean always, int userId,
11688            String opname) {
11689        // writer
11690        int callingUid = Binder.getCallingUid();
11691        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11692        if (filter.countActions() == 0) {
11693            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11694            return;
11695        }
11696        synchronized (mPackages) {
11697            if (mContext.checkCallingOrSelfPermission(
11698                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11699                    != PackageManager.PERMISSION_GRANTED) {
11700                if (getUidTargetSdkVersionLockedLPr(callingUid)
11701                        < Build.VERSION_CODES.FROYO) {
11702                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11703                            + callingUid);
11704                    return;
11705                }
11706                mContext.enforceCallingOrSelfPermission(
11707                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11708            }
11709
11710            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11711            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11712                    + userId + ":");
11713            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11714            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11715            scheduleWritePackageRestrictionsLocked(userId);
11716        }
11717    }
11718
11719    @Override
11720    public void replacePreferredActivity(IntentFilter filter, int match,
11721            ComponentName[] set, ComponentName activity, int userId) {
11722        if (filter.countActions() != 1) {
11723            throw new IllegalArgumentException(
11724                    "replacePreferredActivity expects filter to have only 1 action.");
11725        }
11726        if (filter.countDataAuthorities() != 0
11727                || filter.countDataPaths() != 0
11728                || filter.countDataSchemes() > 1
11729                || filter.countDataTypes() != 0) {
11730            throw new IllegalArgumentException(
11731                    "replacePreferredActivity expects filter to have no data authorities, " +
11732                    "paths, or types; and at most one scheme.");
11733        }
11734
11735        final int callingUid = Binder.getCallingUid();
11736        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11737        synchronized (mPackages) {
11738            if (mContext.checkCallingOrSelfPermission(
11739                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11740                    != PackageManager.PERMISSION_GRANTED) {
11741                if (getUidTargetSdkVersionLockedLPr(callingUid)
11742                        < Build.VERSION_CODES.FROYO) {
11743                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11744                            + Binder.getCallingUid());
11745                    return;
11746                }
11747                mContext.enforceCallingOrSelfPermission(
11748                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11749            }
11750
11751            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11752            if (pir != null) {
11753                // Get all of the existing entries that exactly match this filter.
11754                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11755                if (existing != null && existing.size() == 1) {
11756                    PreferredActivity cur = existing.get(0);
11757                    if (DEBUG_PREFERRED) {
11758                        Slog.i(TAG, "Checking replace of preferred:");
11759                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11760                        if (!cur.mPref.mAlways) {
11761                            Slog.i(TAG, "  -- CUR; not mAlways!");
11762                        } else {
11763                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11764                            Slog.i(TAG, "  -- CUR: mSet="
11765                                    + Arrays.toString(cur.mPref.mSetComponents));
11766                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11767                            Slog.i(TAG, "  -- NEW: mMatch="
11768                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11769                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11770                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11771                        }
11772                    }
11773                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11774                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11775                            && cur.mPref.sameSet(set)) {
11776                        // Setting the preferred activity to what it happens to be already
11777                        if (DEBUG_PREFERRED) {
11778                            Slog.i(TAG, "Replacing with same preferred activity "
11779                                    + cur.mPref.mShortComponent + " for user "
11780                                    + userId + ":");
11781                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11782                        }
11783                        return;
11784                    }
11785                }
11786
11787                if (existing != null) {
11788                    if (DEBUG_PREFERRED) {
11789                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11790                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11791                    }
11792                    for (int i = 0; i < existing.size(); i++) {
11793                        PreferredActivity pa = existing.get(i);
11794                        if (DEBUG_PREFERRED) {
11795                            Slog.i(TAG, "Removing existing preferred activity "
11796                                    + pa.mPref.mComponent + ":");
11797                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11798                        }
11799                        pir.removeFilter(pa);
11800                    }
11801                }
11802            }
11803            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11804                    "Replacing preferred");
11805        }
11806    }
11807
11808    @Override
11809    public void clearPackagePreferredActivities(String packageName) {
11810        final int uid = Binder.getCallingUid();
11811        // writer
11812        synchronized (mPackages) {
11813            PackageParser.Package pkg = mPackages.get(packageName);
11814            if (pkg == null || pkg.applicationInfo.uid != uid) {
11815                if (mContext.checkCallingOrSelfPermission(
11816                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11817                        != PackageManager.PERMISSION_GRANTED) {
11818                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11819                            < Build.VERSION_CODES.FROYO) {
11820                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11821                                + Binder.getCallingUid());
11822                        return;
11823                    }
11824                    mContext.enforceCallingOrSelfPermission(
11825                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11826                }
11827            }
11828
11829            int user = UserHandle.getCallingUserId();
11830            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11831                scheduleWritePackageRestrictionsLocked(user);
11832            }
11833        }
11834    }
11835
11836    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11837    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11838        ArrayList<PreferredActivity> removed = null;
11839        boolean changed = false;
11840        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11841            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11842            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11843            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11844                continue;
11845            }
11846            Iterator<PreferredActivity> it = pir.filterIterator();
11847            while (it.hasNext()) {
11848                PreferredActivity pa = it.next();
11849                // Mark entry for removal only if it matches the package name
11850                // and the entry is of type "always".
11851                if (packageName == null ||
11852                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11853                                && pa.mPref.mAlways)) {
11854                    if (removed == null) {
11855                        removed = new ArrayList<PreferredActivity>();
11856                    }
11857                    removed.add(pa);
11858                }
11859            }
11860            if (removed != null) {
11861                for (int j=0; j<removed.size(); j++) {
11862                    PreferredActivity pa = removed.get(j);
11863                    pir.removeFilter(pa);
11864                }
11865                changed = true;
11866            }
11867        }
11868        return changed;
11869    }
11870
11871    @Override
11872    public void resetPreferredActivities(int userId) {
11873        /* TODO: Actually use userId. Why is it being passed in? */
11874        mContext.enforceCallingOrSelfPermission(
11875                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11876        // writer
11877        synchronized (mPackages) {
11878            int user = UserHandle.getCallingUserId();
11879            clearPackagePreferredActivitiesLPw(null, user);
11880            mSettings.readDefaultPreferredAppsLPw(this, user);
11881            scheduleWritePackageRestrictionsLocked(user);
11882        }
11883    }
11884
11885    @Override
11886    public int getPreferredActivities(List<IntentFilter> outFilters,
11887            List<ComponentName> outActivities, String packageName) {
11888
11889        int num = 0;
11890        final int userId = UserHandle.getCallingUserId();
11891        // reader
11892        synchronized (mPackages) {
11893            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11894            if (pir != null) {
11895                final Iterator<PreferredActivity> it = pir.filterIterator();
11896                while (it.hasNext()) {
11897                    final PreferredActivity pa = it.next();
11898                    if (packageName == null
11899                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11900                                    && pa.mPref.mAlways)) {
11901                        if (outFilters != null) {
11902                            outFilters.add(new IntentFilter(pa));
11903                        }
11904                        if (outActivities != null) {
11905                            outActivities.add(pa.mPref.mComponent);
11906                        }
11907                    }
11908                }
11909            }
11910        }
11911
11912        return num;
11913    }
11914
11915    @Override
11916    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11917            int userId) {
11918        int callingUid = Binder.getCallingUid();
11919        if (callingUid != Process.SYSTEM_UID) {
11920            throw new SecurityException(
11921                    "addPersistentPreferredActivity can only be run by the system");
11922        }
11923        if (filter.countActions() == 0) {
11924            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11925            return;
11926        }
11927        synchronized (mPackages) {
11928            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11929                    " :");
11930            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11931            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11932                    new PersistentPreferredActivity(filter, activity));
11933            scheduleWritePackageRestrictionsLocked(userId);
11934        }
11935    }
11936
11937    @Override
11938    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11939        int callingUid = Binder.getCallingUid();
11940        if (callingUid != Process.SYSTEM_UID) {
11941            throw new SecurityException(
11942                    "clearPackagePersistentPreferredActivities can only be run by the system");
11943        }
11944        ArrayList<PersistentPreferredActivity> removed = null;
11945        boolean changed = false;
11946        synchronized (mPackages) {
11947            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11948                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11949                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11950                        .valueAt(i);
11951                if (userId != thisUserId) {
11952                    continue;
11953                }
11954                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11955                while (it.hasNext()) {
11956                    PersistentPreferredActivity ppa = it.next();
11957                    // Mark entry for removal only if it matches the package name.
11958                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11959                        if (removed == null) {
11960                            removed = new ArrayList<PersistentPreferredActivity>();
11961                        }
11962                        removed.add(ppa);
11963                    }
11964                }
11965                if (removed != null) {
11966                    for (int j=0; j<removed.size(); j++) {
11967                        PersistentPreferredActivity ppa = removed.get(j);
11968                        ppir.removeFilter(ppa);
11969                    }
11970                    changed = true;
11971                }
11972            }
11973
11974            if (changed) {
11975                scheduleWritePackageRestrictionsLocked(userId);
11976            }
11977        }
11978    }
11979
11980    @Override
11981    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11982            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11983        mContext.enforceCallingOrSelfPermission(
11984                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11985        int callingUid = Binder.getCallingUid();
11986        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11987        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11988        if (intentFilter.countActions() == 0) {
11989            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11990            return;
11991        }
11992        synchronized (mPackages) {
11993            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
11994                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11995            CrossProfileIntentResolver resolver =
11996                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11997            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
11998            // We have all those whose filter is equal. Now checking if the rest is equal as well.
11999            if (existing != null) {
12000                int size = existing.size();
12001                for (int i = 0; i < size; i++) {
12002                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12003                        return;
12004                    }
12005                }
12006            }
12007            resolver.addFilter(newFilter);
12008            scheduleWritePackageRestrictionsLocked(sourceUserId);
12009        }
12010    }
12011
12012    @Override
12013    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
12014            int ownerUserId) {
12015        mContext.enforceCallingOrSelfPermission(
12016                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12017        int callingUid = Binder.getCallingUid();
12018        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
12019        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12020        int callingUserId = UserHandle.getUserId(callingUid);
12021        synchronized (mPackages) {
12022            CrossProfileIntentResolver resolver =
12023                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12024            ArraySet<CrossProfileIntentFilter> set =
12025                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12026            for (CrossProfileIntentFilter filter : set) {
12027                if (filter.getOwnerPackage().equals(ownerPackage)
12028                        && filter.getOwnerUserId() == callingUserId) {
12029                    resolver.removeFilter(filter);
12030                }
12031            }
12032            scheduleWritePackageRestrictionsLocked(sourceUserId);
12033        }
12034    }
12035
12036    // Enforcing that callingUid is owning pkg on userId
12037    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
12038        // The system owns everything.
12039        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12040            return;
12041        }
12042        int callingUserId = UserHandle.getUserId(callingUid);
12043        if (callingUserId != userId) {
12044            throw new SecurityException("calling uid " + callingUid
12045                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
12046                    + callingUserId);
12047        }
12048        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12049        if (pi == null) {
12050            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12051                    + callingUserId);
12052        }
12053        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12054            throw new SecurityException("Calling uid " + callingUid
12055                    + " does not own package " + pkg);
12056        }
12057    }
12058
12059    @Override
12060    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12061        Intent intent = new Intent(Intent.ACTION_MAIN);
12062        intent.addCategory(Intent.CATEGORY_HOME);
12063
12064        final int callingUserId = UserHandle.getCallingUserId();
12065        List<ResolveInfo> list = queryIntentActivities(intent, null,
12066                PackageManager.GET_META_DATA, callingUserId);
12067        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12068                true, false, false, callingUserId);
12069
12070        allHomeCandidates.clear();
12071        if (list != null) {
12072            for (ResolveInfo ri : list) {
12073                allHomeCandidates.add(ri);
12074            }
12075        }
12076        return (preferred == null || preferred.activityInfo == null)
12077                ? null
12078                : new ComponentName(preferred.activityInfo.packageName,
12079                        preferred.activityInfo.name);
12080    }
12081
12082    @Override
12083    public void setApplicationEnabledSetting(String appPackageName,
12084            int newState, int flags, int userId, String callingPackage) {
12085        if (!sUserManager.exists(userId)) return;
12086        if (callingPackage == null) {
12087            callingPackage = Integer.toString(Binder.getCallingUid());
12088        }
12089        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12090    }
12091
12092    @Override
12093    public void setComponentEnabledSetting(ComponentName componentName,
12094            int newState, int flags, int userId) {
12095        if (!sUserManager.exists(userId)) return;
12096        setEnabledSetting(componentName.getPackageName(),
12097                componentName.getClassName(), newState, flags, userId, null);
12098    }
12099
12100    private void setEnabledSetting(final String packageName, String className, int newState,
12101            final int flags, int userId, String callingPackage) {
12102        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12103              || newState == COMPONENT_ENABLED_STATE_ENABLED
12104              || newState == COMPONENT_ENABLED_STATE_DISABLED
12105              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12106              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12107            throw new IllegalArgumentException("Invalid new component state: "
12108                    + newState);
12109        }
12110        PackageSetting pkgSetting;
12111        final int uid = Binder.getCallingUid();
12112        final int permission = mContext.checkCallingOrSelfPermission(
12113                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12114        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12115        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12116        boolean sendNow = false;
12117        boolean isApp = (className == null);
12118        String componentName = isApp ? packageName : className;
12119        int packageUid = -1;
12120        ArrayList<String> components;
12121
12122        // writer
12123        synchronized (mPackages) {
12124            pkgSetting = mSettings.mPackages.get(packageName);
12125            if (pkgSetting == null) {
12126                if (className == null) {
12127                    throw new IllegalArgumentException(
12128                            "Unknown package: " + packageName);
12129                }
12130                throw new IllegalArgumentException(
12131                        "Unknown component: " + packageName
12132                        + "/" + className);
12133            }
12134            // Allow root and verify that userId is not being specified by a different user
12135            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12136                throw new SecurityException(
12137                        "Permission Denial: attempt to change component state from pid="
12138                        + Binder.getCallingPid()
12139                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12140            }
12141            if (className == null) {
12142                // We're dealing with an application/package level state change
12143                if (pkgSetting.getEnabled(userId) == newState) {
12144                    // Nothing to do
12145                    return;
12146                }
12147                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12148                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12149                    // Don't care about who enables an app.
12150                    callingPackage = null;
12151                }
12152                pkgSetting.setEnabled(newState, userId, callingPackage);
12153                // pkgSetting.pkg.mSetEnabled = newState;
12154            } else {
12155                // We're dealing with a component level state change
12156                // First, verify that this is a valid class name.
12157                PackageParser.Package pkg = pkgSetting.pkg;
12158                if (pkg == null || !pkg.hasComponentClassName(className)) {
12159                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12160                        throw new IllegalArgumentException("Component class " + className
12161                                + " does not exist in " + packageName);
12162                    } else {
12163                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12164                                + className + " does not exist in " + packageName);
12165                    }
12166                }
12167                switch (newState) {
12168                case COMPONENT_ENABLED_STATE_ENABLED:
12169                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12170                        return;
12171                    }
12172                    break;
12173                case COMPONENT_ENABLED_STATE_DISABLED:
12174                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12175                        return;
12176                    }
12177                    break;
12178                case COMPONENT_ENABLED_STATE_DEFAULT:
12179                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12180                        return;
12181                    }
12182                    break;
12183                default:
12184                    Slog.e(TAG, "Invalid new component state: " + newState);
12185                    return;
12186                }
12187            }
12188            mSettings.writePackageRestrictionsLPr(userId);
12189            components = mPendingBroadcasts.get(userId, packageName);
12190            final boolean newPackage = components == null;
12191            if (newPackage) {
12192                components = new ArrayList<String>();
12193            }
12194            if (!components.contains(componentName)) {
12195                components.add(componentName);
12196            }
12197            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12198                sendNow = true;
12199                // Purge entry from pending broadcast list if another one exists already
12200                // since we are sending one right away.
12201                mPendingBroadcasts.remove(userId, packageName);
12202            } else {
12203                if (newPackage) {
12204                    mPendingBroadcasts.put(userId, packageName, components);
12205                }
12206                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12207                    // Schedule a message
12208                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12209                }
12210            }
12211        }
12212
12213        long callingId = Binder.clearCallingIdentity();
12214        try {
12215            if (sendNow) {
12216                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12217                sendPackageChangedBroadcast(packageName,
12218                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12219            }
12220        } finally {
12221            Binder.restoreCallingIdentity(callingId);
12222        }
12223    }
12224
12225    private void sendPackageChangedBroadcast(String packageName,
12226            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12227        if (DEBUG_INSTALL)
12228            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12229                    + componentNames);
12230        Bundle extras = new Bundle(4);
12231        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12232        String nameList[] = new String[componentNames.size()];
12233        componentNames.toArray(nameList);
12234        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12235        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12236        extras.putInt(Intent.EXTRA_UID, packageUid);
12237        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12238                new int[] {UserHandle.getUserId(packageUid)});
12239    }
12240
12241    @Override
12242    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12243        if (!sUserManager.exists(userId)) return;
12244        final int uid = Binder.getCallingUid();
12245        final int permission = mContext.checkCallingOrSelfPermission(
12246                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12247        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12248        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12249        // writer
12250        synchronized (mPackages) {
12251            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12252                    uid, userId)) {
12253                scheduleWritePackageRestrictionsLocked(userId);
12254            }
12255        }
12256    }
12257
12258    @Override
12259    public String getInstallerPackageName(String packageName) {
12260        // reader
12261        synchronized (mPackages) {
12262            return mSettings.getInstallerPackageNameLPr(packageName);
12263        }
12264    }
12265
12266    @Override
12267    public int getApplicationEnabledSetting(String packageName, int userId) {
12268        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12269        int uid = Binder.getCallingUid();
12270        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12271        // reader
12272        synchronized (mPackages) {
12273            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12274        }
12275    }
12276
12277    @Override
12278    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12279        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12280        int uid = Binder.getCallingUid();
12281        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12282        // reader
12283        synchronized (mPackages) {
12284            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12285        }
12286    }
12287
12288    @Override
12289    public void enterSafeMode() {
12290        enforceSystemOrRoot("Only the system can request entering safe mode");
12291
12292        if (!mSystemReady) {
12293            mSafeMode = true;
12294        }
12295    }
12296
12297    @Override
12298    public void systemReady() {
12299        mSystemReady = true;
12300
12301        // Read the compatibilty setting when the system is ready.
12302        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12303                mContext.getContentResolver(),
12304                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12305        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12306        if (DEBUG_SETTINGS) {
12307            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12308        }
12309
12310        synchronized (mPackages) {
12311            // Verify that all of the preferred activity components actually
12312            // exist.  It is possible for applications to be updated and at
12313            // that point remove a previously declared activity component that
12314            // had been set as a preferred activity.  We try to clean this up
12315            // the next time we encounter that preferred activity, but it is
12316            // possible for the user flow to never be able to return to that
12317            // situation so here we do a sanity check to make sure we haven't
12318            // left any junk around.
12319            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12320            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12321                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12322                removed.clear();
12323                for (PreferredActivity pa : pir.filterSet()) {
12324                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12325                        removed.add(pa);
12326                    }
12327                }
12328                if (removed.size() > 0) {
12329                    for (int r=0; r<removed.size(); r++) {
12330                        PreferredActivity pa = removed.get(r);
12331                        Slog.w(TAG, "Removing dangling preferred activity: "
12332                                + pa.mPref.mComponent);
12333                        pir.removeFilter(pa);
12334                    }
12335                    mSettings.writePackageRestrictionsLPr(
12336                            mSettings.mPreferredActivities.keyAt(i));
12337                }
12338            }
12339        }
12340        sUserManager.systemReady();
12341
12342        // Kick off any messages waiting for system ready
12343        if (mPostSystemReadyMessages != null) {
12344            for (Message msg : mPostSystemReadyMessages) {
12345                msg.sendToTarget();
12346            }
12347            mPostSystemReadyMessages = null;
12348        }
12349    }
12350
12351    @Override
12352    public boolean isSafeMode() {
12353        return mSafeMode;
12354    }
12355
12356    @Override
12357    public boolean hasSystemUidErrors() {
12358        return mHasSystemUidErrors;
12359    }
12360
12361    static String arrayToString(int[] array) {
12362        StringBuffer buf = new StringBuffer(128);
12363        buf.append('[');
12364        if (array != null) {
12365            for (int i=0; i<array.length; i++) {
12366                if (i > 0) buf.append(", ");
12367                buf.append(array[i]);
12368            }
12369        }
12370        buf.append(']');
12371        return buf.toString();
12372    }
12373
12374    static class DumpState {
12375        public static final int DUMP_LIBS = 1 << 0;
12376        public static final int DUMP_FEATURES = 1 << 1;
12377        public static final int DUMP_RESOLVERS = 1 << 2;
12378        public static final int DUMP_PERMISSIONS = 1 << 3;
12379        public static final int DUMP_PACKAGES = 1 << 4;
12380        public static final int DUMP_SHARED_USERS = 1 << 5;
12381        public static final int DUMP_MESSAGES = 1 << 6;
12382        public static final int DUMP_PROVIDERS = 1 << 7;
12383        public static final int DUMP_VERIFIERS = 1 << 8;
12384        public static final int DUMP_PREFERRED = 1 << 9;
12385        public static final int DUMP_PREFERRED_XML = 1 << 10;
12386        public static final int DUMP_KEYSETS = 1 << 11;
12387        public static final int DUMP_VERSION = 1 << 12;
12388        public static final int DUMP_INSTALLS = 1 << 13;
12389
12390        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12391
12392        private int mTypes;
12393
12394        private int mOptions;
12395
12396        private boolean mTitlePrinted;
12397
12398        private SharedUserSetting mSharedUser;
12399
12400        public boolean isDumping(int type) {
12401            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12402                return true;
12403            }
12404
12405            return (mTypes & type) != 0;
12406        }
12407
12408        public void setDump(int type) {
12409            mTypes |= type;
12410        }
12411
12412        public boolean isOptionEnabled(int option) {
12413            return (mOptions & option) != 0;
12414        }
12415
12416        public void setOptionEnabled(int option) {
12417            mOptions |= option;
12418        }
12419
12420        public boolean onTitlePrinted() {
12421            final boolean printed = mTitlePrinted;
12422            mTitlePrinted = true;
12423            return printed;
12424        }
12425
12426        public boolean getTitlePrinted() {
12427            return mTitlePrinted;
12428        }
12429
12430        public void setTitlePrinted(boolean enabled) {
12431            mTitlePrinted = enabled;
12432        }
12433
12434        public SharedUserSetting getSharedUser() {
12435            return mSharedUser;
12436        }
12437
12438        public void setSharedUser(SharedUserSetting user) {
12439            mSharedUser = user;
12440        }
12441    }
12442
12443    @Override
12444    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12445        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12446                != PackageManager.PERMISSION_GRANTED) {
12447            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12448                    + Binder.getCallingPid()
12449                    + ", uid=" + Binder.getCallingUid()
12450                    + " without permission "
12451                    + android.Manifest.permission.DUMP);
12452            return;
12453        }
12454
12455        DumpState dumpState = new DumpState();
12456        boolean fullPreferred = false;
12457        boolean checkin = false;
12458
12459        String packageName = null;
12460
12461        int opti = 0;
12462        while (opti < args.length) {
12463            String opt = args[opti];
12464            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12465                break;
12466            }
12467            opti++;
12468
12469            if ("-a".equals(opt)) {
12470                // Right now we only know how to print all.
12471            } else if ("-h".equals(opt)) {
12472                pw.println("Package manager dump options:");
12473                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12474                pw.println("    --checkin: dump for a checkin");
12475                pw.println("    -f: print details of intent filters");
12476                pw.println("    -h: print this help");
12477                pw.println("  cmd may be one of:");
12478                pw.println("    l[ibraries]: list known shared libraries");
12479                pw.println("    f[ibraries]: list device features");
12480                pw.println("    k[eysets]: print known keysets");
12481                pw.println("    r[esolvers]: dump intent resolvers");
12482                pw.println("    perm[issions]: dump permissions");
12483                pw.println("    pref[erred]: print preferred package settings");
12484                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12485                pw.println("    prov[iders]: dump content providers");
12486                pw.println("    p[ackages]: dump installed packages");
12487                pw.println("    s[hared-users]: dump shared user IDs");
12488                pw.println("    m[essages]: print collected runtime messages");
12489                pw.println("    v[erifiers]: print package verifier info");
12490                pw.println("    version: print database version info");
12491                pw.println("    write: write current settings now");
12492                pw.println("    <package.name>: info about given package");
12493                pw.println("    installs: details about install sessions");
12494                return;
12495            } else if ("--checkin".equals(opt)) {
12496                checkin = true;
12497            } else if ("-f".equals(opt)) {
12498                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12499            } else {
12500                pw.println("Unknown argument: " + opt + "; use -h for help");
12501            }
12502        }
12503
12504        // Is the caller requesting to dump a particular piece of data?
12505        if (opti < args.length) {
12506            String cmd = args[opti];
12507            opti++;
12508            // Is this a package name?
12509            if ("android".equals(cmd) || cmd.contains(".")) {
12510                packageName = cmd;
12511                // When dumping a single package, we always dump all of its
12512                // filter information since the amount of data will be reasonable.
12513                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12514            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12515                dumpState.setDump(DumpState.DUMP_LIBS);
12516            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12517                dumpState.setDump(DumpState.DUMP_FEATURES);
12518            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12519                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12520            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12521                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12522            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12523                dumpState.setDump(DumpState.DUMP_PREFERRED);
12524            } else if ("preferred-xml".equals(cmd)) {
12525                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12526                if (opti < args.length && "--full".equals(args[opti])) {
12527                    fullPreferred = true;
12528                    opti++;
12529                }
12530            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12531                dumpState.setDump(DumpState.DUMP_PACKAGES);
12532            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12533                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12534            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12535                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12536            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12537                dumpState.setDump(DumpState.DUMP_MESSAGES);
12538            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12539                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12540            } else if ("version".equals(cmd)) {
12541                dumpState.setDump(DumpState.DUMP_VERSION);
12542            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12543                dumpState.setDump(DumpState.DUMP_KEYSETS);
12544            } else if ("installs".equals(cmd)) {
12545                dumpState.setDump(DumpState.DUMP_INSTALLS);
12546            } else if ("write".equals(cmd)) {
12547                synchronized (mPackages) {
12548                    mSettings.writeLPr();
12549                    pw.println("Settings written.");
12550                    return;
12551                }
12552            }
12553        }
12554
12555        if (checkin) {
12556            pw.println("vers,1");
12557        }
12558
12559        // reader
12560        synchronized (mPackages) {
12561            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12562                if (!checkin) {
12563                    if (dumpState.onTitlePrinted())
12564                        pw.println();
12565                    pw.println("Database versions:");
12566                    pw.print("  SDK Version:");
12567                    pw.print(" internal=");
12568                    pw.print(mSettings.mInternalSdkPlatform);
12569                    pw.print(" external=");
12570                    pw.println(mSettings.mExternalSdkPlatform);
12571                    pw.print("  DB Version:");
12572                    pw.print(" internal=");
12573                    pw.print(mSettings.mInternalDatabaseVersion);
12574                    pw.print(" external=");
12575                    pw.println(mSettings.mExternalDatabaseVersion);
12576                }
12577            }
12578
12579            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12580                if (!checkin) {
12581                    if (dumpState.onTitlePrinted())
12582                        pw.println();
12583                    pw.println("Verifiers:");
12584                    pw.print("  Required: ");
12585                    pw.print(mRequiredVerifierPackage);
12586                    pw.print(" (uid=");
12587                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12588                    pw.println(")");
12589                } else if (mRequiredVerifierPackage != null) {
12590                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12591                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12592                }
12593            }
12594
12595            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12596                boolean printedHeader = false;
12597                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12598                while (it.hasNext()) {
12599                    String name = it.next();
12600                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12601                    if (!checkin) {
12602                        if (!printedHeader) {
12603                            if (dumpState.onTitlePrinted())
12604                                pw.println();
12605                            pw.println("Libraries:");
12606                            printedHeader = true;
12607                        }
12608                        pw.print("  ");
12609                    } else {
12610                        pw.print("lib,");
12611                    }
12612                    pw.print(name);
12613                    if (!checkin) {
12614                        pw.print(" -> ");
12615                    }
12616                    if (ent.path != null) {
12617                        if (!checkin) {
12618                            pw.print("(jar) ");
12619                            pw.print(ent.path);
12620                        } else {
12621                            pw.print(",jar,");
12622                            pw.print(ent.path);
12623                        }
12624                    } else {
12625                        if (!checkin) {
12626                            pw.print("(apk) ");
12627                            pw.print(ent.apk);
12628                        } else {
12629                            pw.print(",apk,");
12630                            pw.print(ent.apk);
12631                        }
12632                    }
12633                    pw.println();
12634                }
12635            }
12636
12637            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12638                if (dumpState.onTitlePrinted())
12639                    pw.println();
12640                if (!checkin) {
12641                    pw.println("Features:");
12642                }
12643                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12644                while (it.hasNext()) {
12645                    String name = it.next();
12646                    if (!checkin) {
12647                        pw.print("  ");
12648                    } else {
12649                        pw.print("feat,");
12650                    }
12651                    pw.println(name);
12652                }
12653            }
12654
12655            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12656                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12657                        : "Activity Resolver Table:", "  ", packageName,
12658                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12659                    dumpState.setTitlePrinted(true);
12660                }
12661                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12662                        : "Receiver Resolver Table:", "  ", packageName,
12663                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12664                    dumpState.setTitlePrinted(true);
12665                }
12666                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12667                        : "Service Resolver Table:", "  ", packageName,
12668                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12669                    dumpState.setTitlePrinted(true);
12670                }
12671                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12672                        : "Provider Resolver Table:", "  ", packageName,
12673                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12674                    dumpState.setTitlePrinted(true);
12675                }
12676            }
12677
12678            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12679                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12680                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12681                    int user = mSettings.mPreferredActivities.keyAt(i);
12682                    if (pir.dump(pw,
12683                            dumpState.getTitlePrinted()
12684                                ? "\nPreferred Activities User " + user + ":"
12685                                : "Preferred Activities User " + user + ":", "  ",
12686                            packageName, true, false)) {
12687                        dumpState.setTitlePrinted(true);
12688                    }
12689                }
12690            }
12691
12692            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12693                pw.flush();
12694                FileOutputStream fout = new FileOutputStream(fd);
12695                BufferedOutputStream str = new BufferedOutputStream(fout);
12696                XmlSerializer serializer = new FastXmlSerializer();
12697                try {
12698                    serializer.setOutput(str, "utf-8");
12699                    serializer.startDocument(null, true);
12700                    serializer.setFeature(
12701                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12702                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12703                    serializer.endDocument();
12704                    serializer.flush();
12705                } catch (IllegalArgumentException e) {
12706                    pw.println("Failed writing: " + e);
12707                } catch (IllegalStateException e) {
12708                    pw.println("Failed writing: " + e);
12709                } catch (IOException e) {
12710                    pw.println("Failed writing: " + e);
12711                }
12712            }
12713
12714            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12715                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12716                if (packageName == null) {
12717                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12718                        if (iperm == 0) {
12719                            if (dumpState.onTitlePrinted())
12720                                pw.println();
12721                            pw.println("AppOp Permissions:");
12722                        }
12723                        pw.print("  AppOp Permission ");
12724                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12725                        pw.println(":");
12726                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12727                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12728                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12729                        }
12730                    }
12731                }
12732            }
12733
12734            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12735                boolean printedSomething = false;
12736                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12737                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12738                        continue;
12739                    }
12740                    if (!printedSomething) {
12741                        if (dumpState.onTitlePrinted())
12742                            pw.println();
12743                        pw.println("Registered ContentProviders:");
12744                        printedSomething = true;
12745                    }
12746                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12747                    pw.print("    "); pw.println(p.toString());
12748                }
12749                printedSomething = false;
12750                for (Map.Entry<String, PackageParser.Provider> entry :
12751                        mProvidersByAuthority.entrySet()) {
12752                    PackageParser.Provider p = entry.getValue();
12753                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12754                        continue;
12755                    }
12756                    if (!printedSomething) {
12757                        if (dumpState.onTitlePrinted())
12758                            pw.println();
12759                        pw.println("ContentProvider Authorities:");
12760                        printedSomething = true;
12761                    }
12762                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12763                    pw.print("    "); pw.println(p.toString());
12764                    if (p.info != null && p.info.applicationInfo != null) {
12765                        final String appInfo = p.info.applicationInfo.toString();
12766                        pw.print("      applicationInfo="); pw.println(appInfo);
12767                    }
12768                }
12769            }
12770
12771            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12772                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12773            }
12774
12775            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12776                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12777            }
12778
12779            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12780                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12781            }
12782
12783            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12784                // XXX should handle packageName != null by dumping only install data that
12785                // the given package is involved with.
12786                if (dumpState.onTitlePrinted()) pw.println();
12787                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12788            }
12789
12790            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12791                if (dumpState.onTitlePrinted()) pw.println();
12792                mSettings.dumpReadMessagesLPr(pw, dumpState);
12793
12794                pw.println();
12795                pw.println("Package warning messages:");
12796                BufferedReader in = null;
12797                String line = null;
12798                try {
12799                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12800                    while ((line = in.readLine()) != null) {
12801                        if (line.contains("ignored: updated version")) continue;
12802                        pw.println(line);
12803                    }
12804                } catch (IOException ignored) {
12805                } finally {
12806                    IoUtils.closeQuietly(in);
12807                }
12808            }
12809
12810            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12811                BufferedReader in = null;
12812                String line = null;
12813                try {
12814                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12815                    while ((line = in.readLine()) != null) {
12816                        if (line.contains("ignored: updated version")) continue;
12817                        pw.print("msg,");
12818                        pw.println(line);
12819                    }
12820                } catch (IOException ignored) {
12821                } finally {
12822                    IoUtils.closeQuietly(in);
12823                }
12824            }
12825        }
12826    }
12827
12828    // ------- apps on sdcard specific code -------
12829    static final boolean DEBUG_SD_INSTALL = false;
12830
12831    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12832
12833    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12834
12835    private boolean mMediaMounted = false;
12836
12837    static String getEncryptKey() {
12838        try {
12839            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12840                    SD_ENCRYPTION_KEYSTORE_NAME);
12841            if (sdEncKey == null) {
12842                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12843                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12844                if (sdEncKey == null) {
12845                    Slog.e(TAG, "Failed to create encryption keys");
12846                    return null;
12847                }
12848            }
12849            return sdEncKey;
12850        } catch (NoSuchAlgorithmException nsae) {
12851            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12852            return null;
12853        } catch (IOException ioe) {
12854            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12855            return null;
12856        }
12857    }
12858
12859    /*
12860     * Update media status on PackageManager.
12861     */
12862    @Override
12863    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12864        int callingUid = Binder.getCallingUid();
12865        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12866            throw new SecurityException("Media status can only be updated by the system");
12867        }
12868        // reader; this apparently protects mMediaMounted, but should probably
12869        // be a different lock in that case.
12870        synchronized (mPackages) {
12871            Log.i(TAG, "Updating external media status from "
12872                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12873                    + (mediaStatus ? "mounted" : "unmounted"));
12874            if (DEBUG_SD_INSTALL)
12875                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12876                        + ", mMediaMounted=" + mMediaMounted);
12877            if (mediaStatus == mMediaMounted) {
12878                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12879                        : 0, -1);
12880                mHandler.sendMessage(msg);
12881                return;
12882            }
12883            mMediaMounted = mediaStatus;
12884        }
12885        // Queue up an async operation since the package installation may take a
12886        // little while.
12887        mHandler.post(new Runnable() {
12888            public void run() {
12889                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12890            }
12891        });
12892    }
12893
12894    /**
12895     * Called by MountService when the initial ASECs to scan are available.
12896     * Should block until all the ASEC containers are finished being scanned.
12897     */
12898    public void scanAvailableAsecs() {
12899        updateExternalMediaStatusInner(true, false, false);
12900        if (mShouldRestoreconData) {
12901            SELinuxMMAC.setRestoreconDone();
12902            mShouldRestoreconData = false;
12903        }
12904    }
12905
12906    /*
12907     * Collect information of applications on external media, map them against
12908     * existing containers and update information based on current mount status.
12909     * Please note that we always have to report status if reportStatus has been
12910     * set to true especially when unloading packages.
12911     */
12912    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12913            boolean externalStorage) {
12914        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12915        int[] uidArr = EmptyArray.INT;
12916
12917        final String[] list = PackageHelper.getSecureContainerList();
12918        if (ArrayUtils.isEmpty(list)) {
12919            Log.i(TAG, "No secure containers found");
12920        } else {
12921            // Process list of secure containers and categorize them
12922            // as active or stale based on their package internal state.
12923
12924            // reader
12925            synchronized (mPackages) {
12926                for (String cid : list) {
12927                    // Leave stages untouched for now; installer service owns them
12928                    if (PackageInstallerService.isStageName(cid)) continue;
12929
12930                    if (DEBUG_SD_INSTALL)
12931                        Log.i(TAG, "Processing container " + cid);
12932                    String pkgName = getAsecPackageName(cid);
12933                    if (pkgName == null) {
12934                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12935                        continue;
12936                    }
12937                    if (DEBUG_SD_INSTALL)
12938                        Log.i(TAG, "Looking for pkg : " + pkgName);
12939
12940                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12941                    if (ps == null) {
12942                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12943                        continue;
12944                    }
12945
12946                    /*
12947                     * Skip packages that are not external if we're unmounting
12948                     * external storage.
12949                     */
12950                    if (externalStorage && !isMounted && !isExternal(ps)) {
12951                        continue;
12952                    }
12953
12954                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12955                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12956                    // The package status is changed only if the code path
12957                    // matches between settings and the container id.
12958                    if (ps.codePathString != null
12959                            && ps.codePathString.startsWith(args.getCodePath())) {
12960                        if (DEBUG_SD_INSTALL) {
12961                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12962                                    + " at code path: " + ps.codePathString);
12963                        }
12964
12965                        // We do have a valid package installed on sdcard
12966                        processCids.put(args, ps.codePathString);
12967                        final int uid = ps.appId;
12968                        if (uid != -1) {
12969                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12970                        }
12971                    } else {
12972                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12973                                + ps.codePathString);
12974                    }
12975                }
12976            }
12977
12978            Arrays.sort(uidArr);
12979        }
12980
12981        // Process packages with valid entries.
12982        if (isMounted) {
12983            if (DEBUG_SD_INSTALL)
12984                Log.i(TAG, "Loading packages");
12985            loadMediaPackages(processCids, uidArr);
12986            startCleaningPackages();
12987            mInstallerService.onSecureContainersAvailable();
12988        } else {
12989            if (DEBUG_SD_INSTALL)
12990                Log.i(TAG, "Unloading packages");
12991            unloadMediaPackages(processCids, uidArr, reportStatus);
12992        }
12993    }
12994
12995    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12996            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12997        int size = pkgList.size();
12998        if (size > 0) {
12999            // Send broadcasts here
13000            Bundle extras = new Bundle();
13001            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
13002                    .toArray(new String[size]));
13003            if (uidArr != null) {
13004                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13005            }
13006            if (replacing) {
13007                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13008            }
13009            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13010                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13011            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13012        }
13013    }
13014
13015   /*
13016     * Look at potentially valid container ids from processCids If package
13017     * information doesn't match the one on record or package scanning fails,
13018     * the cid is added to list of removeCids. We currently don't delete stale
13019     * containers.
13020     */
13021    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13022        ArrayList<String> pkgList = new ArrayList<String>();
13023        Set<AsecInstallArgs> keys = processCids.keySet();
13024
13025        for (AsecInstallArgs args : keys) {
13026            String codePath = processCids.get(args);
13027            if (DEBUG_SD_INSTALL)
13028                Log.i(TAG, "Loading container : " + args.cid);
13029            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13030            try {
13031                // Make sure there are no container errors first.
13032                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13033                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13034                            + " when installing from sdcard");
13035                    continue;
13036                }
13037                // Check code path here.
13038                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13039                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13040                            + " does not match one in settings " + codePath);
13041                    continue;
13042                }
13043                // Parse package
13044                int parseFlags = mDefParseFlags;
13045                if (args.isExternal()) {
13046                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
13047                }
13048                if (args.isFwdLocked()) {
13049                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13050                }
13051
13052                synchronized (mInstallLock) {
13053                    PackageParser.Package pkg = null;
13054                    try {
13055                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13056                    } catch (PackageManagerException e) {
13057                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13058                    }
13059                    // Scan the package
13060                    if (pkg != null) {
13061                        /*
13062                         * TODO why is the lock being held? doPostInstall is
13063                         * called in other places without the lock. This needs
13064                         * to be straightened out.
13065                         */
13066                        // writer
13067                        synchronized (mPackages) {
13068                            retCode = PackageManager.INSTALL_SUCCEEDED;
13069                            pkgList.add(pkg.packageName);
13070                            // Post process args
13071                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13072                                    pkg.applicationInfo.uid);
13073                        }
13074                    } else {
13075                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13076                    }
13077                }
13078
13079            } finally {
13080                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13081                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13082                }
13083            }
13084        }
13085        // writer
13086        synchronized (mPackages) {
13087            // If the platform SDK has changed since the last time we booted,
13088            // we need to re-grant app permission to catch any new ones that
13089            // appear. This is really a hack, and means that apps can in some
13090            // cases get permissions that the user didn't initially explicitly
13091            // allow... it would be nice to have some better way to handle
13092            // this situation.
13093            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13094            if (regrantPermissions)
13095                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13096                        + mSdkVersion + "; regranting permissions for external storage");
13097            mSettings.mExternalSdkPlatform = mSdkVersion;
13098
13099            // Make sure group IDs have been assigned, and any permission
13100            // changes in other apps are accounted for
13101            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13102                    | (regrantPermissions
13103                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13104                            : 0));
13105
13106            mSettings.updateExternalDatabaseVersion();
13107
13108            // can downgrade to reader
13109            // Persist settings
13110            mSettings.writeLPr();
13111        }
13112        // Send a broadcast to let everyone know we are done processing
13113        if (pkgList.size() > 0) {
13114            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13115        }
13116    }
13117
13118   /*
13119     * Utility method to unload a list of specified containers
13120     */
13121    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13122        // Just unmount all valid containers.
13123        for (AsecInstallArgs arg : cidArgs) {
13124            synchronized (mInstallLock) {
13125                arg.doPostDeleteLI(false);
13126           }
13127       }
13128   }
13129
13130    /*
13131     * Unload packages mounted on external media. This involves deleting package
13132     * data from internal structures, sending broadcasts about diabled packages,
13133     * gc'ing to free up references, unmounting all secure containers
13134     * corresponding to packages on external media, and posting a
13135     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13136     * that we always have to post this message if status has been requested no
13137     * matter what.
13138     */
13139    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13140            final boolean reportStatus) {
13141        if (DEBUG_SD_INSTALL)
13142            Log.i(TAG, "unloading media packages");
13143        ArrayList<String> pkgList = new ArrayList<String>();
13144        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13145        final Set<AsecInstallArgs> keys = processCids.keySet();
13146        for (AsecInstallArgs args : keys) {
13147            String pkgName = args.getPackageName();
13148            if (DEBUG_SD_INSTALL)
13149                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13150            // Delete package internally
13151            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13152            synchronized (mInstallLock) {
13153                boolean res = deletePackageLI(pkgName, null, false, null, null,
13154                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13155                if (res) {
13156                    pkgList.add(pkgName);
13157                } else {
13158                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13159                    failedList.add(args);
13160                }
13161            }
13162        }
13163
13164        // reader
13165        synchronized (mPackages) {
13166            // We didn't update the settings after removing each package;
13167            // write them now for all packages.
13168            mSettings.writeLPr();
13169        }
13170
13171        // We have to absolutely send UPDATED_MEDIA_STATUS only
13172        // after confirming that all the receivers processed the ordered
13173        // broadcast when packages get disabled, force a gc to clean things up.
13174        // and unload all the containers.
13175        if (pkgList.size() > 0) {
13176            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13177                    new IIntentReceiver.Stub() {
13178                public void performReceive(Intent intent, int resultCode, String data,
13179                        Bundle extras, boolean ordered, boolean sticky,
13180                        int sendingUser) throws RemoteException {
13181                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13182                            reportStatus ? 1 : 0, 1, keys);
13183                    mHandler.sendMessage(msg);
13184                }
13185            });
13186        } else {
13187            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13188                    keys);
13189            mHandler.sendMessage(msg);
13190        }
13191    }
13192
13193    /** Binder call */
13194    @Override
13195    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13196            final int flags) {
13197        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13198        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13199        int returnCode = PackageManager.MOVE_SUCCEEDED;
13200        int currInstallFlags = 0;
13201        int newInstallFlags = 0;
13202
13203        File codeFile = null;
13204        String installerPackageName = null;
13205        String packageAbiOverride = null;
13206
13207        // reader
13208        synchronized (mPackages) {
13209            final PackageParser.Package pkg = mPackages.get(packageName);
13210            final PackageSetting ps = mSettings.mPackages.get(packageName);
13211            if (pkg == null || ps == null) {
13212                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13213            } else {
13214                // Disable moving fwd locked apps and system packages
13215                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13216                    Slog.w(TAG, "Cannot move system application");
13217                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13218                } else if (pkg.mOperationPending) {
13219                    Slog.w(TAG, "Attempt to move package which has pending operations");
13220                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13221                } else {
13222                    // Find install location first
13223                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13224                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13225                        Slog.w(TAG, "Ambigous flags specified for move location.");
13226                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13227                    } else {
13228                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13229                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13230                        currInstallFlags = isExternal(pkg)
13231                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13232
13233                        if (newInstallFlags == currInstallFlags) {
13234                            Slog.w(TAG, "No move required. Trying to move to same location");
13235                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13236                        } else {
13237                            if (isForwardLocked(pkg)) {
13238                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13239                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13240                            }
13241                        }
13242                    }
13243                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13244                        pkg.mOperationPending = true;
13245                    }
13246                }
13247
13248                codeFile = new File(pkg.codePath);
13249                installerPackageName = ps.installerPackageName;
13250                packageAbiOverride = ps.cpuAbiOverrideString;
13251            }
13252        }
13253
13254        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13255            try {
13256                observer.packageMoved(packageName, returnCode);
13257            } catch (RemoteException ignored) {
13258            }
13259            return;
13260        }
13261
13262        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13263            @Override
13264            public void onUserActionRequired(Intent intent) throws RemoteException {
13265                throw new IllegalStateException();
13266            }
13267
13268            @Override
13269            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13270                    Bundle extras) throws RemoteException {
13271                Slog.d(TAG, "Install result for move: "
13272                        + PackageManager.installStatusToString(returnCode, msg));
13273
13274                // We usually have a new package now after the install, but if
13275                // we failed we need to clear the pending flag on the original
13276                // package object.
13277                synchronized (mPackages) {
13278                    final PackageParser.Package pkg = mPackages.get(packageName);
13279                    if (pkg != null) {
13280                        pkg.mOperationPending = false;
13281                    }
13282                }
13283
13284                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13285                switch (status) {
13286                    case PackageInstaller.STATUS_SUCCESS:
13287                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13288                        break;
13289                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13290                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13291                        break;
13292                    default:
13293                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13294                        break;
13295                }
13296            }
13297        };
13298
13299        // Treat a move like reinstalling an existing app, which ensures that we
13300        // process everythign uniformly, like unpacking native libraries.
13301        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13302
13303        final Message msg = mHandler.obtainMessage(INIT_COPY);
13304        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13305        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13306                installerPackageName, null, user, packageAbiOverride);
13307        mHandler.sendMessage(msg);
13308    }
13309
13310    @Override
13311    public boolean setInstallLocation(int loc) {
13312        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13313                null);
13314        if (getInstallLocation() == loc) {
13315            return true;
13316        }
13317        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13318                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13319            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13320                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13321            return true;
13322        }
13323        return false;
13324   }
13325
13326    @Override
13327    public int getInstallLocation() {
13328        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13329                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13330                PackageHelper.APP_INSTALL_AUTO);
13331    }
13332
13333    /** Called by UserManagerService */
13334    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13335        mDirtyUsers.remove(userHandle);
13336        mSettings.removeUserLPw(userHandle);
13337        mPendingBroadcasts.remove(userHandle);
13338        if (mInstaller != null) {
13339            // Technically, we shouldn't be doing this with the package lock
13340            // held.  However, this is very rare, and there is already so much
13341            // other disk I/O going on, that we'll let it slide for now.
13342            mInstaller.removeUserDataDirs(userHandle);
13343        }
13344        mUserNeedsBadging.delete(userHandle);
13345        removeUnusedPackagesLILPw(userManager, userHandle);
13346    }
13347
13348    /**
13349     * We're removing userHandle and would like to remove any downloaded packages
13350     * that are no longer in use by any other user.
13351     * @param userHandle the user being removed
13352     */
13353    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13354        final boolean DEBUG_CLEAN_APKS = false;
13355        int [] users = userManager.getUserIdsLPr();
13356        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13357        while (psit.hasNext()) {
13358            PackageSetting ps = psit.next();
13359            if (ps.pkg == null) {
13360                continue;
13361            }
13362            final String packageName = ps.pkg.packageName;
13363            // Skip over if system app
13364            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13365                continue;
13366            }
13367            if (DEBUG_CLEAN_APKS) {
13368                Slog.i(TAG, "Checking package " + packageName);
13369            }
13370            boolean keep = false;
13371            for (int i = 0; i < users.length; i++) {
13372                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13373                    keep = true;
13374                    if (DEBUG_CLEAN_APKS) {
13375                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13376                                + users[i]);
13377                    }
13378                    break;
13379                }
13380            }
13381            if (!keep) {
13382                if (DEBUG_CLEAN_APKS) {
13383                    Slog.i(TAG, "  Removing package " + packageName);
13384                }
13385                mHandler.post(new Runnable() {
13386                    public void run() {
13387                        deletePackageX(packageName, userHandle, 0);
13388                    } //end run
13389                });
13390            }
13391        }
13392    }
13393
13394    /** Called by UserManagerService */
13395    void createNewUserLILPw(int userHandle, File path) {
13396        if (mInstaller != null) {
13397            mInstaller.createUserConfig(userHandle);
13398            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13399        }
13400    }
13401
13402    @Override
13403    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13404        mContext.enforceCallingOrSelfPermission(
13405                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13406                "Only package verification agents can read the verifier device identity");
13407
13408        synchronized (mPackages) {
13409            return mSettings.getVerifierDeviceIdentityLPw();
13410        }
13411    }
13412
13413    @Override
13414    public void setPermissionEnforced(String permission, boolean enforced) {
13415        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13416        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13417            synchronized (mPackages) {
13418                if (mSettings.mReadExternalStorageEnforced == null
13419                        || mSettings.mReadExternalStorageEnforced != enforced) {
13420                    mSettings.mReadExternalStorageEnforced = enforced;
13421                    mSettings.writeLPr();
13422                }
13423            }
13424            // kill any non-foreground processes so we restart them and
13425            // grant/revoke the GID.
13426            final IActivityManager am = ActivityManagerNative.getDefault();
13427            if (am != null) {
13428                final long token = Binder.clearCallingIdentity();
13429                try {
13430                    am.killProcessesBelowForeground("setPermissionEnforcement");
13431                } catch (RemoteException e) {
13432                } finally {
13433                    Binder.restoreCallingIdentity(token);
13434                }
13435            }
13436        } else {
13437            throw new IllegalArgumentException("No selective enforcement for " + permission);
13438        }
13439    }
13440
13441    @Override
13442    @Deprecated
13443    public boolean isPermissionEnforced(String permission) {
13444        return true;
13445    }
13446
13447    @Override
13448    public boolean isStorageLow() {
13449        final long token = Binder.clearCallingIdentity();
13450        try {
13451            final DeviceStorageMonitorInternal
13452                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13453            if (dsm != null) {
13454                return dsm.isMemoryLow();
13455            } else {
13456                return false;
13457            }
13458        } finally {
13459            Binder.restoreCallingIdentity(token);
13460        }
13461    }
13462
13463    @Override
13464    public IPackageInstaller getPackageInstaller() {
13465        return mInstallerService;
13466    }
13467
13468    private boolean userNeedsBadging(int userId) {
13469        int index = mUserNeedsBadging.indexOfKey(userId);
13470        if (index < 0) {
13471            final UserInfo userInfo;
13472            final long token = Binder.clearCallingIdentity();
13473            try {
13474                userInfo = sUserManager.getUserInfo(userId);
13475            } finally {
13476                Binder.restoreCallingIdentity(token);
13477            }
13478            final boolean b;
13479            if (userInfo != null && userInfo.isManagedProfile()) {
13480                b = true;
13481            } else {
13482                b = false;
13483            }
13484            mUserNeedsBadging.put(userId, b);
13485            return b;
13486        }
13487        return mUserNeedsBadging.valueAt(index);
13488    }
13489
13490    @Override
13491    public KeySet getKeySetByAlias(String packageName, String alias) {
13492        if (packageName == null || alias == null) {
13493            return null;
13494        }
13495        synchronized(mPackages) {
13496            final PackageParser.Package pkg = mPackages.get(packageName);
13497            if (pkg == null) {
13498                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13499                throw new IllegalArgumentException("Unknown package: " + packageName);
13500            }
13501            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13502            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13503        }
13504    }
13505
13506    @Override
13507    public KeySet getSigningKeySet(String packageName) {
13508        if (packageName == null) {
13509            return null;
13510        }
13511        synchronized(mPackages) {
13512            final PackageParser.Package pkg = mPackages.get(packageName);
13513            if (pkg == null) {
13514                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13515                throw new IllegalArgumentException("Unknown package: " + packageName);
13516            }
13517            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13518                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13519                throw new SecurityException("May not access signing KeySet of other apps.");
13520            }
13521            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13522            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13523        }
13524    }
13525
13526    @Override
13527    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13528        if (packageName == null || ks == null) {
13529            return false;
13530        }
13531        synchronized(mPackages) {
13532            final PackageParser.Package pkg = mPackages.get(packageName);
13533            if (pkg == null) {
13534                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13535                throw new IllegalArgumentException("Unknown package: " + packageName);
13536            }
13537            IBinder ksh = ks.getToken();
13538            if (ksh instanceof KeySetHandle) {
13539                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13540                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13541            }
13542            return false;
13543        }
13544    }
13545
13546    @Override
13547    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13548        if (packageName == null || ks == null) {
13549            return false;
13550        }
13551        synchronized(mPackages) {
13552            final PackageParser.Package pkg = mPackages.get(packageName);
13553            if (pkg == null) {
13554                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13555                throw new IllegalArgumentException("Unknown package: " + packageName);
13556            }
13557            IBinder ksh = ks.getToken();
13558            if (ksh instanceof KeySetHandle) {
13559                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13560                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13561            }
13562            return false;
13563        }
13564    }
13565
13566    public void getUsageStatsIfNoPackageUsageInfo() {
13567        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13568            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13569            if (usm == null) {
13570                throw new IllegalStateException("UsageStatsManager must be initialized");
13571            }
13572            long now = System.currentTimeMillis();
13573            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13574            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13575                String packageName = entry.getKey();
13576                PackageParser.Package pkg = mPackages.get(packageName);
13577                if (pkg == null) {
13578                    continue;
13579                }
13580                UsageStats usage = entry.getValue();
13581                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13582                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13583            }
13584        }
13585    }
13586
13587    /**
13588     * Check and throw if the given before/after packages would be considered a
13589     * downgrade.
13590     */
13591    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13592            throws PackageManagerException {
13593        if (after.versionCode < before.mVersionCode) {
13594            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13595                    "Update version code " + after.versionCode + " is older than current "
13596                    + before.mVersionCode);
13597        } else if (after.versionCode == before.mVersionCode) {
13598            if (after.baseRevisionCode < before.baseRevisionCode) {
13599                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13600                        "Update base revision code " + after.baseRevisionCode
13601                        + " is older than current " + before.baseRevisionCode);
13602            }
13603
13604            if (!ArrayUtils.isEmpty(after.splitNames)) {
13605                for (int i = 0; i < after.splitNames.length; i++) {
13606                    final String splitName = after.splitNames[i];
13607                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13608                    if (j != -1) {
13609                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13610                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13611                                    "Update split " + splitName + " revision code "
13612                                    + after.splitRevisionCodes[i] + " is older than current "
13613                                    + before.splitRevisionCodes[j]);
13614                        }
13615                    }
13616                }
13617            }
13618        }
13619    }
13620}
13621