PackageManagerService.java revision cf959f6e722ddd20033b7c98b3e04c7143f6438e
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.server.pm.InstructionSets.getAppDexInstructionSets;
58import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
59import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
60import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
61
62import android.util.ArrayMap;
63
64import com.android.internal.R;
65import com.android.internal.app.IMediaContainerService;
66import com.android.internal.app.ResolverActivity;
67import com.android.internal.content.NativeLibraryHelper;
68import com.android.internal.content.PackageHelper;
69import com.android.internal.os.IParcelFileDescriptorFactory;
70import com.android.internal.util.ArrayUtils;
71import com.android.internal.util.FastPrintWriter;
72import com.android.internal.util.FastXmlSerializer;
73import com.android.internal.util.IndentingPrintWriter;
74import com.android.server.EventLogTags;
75import com.android.server.IntentResolver;
76import com.android.server.LocalServices;
77import com.android.server.ServiceThread;
78import com.android.server.SystemConfig;
79import com.android.server.Watchdog;
80import com.android.server.pm.Settings.DatabaseVersion;
81import com.android.server.storage.DeviceStorageMonitorInternal;
82
83import org.xmlpull.v1.XmlSerializer;
84
85import android.app.ActivityManager;
86import android.app.ActivityManagerNative;
87import android.app.AppGlobals;
88import android.app.IActivityManager;
89import android.app.admin.IDevicePolicyManager;
90import android.app.backup.IBackupManager;
91import android.app.usage.UsageStats;
92import android.app.usage.UsageStatsManager;
93import android.content.BroadcastReceiver;
94import android.content.ComponentName;
95import android.content.Context;
96import android.content.IIntentReceiver;
97import android.content.Intent;
98import android.content.IntentFilter;
99import android.content.IntentSender;
100import android.content.IntentSender.SendIntentException;
101import android.content.ServiceConnection;
102import android.content.pm.ActivityInfo;
103import android.content.pm.ApplicationInfo;
104import android.content.pm.FeatureInfo;
105import android.content.pm.IPackageDataObserver;
106import android.content.pm.IPackageDeleteObserver;
107import android.content.pm.IPackageDeleteObserver2;
108import android.content.pm.IPackageInstallObserver2;
109import android.content.pm.IPackageInstaller;
110import android.content.pm.IPackageManager;
111import android.content.pm.IPackageMoveObserver;
112import android.content.pm.IPackageStatsObserver;
113import android.content.pm.InstrumentationInfo;
114import android.content.pm.KeySet;
115import android.content.pm.ManifestDigest;
116import android.content.pm.PackageCleanItem;
117import android.content.pm.PackageInfo;
118import android.content.pm.PackageInfoLite;
119import android.content.pm.PackageInstaller;
120import android.content.pm.PackageManager;
121import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
122import android.content.pm.PackageParser.ActivityIntentInfo;
123import android.content.pm.PackageParser.PackageLite;
124import android.content.pm.PackageParser.PackageParserException;
125import android.content.pm.PackageParser;
126import android.content.pm.PackageStats;
127import android.content.pm.PackageUserState;
128import android.content.pm.ParceledListSlice;
129import android.content.pm.PermissionGroupInfo;
130import android.content.pm.PermissionInfo;
131import android.content.pm.ProviderInfo;
132import android.content.pm.ResolveInfo;
133import android.content.pm.ServiceInfo;
134import android.content.pm.Signature;
135import android.content.pm.UserInfo;
136import android.content.pm.VerificationParams;
137import android.content.pm.VerifierDeviceIdentity;
138import android.content.pm.VerifierInfo;
139import android.content.res.Resources;
140import android.hardware.display.DisplayManager;
141import android.net.Uri;
142import android.os.Binder;
143import android.os.Build;
144import android.os.Bundle;
145import android.os.Environment;
146import android.os.Environment.UserEnvironment;
147import android.os.storage.IMountService;
148import android.os.storage.StorageManager;
149import android.os.Debug;
150import android.os.FileUtils;
151import android.os.Handler;
152import android.os.IBinder;
153import android.os.Looper;
154import android.os.Message;
155import android.os.Parcel;
156import android.os.ParcelFileDescriptor;
157import android.os.Process;
158import android.os.RemoteException;
159import android.os.SELinux;
160import android.os.ServiceManager;
161import android.os.SystemClock;
162import android.os.SystemProperties;
163import android.os.UserHandle;
164import android.os.UserManager;
165import android.security.KeyStore;
166import android.security.SystemKeyStore;
167import android.system.ErrnoException;
168import android.system.Os;
169import android.system.StructStat;
170import android.text.TextUtils;
171import android.text.format.DateUtils;
172import android.util.ArraySet;
173import android.util.AtomicFile;
174import android.util.DisplayMetrics;
175import android.util.EventLog;
176import android.util.ExceptionUtils;
177import android.util.Log;
178import android.util.LogPrinter;
179import android.util.PrintStreamPrinter;
180import android.util.Slog;
181import android.util.SparseArray;
182import android.util.SparseBooleanArray;
183import android.view.Display;
184
185import java.io.BufferedInputStream;
186import java.io.BufferedOutputStream;
187import java.io.BufferedReader;
188import java.io.File;
189import java.io.FileDescriptor;
190import java.io.FileNotFoundException;
191import java.io.FileOutputStream;
192import java.io.FileReader;
193import java.io.FilenameFilter;
194import java.io.IOException;
195import java.io.InputStream;
196import java.io.PrintWriter;
197import java.nio.charset.StandardCharsets;
198import java.security.NoSuchAlgorithmException;
199import java.security.PublicKey;
200import java.security.cert.CertificateEncodingException;
201import java.security.cert.CertificateException;
202import java.text.SimpleDateFormat;
203import java.util.ArrayList;
204import java.util.Arrays;
205import java.util.Collection;
206import java.util.Collections;
207import java.util.Comparator;
208import java.util.Date;
209import java.util.Iterator;
210import java.util.List;
211import java.util.Map;
212import java.util.Objects;
213import java.util.Set;
214import java.util.concurrent.atomic.AtomicBoolean;
215import java.util.concurrent.atomic.AtomicLong;
216
217import dalvik.system.DexFile;
218import dalvik.system.VMRuntime;
219
220import libcore.io.IoUtils;
221import libcore.util.EmptyArray;
222
223/**
224 * Keep track of all those .apks everywhere.
225 *
226 * This is very central to the platform's security; please run the unit
227 * tests whenever making modifications here:
228 *
229mmm frameworks/base/tests/AndroidTests
230adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
231adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
232 *
233 * {@hide}
234 */
235public class PackageManagerService extends IPackageManager.Stub {
236    static final String TAG = "PackageManager";
237    static final boolean DEBUG_SETTINGS = false;
238    static final boolean DEBUG_PREFERRED = false;
239    static final boolean DEBUG_UPGRADE = false;
240    private static final boolean DEBUG_INSTALL = false;
241    private static final boolean DEBUG_REMOVE = false;
242    private static final boolean DEBUG_BROADCASTS = false;
243    private static final boolean DEBUG_SHOW_INFO = false;
244    private static final boolean DEBUG_PACKAGE_INFO = false;
245    private static final boolean DEBUG_INTENT_MATCHING = false;
246    private static final boolean DEBUG_PACKAGE_SCANNING = false;
247    private static final boolean DEBUG_VERIFY = false;
248    private static final boolean DEBUG_DEXOPT = false;
249    private static final boolean DEBUG_ABI_SELECTION = false;
250
251    static final boolean RUNTIME_PERMISSIONS_ENABLED =
252            SystemProperties.getInt("ro.runtime.permissions.enabled", 0) == 1;
253
254    private static final int RADIO_UID = Process.PHONE_UID;
255    private static final int LOG_UID = Process.LOG_UID;
256    private static final int NFC_UID = Process.NFC_UID;
257    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
258    private static final int SHELL_UID = Process.SHELL_UID;
259
260    // Cap the size of permission trees that 3rd party apps can define
261    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
262
263    // Suffix used during package installation when copying/moving
264    // package apks to install directory.
265    private static final String INSTALL_PACKAGE_SUFFIX = "-";
266
267    static final int SCAN_NO_DEX = 1<<1;
268    static final int SCAN_FORCE_DEX = 1<<2;
269    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
270    static final int SCAN_NEW_INSTALL = 1<<4;
271    static final int SCAN_NO_PATHS = 1<<5;
272    static final int SCAN_UPDATE_TIME = 1<<6;
273    static final int SCAN_DEFER_DEX = 1<<7;
274    static final int SCAN_BOOTING = 1<<8;
275    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
276    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
277    static final int SCAN_REPLACING = 1<<11;
278
279    static final int REMOVE_CHATTY = 1<<16;
280
281    /**
282     * Timeout (in milliseconds) after which the watchdog should declare that
283     * our handler thread is wedged.  The usual default for such things is one
284     * minute but we sometimes do very lengthy I/O operations on this thread,
285     * such as installing multi-gigabyte applications, so ours needs to be longer.
286     */
287    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
288
289    /**
290     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
291     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
292     * settings entry if available, otherwise we use the hardcoded default.  If it's been
293     * more than this long since the last fstrim, we force one during the boot sequence.
294     *
295     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
296     * one gets run at the next available charging+idle time.  This final mandatory
297     * no-fstrim check kicks in only of the other scheduling criteria is never met.
298     */
299    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
300
301    /**
302     * Whether verification is enabled by default.
303     */
304    private static final boolean DEFAULT_VERIFY_ENABLE = true;
305
306    /**
307     * The default maximum time to wait for the verification agent to return in
308     * milliseconds.
309     */
310    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
311
312    /**
313     * The default response for package verification timeout.
314     *
315     * This can be either PackageManager.VERIFICATION_ALLOW or
316     * PackageManager.VERIFICATION_REJECT.
317     */
318    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
319
320    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
321
322    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
323            DEFAULT_CONTAINER_PACKAGE,
324            "com.android.defcontainer.DefaultContainerService");
325
326    private static final String KILL_APP_REASON_GIDS_CHANGED =
327            "permission grant or revoke changed gids";
328
329    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
330            "permissions revoked";
331
332    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
333
334    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
335
336    /** Permission grant: not grant the permission. */
337    private static final int GRANT_DENIED = 1;
338
339    /** Permission grant: grant the permission as an install permission. */
340    private static final int GRANT_INSTALL = 2;
341
342    /** Permission grant: grant the permission as a runtime one. */
343    private static final int GRANT_RUNTIME = 3;
344
345    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
346    private static final int GRANT_UPGRADE = 4;
347
348    final ServiceThread mHandlerThread;
349
350    final PackageHandler mHandler;
351
352    /**
353     * Messages for {@link #mHandler} that need to wait for system ready before
354     * being dispatched.
355     */
356    private ArrayList<Message> mPostSystemReadyMessages;
357
358    final int mSdkVersion = Build.VERSION.SDK_INT;
359
360    final Context mContext;
361    final boolean mFactoryTest;
362    final boolean mOnlyCore;
363    final boolean mLazyDexOpt;
364    final long mDexOptLRUThresholdInMills;
365    final DisplayMetrics mMetrics;
366    final int mDefParseFlags;
367    final String[] mSeparateProcesses;
368    final boolean mIsUpgrade;
369
370    // This is where all application persistent data goes.
371    final File mAppDataDir;
372
373    // This is where all application persistent data goes for secondary users.
374    final File mUserAppDataDir;
375
376    /** The location for ASEC container files on internal storage. */
377    final String mAsecInternalPath;
378
379    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
380    // LOCK HELD.  Can be called with mInstallLock held.
381    final Installer mInstaller;
382
383    /** Directory where installed third-party apps stored */
384    final File mAppInstallDir;
385
386    /**
387     * Directory to which applications installed internally have their
388     * 32 bit native libraries copied.
389     */
390    private File mAppLib32InstallDir;
391
392    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
393    // apps.
394    final File mDrmAppPrivateInstallDir;
395
396    // ----------------------------------------------------------------
397
398    // Lock for state used when installing and doing other long running
399    // operations.  Methods that must be called with this lock held have
400    // the suffix "LI".
401    final Object mInstallLock = new Object();
402
403    // ----------------------------------------------------------------
404
405    // Keys are String (package name), values are Package.  This also serves
406    // as the lock for the global state.  Methods that must be called with
407    // this lock held have the prefix "LP".
408    final ArrayMap<String, PackageParser.Package> mPackages =
409            new ArrayMap<String, PackageParser.Package>();
410
411    // Tracks available target package names -> overlay package paths.
412    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
413        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
414
415    final Settings mSettings;
416    boolean mRestoredSettings;
417
418    // System configuration read by SystemConfig.
419    final int[] mGlobalGids;
420    final SparseArray<ArraySet<String>> mSystemPermissions;
421    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
422
423    // If mac_permissions.xml was found for seinfo labeling.
424    boolean mFoundPolicyFile;
425
426    // If a recursive restorecon of /data/data/<pkg> is needed.
427    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
428
429    public static final class SharedLibraryEntry {
430        public final String path;
431        public final String apk;
432
433        SharedLibraryEntry(String _path, String _apk) {
434            path = _path;
435            apk = _apk;
436        }
437    }
438
439    // Currently known shared libraries.
440    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
441            new ArrayMap<String, SharedLibraryEntry>();
442
443    // All available activities, for your resolving pleasure.
444    final ActivityIntentResolver mActivities =
445            new ActivityIntentResolver();
446
447    // All available receivers, for your resolving pleasure.
448    final ActivityIntentResolver mReceivers =
449            new ActivityIntentResolver();
450
451    // All available services, for your resolving pleasure.
452    final ServiceIntentResolver mServices = new ServiceIntentResolver();
453
454    // All available providers, for your resolving pleasure.
455    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
456
457    // Mapping from provider base names (first directory in content URI codePath)
458    // to the provider information.
459    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
460            new ArrayMap<String, PackageParser.Provider>();
461
462    // Mapping from instrumentation class names to info about them.
463    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
464            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
465
466    // Mapping from permission names to info about them.
467    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
468            new ArrayMap<String, PackageParser.PermissionGroup>();
469
470    // Packages whose data we have transfered into another package, thus
471    // should no longer exist.
472    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
473
474    // Broadcast actions that are only available to the system.
475    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
476
477    /** List of packages waiting for verification. */
478    final SparseArray<PackageVerificationState> mPendingVerification
479            = new SparseArray<PackageVerificationState>();
480
481    /** Set of packages associated with each app op permission. */
482    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
483
484    final PackageInstallerService mInstallerService;
485
486    private final PackageDexOptimizer mPackageDexOptimizer;
487    // Cache of users who need badging.
488    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
489
490    /** Token for keys in mPendingVerification. */
491    private int mPendingVerificationToken = 0;
492
493    volatile boolean mSystemReady;
494    volatile boolean mSafeMode;
495    volatile boolean mHasSystemUidErrors;
496
497    ApplicationInfo mAndroidApplication;
498    final ActivityInfo mResolveActivity = new ActivityInfo();
499    final ResolveInfo mResolveInfo = new ResolveInfo();
500    ComponentName mResolveComponentName;
501    PackageParser.Package mPlatformPackage;
502    ComponentName mCustomResolverComponentName;
503
504    boolean mResolverReplaced = false;
505
506    // Set of pending broadcasts for aggregating enable/disable of components.
507    static class PendingPackageBroadcasts {
508        // for each user id, a map of <package name -> components within that package>
509        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
510
511        public PendingPackageBroadcasts() {
512            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
513        }
514
515        public ArrayList<String> get(int userId, String packageName) {
516            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
517            return packages.get(packageName);
518        }
519
520        public void put(int userId, String packageName, ArrayList<String> components) {
521            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
522            packages.put(packageName, components);
523        }
524
525        public void remove(int userId, String packageName) {
526            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
527            if (packages != null) {
528                packages.remove(packageName);
529            }
530        }
531
532        public void remove(int userId) {
533            mUidMap.remove(userId);
534        }
535
536        public int userIdCount() {
537            return mUidMap.size();
538        }
539
540        public int userIdAt(int n) {
541            return mUidMap.keyAt(n);
542        }
543
544        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
545            return mUidMap.get(userId);
546        }
547
548        public int size() {
549            // total number of pending broadcast entries across all userIds
550            int num = 0;
551            for (int i = 0; i< mUidMap.size(); i++) {
552                num += mUidMap.valueAt(i).size();
553            }
554            return num;
555        }
556
557        public void clear() {
558            mUidMap.clear();
559        }
560
561        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
562            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
563            if (map == null) {
564                map = new ArrayMap<String, ArrayList<String>>();
565                mUidMap.put(userId, map);
566            }
567            return map;
568        }
569    }
570    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
571
572    // Service Connection to remote media container service to copy
573    // package uri's from external media onto secure containers
574    // or internal storage.
575    private IMediaContainerService mContainerService = null;
576
577    static final int SEND_PENDING_BROADCAST = 1;
578    static final int MCS_BOUND = 3;
579    static final int END_COPY = 4;
580    static final int INIT_COPY = 5;
581    static final int MCS_UNBIND = 6;
582    static final int START_CLEANING_PACKAGE = 7;
583    static final int FIND_INSTALL_LOC = 8;
584    static final int POST_INSTALL = 9;
585    static final int MCS_RECONNECT = 10;
586    static final int MCS_GIVE_UP = 11;
587    static final int UPDATED_MEDIA_STATUS = 12;
588    static final int WRITE_SETTINGS = 13;
589    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
590    static final int PACKAGE_VERIFIED = 15;
591    static final int CHECK_PENDING_VERIFICATION = 16;
592
593    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
594
595    // Delay time in millisecs
596    static final int BROADCAST_DELAY = 10 * 1000;
597
598    static UserManagerService sUserManager;
599
600    // Stores a list of users whose package restrictions file needs to be updated
601    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
602
603    final private DefaultContainerConnection mDefContainerConn =
604            new DefaultContainerConnection();
605    class DefaultContainerConnection implements ServiceConnection {
606        public void onServiceConnected(ComponentName name, IBinder service) {
607            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
608            IMediaContainerService imcs =
609                IMediaContainerService.Stub.asInterface(service);
610            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
611        }
612
613        public void onServiceDisconnected(ComponentName name) {
614            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
615        }
616    };
617
618    // Recordkeeping of restore-after-install operations that are currently in flight
619    // between the Package Manager and the Backup Manager
620    class PostInstallData {
621        public InstallArgs args;
622        public PackageInstalledInfo res;
623
624        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
625            args = _a;
626            res = _r;
627        }
628    };
629    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
630    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
631
632    private final String mRequiredVerifierPackage;
633
634    private final PackageUsage mPackageUsage = new PackageUsage();
635
636    private class PackageUsage {
637        private static final int WRITE_INTERVAL
638            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
639
640        private final Object mFileLock = new Object();
641        private final AtomicLong mLastWritten = new AtomicLong(0);
642        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
643
644        private boolean mIsHistoricalPackageUsageAvailable = true;
645
646        boolean isHistoricalPackageUsageAvailable() {
647            return mIsHistoricalPackageUsageAvailable;
648        }
649
650        void write(boolean force) {
651            if (force) {
652                writeInternal();
653                return;
654            }
655            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
656                && !DEBUG_DEXOPT) {
657                return;
658            }
659            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
660                new Thread("PackageUsage_DiskWriter") {
661                    @Override
662                    public void run() {
663                        try {
664                            writeInternal();
665                        } finally {
666                            mBackgroundWriteRunning.set(false);
667                        }
668                    }
669                }.start();
670            }
671        }
672
673        private void writeInternal() {
674            synchronized (mPackages) {
675                synchronized (mFileLock) {
676                    AtomicFile file = getFile();
677                    FileOutputStream f = null;
678                    try {
679                        f = file.startWrite();
680                        BufferedOutputStream out = new BufferedOutputStream(f);
681                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
682                        StringBuilder sb = new StringBuilder();
683                        for (PackageParser.Package pkg : mPackages.values()) {
684                            if (pkg.mLastPackageUsageTimeInMills == 0) {
685                                continue;
686                            }
687                            sb.setLength(0);
688                            sb.append(pkg.packageName);
689                            sb.append(' ');
690                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
691                            sb.append('\n');
692                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
693                        }
694                        out.flush();
695                        file.finishWrite(f);
696                    } catch (IOException e) {
697                        if (f != null) {
698                            file.failWrite(f);
699                        }
700                        Log.e(TAG, "Failed to write package usage times", e);
701                    }
702                }
703            }
704            mLastWritten.set(SystemClock.elapsedRealtime());
705        }
706
707        void readLP() {
708            synchronized (mFileLock) {
709                AtomicFile file = getFile();
710                BufferedInputStream in = null;
711                try {
712                    in = new BufferedInputStream(file.openRead());
713                    StringBuffer sb = new StringBuffer();
714                    while (true) {
715                        String packageName = readToken(in, sb, ' ');
716                        if (packageName == null) {
717                            break;
718                        }
719                        String timeInMillisString = readToken(in, sb, '\n');
720                        if (timeInMillisString == null) {
721                            throw new IOException("Failed to find last usage time for package "
722                                                  + packageName);
723                        }
724                        PackageParser.Package pkg = mPackages.get(packageName);
725                        if (pkg == null) {
726                            continue;
727                        }
728                        long timeInMillis;
729                        try {
730                            timeInMillis = Long.parseLong(timeInMillisString.toString());
731                        } catch (NumberFormatException e) {
732                            throw new IOException("Failed to parse " + timeInMillisString
733                                                  + " as a long.", e);
734                        }
735                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
736                    }
737                } catch (FileNotFoundException expected) {
738                    mIsHistoricalPackageUsageAvailable = false;
739                } catch (IOException e) {
740                    Log.w(TAG, "Failed to read package usage times", e);
741                } finally {
742                    IoUtils.closeQuietly(in);
743                }
744            }
745            mLastWritten.set(SystemClock.elapsedRealtime());
746        }
747
748        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
749                throws IOException {
750            sb.setLength(0);
751            while (true) {
752                int ch = in.read();
753                if (ch == -1) {
754                    if (sb.length() == 0) {
755                        return null;
756                    }
757                    throw new IOException("Unexpected EOF");
758                }
759                if (ch == endOfToken) {
760                    return sb.toString();
761                }
762                sb.append((char)ch);
763            }
764        }
765
766        private AtomicFile getFile() {
767            File dataDir = Environment.getDataDirectory();
768            File systemDir = new File(dataDir, "system");
769            File fname = new File(systemDir, "package-usage.list");
770            return new AtomicFile(fname);
771        }
772    }
773
774    class PackageHandler extends Handler {
775        private boolean mBound = false;
776        final ArrayList<HandlerParams> mPendingInstalls =
777            new ArrayList<HandlerParams>();
778
779        private boolean connectToService() {
780            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
781                    " DefaultContainerService");
782            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
783            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
784            if (mContext.bindServiceAsUser(service, mDefContainerConn,
785                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
786                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
787                mBound = true;
788                return true;
789            }
790            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
791            return false;
792        }
793
794        private void disconnectService() {
795            mContainerService = null;
796            mBound = false;
797            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
798            mContext.unbindService(mDefContainerConn);
799            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
800        }
801
802        PackageHandler(Looper looper) {
803            super(looper);
804        }
805
806        public void handleMessage(Message msg) {
807            try {
808                doHandleMessage(msg);
809            } finally {
810                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
811            }
812        }
813
814        void doHandleMessage(Message msg) {
815            switch (msg.what) {
816                case INIT_COPY: {
817                    HandlerParams params = (HandlerParams) msg.obj;
818                    int idx = mPendingInstalls.size();
819                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
820                    // If a bind was already initiated we dont really
821                    // need to do anything. The pending install
822                    // will be processed later on.
823                    if (!mBound) {
824                        // If this is the only one pending we might
825                        // have to bind to the service again.
826                        if (!connectToService()) {
827                            Slog.e(TAG, "Failed to bind to media container service");
828                            params.serviceError();
829                            return;
830                        } else {
831                            // Once we bind to the service, the first
832                            // pending request will be processed.
833                            mPendingInstalls.add(idx, params);
834                        }
835                    } else {
836                        mPendingInstalls.add(idx, params);
837                        // Already bound to the service. Just make
838                        // sure we trigger off processing the first request.
839                        if (idx == 0) {
840                            mHandler.sendEmptyMessage(MCS_BOUND);
841                        }
842                    }
843                    break;
844                }
845                case MCS_BOUND: {
846                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
847                    if (msg.obj != null) {
848                        mContainerService = (IMediaContainerService) msg.obj;
849                    }
850                    if (mContainerService == null) {
851                        // Something seriously wrong. Bail out
852                        Slog.e(TAG, "Cannot bind to media container service");
853                        for (HandlerParams params : mPendingInstalls) {
854                            // Indicate service bind error
855                            params.serviceError();
856                        }
857                        mPendingInstalls.clear();
858                    } else if (mPendingInstalls.size() > 0) {
859                        HandlerParams params = mPendingInstalls.get(0);
860                        if (params != null) {
861                            if (params.startCopy()) {
862                                // We are done...  look for more work or to
863                                // go idle.
864                                if (DEBUG_SD_INSTALL) Log.i(TAG,
865                                        "Checking for more work or unbind...");
866                                // Delete pending install
867                                if (mPendingInstalls.size() > 0) {
868                                    mPendingInstalls.remove(0);
869                                }
870                                if (mPendingInstalls.size() == 0) {
871                                    if (mBound) {
872                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
873                                                "Posting delayed MCS_UNBIND");
874                                        removeMessages(MCS_UNBIND);
875                                        Message ubmsg = obtainMessage(MCS_UNBIND);
876                                        // Unbind after a little delay, to avoid
877                                        // continual thrashing.
878                                        sendMessageDelayed(ubmsg, 10000);
879                                    }
880                                } else {
881                                    // There are more pending requests in queue.
882                                    // Just post MCS_BOUND message to trigger processing
883                                    // of next pending install.
884                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
885                                            "Posting MCS_BOUND for next work");
886                                    mHandler.sendEmptyMessage(MCS_BOUND);
887                                }
888                            }
889                        }
890                    } else {
891                        // Should never happen ideally.
892                        Slog.w(TAG, "Empty queue");
893                    }
894                    break;
895                }
896                case MCS_RECONNECT: {
897                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
898                    if (mPendingInstalls.size() > 0) {
899                        if (mBound) {
900                            disconnectService();
901                        }
902                        if (!connectToService()) {
903                            Slog.e(TAG, "Failed to bind to media container service");
904                            for (HandlerParams params : mPendingInstalls) {
905                                // Indicate service bind error
906                                params.serviceError();
907                            }
908                            mPendingInstalls.clear();
909                        }
910                    }
911                    break;
912                }
913                case MCS_UNBIND: {
914                    // If there is no actual work left, then time to unbind.
915                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
916
917                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
918                        if (mBound) {
919                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
920
921                            disconnectService();
922                        }
923                    } else if (mPendingInstalls.size() > 0) {
924                        // There are more pending requests in queue.
925                        // Just post MCS_BOUND message to trigger processing
926                        // of next pending install.
927                        mHandler.sendEmptyMessage(MCS_BOUND);
928                    }
929
930                    break;
931                }
932                case MCS_GIVE_UP: {
933                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
934                    mPendingInstalls.remove(0);
935                    break;
936                }
937                case SEND_PENDING_BROADCAST: {
938                    String packages[];
939                    ArrayList<String> components[];
940                    int size = 0;
941                    int uids[];
942                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
943                    synchronized (mPackages) {
944                        if (mPendingBroadcasts == null) {
945                            return;
946                        }
947                        size = mPendingBroadcasts.size();
948                        if (size <= 0) {
949                            // Nothing to be done. Just return
950                            return;
951                        }
952                        packages = new String[size];
953                        components = new ArrayList[size];
954                        uids = new int[size];
955                        int i = 0;  // filling out the above arrays
956
957                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
958                            int packageUserId = mPendingBroadcasts.userIdAt(n);
959                            Iterator<Map.Entry<String, ArrayList<String>>> it
960                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
961                                            .entrySet().iterator();
962                            while (it.hasNext() && i < size) {
963                                Map.Entry<String, ArrayList<String>> ent = it.next();
964                                packages[i] = ent.getKey();
965                                components[i] = ent.getValue();
966                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
967                                uids[i] = (ps != null)
968                                        ? UserHandle.getUid(packageUserId, ps.appId)
969                                        : -1;
970                                i++;
971                            }
972                        }
973                        size = i;
974                        mPendingBroadcasts.clear();
975                    }
976                    // Send broadcasts
977                    for (int i = 0; i < size; i++) {
978                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
979                    }
980                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
981                    break;
982                }
983                case START_CLEANING_PACKAGE: {
984                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
985                    final String packageName = (String)msg.obj;
986                    final int userId = msg.arg1;
987                    final boolean andCode = msg.arg2 != 0;
988                    synchronized (mPackages) {
989                        if (userId == UserHandle.USER_ALL) {
990                            int[] users = sUserManager.getUserIds();
991                            for (int user : users) {
992                                mSettings.addPackageToCleanLPw(
993                                        new PackageCleanItem(user, packageName, andCode));
994                            }
995                        } else {
996                            mSettings.addPackageToCleanLPw(
997                                    new PackageCleanItem(userId, packageName, andCode));
998                        }
999                    }
1000                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1001                    startCleaningPackages();
1002                } break;
1003                case POST_INSTALL: {
1004                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1005                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1006                    mRunningInstalls.delete(msg.arg1);
1007                    boolean deleteOld = false;
1008
1009                    if (data != null) {
1010                        InstallArgs args = data.args;
1011                        PackageInstalledInfo res = data.res;
1012
1013                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1014                            res.removedInfo.sendBroadcast(false, true, false);
1015                            Bundle extras = new Bundle(1);
1016                            extras.putInt(Intent.EXTRA_UID, res.uid);
1017
1018                            // Now that we successfully installed the package, grant runtime
1019                            // permissions if requested before broadcasting the install.
1020                            if ((args.installFlags
1021                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1022                                grantRequestedRuntimePermissions(res.pkg,
1023                                        args.user.getIdentifier());
1024                            }
1025
1026                            // Determine the set of users who are adding this
1027                            // package for the first time vs. those who are seeing
1028                            // an update.
1029                            int[] firstUsers;
1030                            int[] updateUsers = new int[0];
1031                            if (res.origUsers == null || res.origUsers.length == 0) {
1032                                firstUsers = res.newUsers;
1033                            } else {
1034                                firstUsers = new int[0];
1035                                for (int i=0; i<res.newUsers.length; i++) {
1036                                    int user = res.newUsers[i];
1037                                    boolean isNew = true;
1038                                    for (int j=0; j<res.origUsers.length; j++) {
1039                                        if (res.origUsers[j] == user) {
1040                                            isNew = false;
1041                                            break;
1042                                        }
1043                                    }
1044                                    if (isNew) {
1045                                        int[] newFirst = new int[firstUsers.length+1];
1046                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1047                                                firstUsers.length);
1048                                        newFirst[firstUsers.length] = user;
1049                                        firstUsers = newFirst;
1050                                    } else {
1051                                        int[] newUpdate = new int[updateUsers.length+1];
1052                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1053                                                updateUsers.length);
1054                                        newUpdate[updateUsers.length] = user;
1055                                        updateUsers = newUpdate;
1056                                    }
1057                                }
1058                            }
1059                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1060                                    res.pkg.applicationInfo.packageName,
1061                                    extras, null, null, firstUsers);
1062                            final boolean update = res.removedInfo.removedPackage != null;
1063                            if (update) {
1064                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1065                            }
1066                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1067                                    res.pkg.applicationInfo.packageName,
1068                                    extras, null, null, updateUsers);
1069                            if (update) {
1070                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1071                                        res.pkg.applicationInfo.packageName,
1072                                        extras, null, null, updateUsers);
1073                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1074                                        null, null,
1075                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1076
1077                                // treat asec-hosted packages like removable media on upgrade
1078                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1079                                    if (DEBUG_INSTALL) {
1080                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1081                                                + " is ASEC-hosted -> AVAILABLE");
1082                                    }
1083                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1084                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1085                                    pkgList.add(res.pkg.applicationInfo.packageName);
1086                                    sendResourcesChangedBroadcast(true, true,
1087                                            pkgList,uidArray, null);
1088                                }
1089                            }
1090                            if (res.removedInfo.args != null) {
1091                                // Remove the replaced package's older resources safely now
1092                                deleteOld = true;
1093                            }
1094
1095                            // Log current value of "unknown sources" setting
1096                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1097                                getUnknownSourcesSettings());
1098                        }
1099                        // Force a gc to clear up things
1100                        Runtime.getRuntime().gc();
1101                        // We delete after a gc for applications  on sdcard.
1102                        if (deleteOld) {
1103                            synchronized (mInstallLock) {
1104                                res.removedInfo.args.doPostDeleteLI(true);
1105                            }
1106                        }
1107                        if (args.observer != null) {
1108                            try {
1109                                Bundle extras = extrasForInstallResult(res);
1110                                args.observer.onPackageInstalled(res.name, res.returnCode,
1111                                        res.returnMsg, extras);
1112                            } catch (RemoteException e) {
1113                                Slog.i(TAG, "Observer no longer exists.");
1114                            }
1115                        }
1116                    } else {
1117                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1118                    }
1119                } break;
1120                case UPDATED_MEDIA_STATUS: {
1121                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1122                    boolean reportStatus = msg.arg1 == 1;
1123                    boolean doGc = msg.arg2 == 1;
1124                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1125                    if (doGc) {
1126                        // Force a gc to clear up stale containers.
1127                        Runtime.getRuntime().gc();
1128                    }
1129                    if (msg.obj != null) {
1130                        @SuppressWarnings("unchecked")
1131                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1132                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1133                        // Unload containers
1134                        unloadAllContainers(args);
1135                    }
1136                    if (reportStatus) {
1137                        try {
1138                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1139                            PackageHelper.getMountService().finishMediaUpdate();
1140                        } catch (RemoteException e) {
1141                            Log.e(TAG, "MountService not running?");
1142                        }
1143                    }
1144                } break;
1145                case WRITE_SETTINGS: {
1146                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1147                    synchronized (mPackages) {
1148                        removeMessages(WRITE_SETTINGS);
1149                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1150                        mSettings.writeLPr();
1151                        mDirtyUsers.clear();
1152                    }
1153                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1154                } break;
1155                case WRITE_PACKAGE_RESTRICTIONS: {
1156                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1157                    synchronized (mPackages) {
1158                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1159                        for (int userId : mDirtyUsers) {
1160                            mSettings.writePackageRestrictionsLPr(userId);
1161                        }
1162                        mDirtyUsers.clear();
1163                    }
1164                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1165                } break;
1166                case CHECK_PENDING_VERIFICATION: {
1167                    final int verificationId = msg.arg1;
1168                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1169
1170                    if ((state != null) && !state.timeoutExtended()) {
1171                        final InstallArgs args = state.getInstallArgs();
1172                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1173
1174                        Slog.i(TAG, "Verification timed out for " + originUri);
1175                        mPendingVerification.remove(verificationId);
1176
1177                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1178
1179                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1180                            Slog.i(TAG, "Continuing with installation of " + originUri);
1181                            state.setVerifierResponse(Binder.getCallingUid(),
1182                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1183                            broadcastPackageVerified(verificationId, originUri,
1184                                    PackageManager.VERIFICATION_ALLOW,
1185                                    state.getInstallArgs().getUser());
1186                            try {
1187                                ret = args.copyApk(mContainerService, true);
1188                            } catch (RemoteException e) {
1189                                Slog.e(TAG, "Could not contact the ContainerService");
1190                            }
1191                        } else {
1192                            broadcastPackageVerified(verificationId, originUri,
1193                                    PackageManager.VERIFICATION_REJECT,
1194                                    state.getInstallArgs().getUser());
1195                        }
1196
1197                        processPendingInstall(args, ret);
1198                        mHandler.sendEmptyMessage(MCS_UNBIND);
1199                    }
1200                    break;
1201                }
1202                case PACKAGE_VERIFIED: {
1203                    final int verificationId = msg.arg1;
1204
1205                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1206                    if (state == null) {
1207                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1208                        break;
1209                    }
1210
1211                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1212
1213                    state.setVerifierResponse(response.callerUid, response.code);
1214
1215                    if (state.isVerificationComplete()) {
1216                        mPendingVerification.remove(verificationId);
1217
1218                        final InstallArgs args = state.getInstallArgs();
1219                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1220
1221                        int ret;
1222                        if (state.isInstallAllowed()) {
1223                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1224                            broadcastPackageVerified(verificationId, originUri,
1225                                    response.code, state.getInstallArgs().getUser());
1226                            try {
1227                                ret = args.copyApk(mContainerService, true);
1228                            } catch (RemoteException e) {
1229                                Slog.e(TAG, "Could not contact the ContainerService");
1230                            }
1231                        } else {
1232                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1233                        }
1234
1235                        processPendingInstall(args, ret);
1236
1237                        mHandler.sendEmptyMessage(MCS_UNBIND);
1238                    }
1239
1240                    break;
1241                }
1242            }
1243        }
1244    }
1245
1246    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1247        if (userId >= UserHandle.USER_OWNER) {
1248            grantRequestedRuntimePermissionsForUser(pkg, userId);
1249        } else if (userId == UserHandle.USER_ALL) {
1250            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1251                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1252            }
1253        }
1254    }
1255
1256    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1257        SettingBase sb = (SettingBase) pkg.mExtras;
1258        if (sb == null) {
1259            return;
1260        }
1261
1262        PermissionsState permissionsState = sb.getPermissionsState();
1263
1264        for (String permission : pkg.requestedPermissions) {
1265            BasePermission bp = mSettings.mPermissions.get(permission);
1266            if (bp != null && bp.isRuntime()) {
1267                permissionsState.grantRuntimePermission(bp, userId);
1268            }
1269        }
1270    }
1271
1272    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1273        Bundle extras = null;
1274        switch (res.returnCode) {
1275            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1276                extras = new Bundle();
1277                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1278                        res.origPermission);
1279                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1280                        res.origPackage);
1281                break;
1282            }
1283        }
1284        return extras;
1285    }
1286
1287    void scheduleWriteSettingsLocked() {
1288        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1289            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1290        }
1291    }
1292
1293    void scheduleWritePackageRestrictionsLocked(int userId) {
1294        if (!sUserManager.exists(userId)) return;
1295        mDirtyUsers.add(userId);
1296        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1297            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1298        }
1299    }
1300
1301    public static PackageManagerService main(Context context, Installer installer,
1302            boolean factoryTest, boolean onlyCore) {
1303        PackageManagerService m = new PackageManagerService(context, installer,
1304                factoryTest, onlyCore);
1305        ServiceManager.addService("package", m);
1306        return m;
1307    }
1308
1309    static String[] splitString(String str, char sep) {
1310        int count = 1;
1311        int i = 0;
1312        while ((i=str.indexOf(sep, i)) >= 0) {
1313            count++;
1314            i++;
1315        }
1316
1317        String[] res = new String[count];
1318        i=0;
1319        count = 0;
1320        int lastI=0;
1321        while ((i=str.indexOf(sep, i)) >= 0) {
1322            res[count] = str.substring(lastI, i);
1323            count++;
1324            i++;
1325            lastI = i;
1326        }
1327        res[count] = str.substring(lastI, str.length());
1328        return res;
1329    }
1330
1331    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1332        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1333                Context.DISPLAY_SERVICE);
1334        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1335    }
1336
1337    public PackageManagerService(Context context, Installer installer,
1338            boolean factoryTest, boolean onlyCore) {
1339        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1340                SystemClock.uptimeMillis());
1341
1342        if (mSdkVersion <= 0) {
1343            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1344        }
1345
1346        mContext = context;
1347        mFactoryTest = factoryTest;
1348        mOnlyCore = onlyCore;
1349        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1350        mMetrics = new DisplayMetrics();
1351        mSettings = new Settings(mContext, mPackages);
1352        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1353                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1354        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1355                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1356        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1357                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1358        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1359                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1360        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1361                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1362        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1363                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1364
1365        // TODO: add a property to control this?
1366        long dexOptLRUThresholdInMinutes;
1367        if (mLazyDexOpt) {
1368            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1369        } else {
1370            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1371        }
1372        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1373
1374        String separateProcesses = SystemProperties.get("debug.separate_processes");
1375        if (separateProcesses != null && separateProcesses.length() > 0) {
1376            if ("*".equals(separateProcesses)) {
1377                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1378                mSeparateProcesses = null;
1379                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1380            } else {
1381                mDefParseFlags = 0;
1382                mSeparateProcesses = separateProcesses.split(",");
1383                Slog.w(TAG, "Running with debug.separate_processes: "
1384                        + separateProcesses);
1385            }
1386        } else {
1387            mDefParseFlags = 0;
1388            mSeparateProcesses = null;
1389        }
1390
1391        mInstaller = installer;
1392        mPackageDexOptimizer = new PackageDexOptimizer(this);
1393
1394        getDefaultDisplayMetrics(context, mMetrics);
1395
1396        SystemConfig systemConfig = SystemConfig.getInstance();
1397        mGlobalGids = systemConfig.getGlobalGids();
1398        mSystemPermissions = systemConfig.getSystemPermissions();
1399        mAvailableFeatures = systemConfig.getAvailableFeatures();
1400
1401        synchronized (mInstallLock) {
1402        // writer
1403        synchronized (mPackages) {
1404            mHandlerThread = new ServiceThread(TAG,
1405                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1406            mHandlerThread.start();
1407            mHandler = new PackageHandler(mHandlerThread.getLooper());
1408            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1409
1410            File dataDir = Environment.getDataDirectory();
1411            mAppDataDir = new File(dataDir, "data");
1412            mAppInstallDir = new File(dataDir, "app");
1413            mAppLib32InstallDir = new File(dataDir, "app-lib");
1414            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1415            mUserAppDataDir = new File(dataDir, "user");
1416            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1417
1418            sUserManager = new UserManagerService(context, this,
1419                    mInstallLock, mPackages);
1420
1421            // Propagate permission configuration in to package manager.
1422            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1423                    = systemConfig.getPermissions();
1424            for (int i=0; i<permConfig.size(); i++) {
1425                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1426                BasePermission bp = mSettings.mPermissions.get(perm.name);
1427                if (bp == null) {
1428                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1429                    mSettings.mPermissions.put(perm.name, bp);
1430                }
1431                if (perm.gids != null) {
1432                    bp.setGids(perm.gids, perm.perUser);
1433                }
1434            }
1435
1436            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1437            for (int i=0; i<libConfig.size(); i++) {
1438                mSharedLibraries.put(libConfig.keyAt(i),
1439                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1440            }
1441
1442            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1443
1444            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1445                    mSdkVersion, mOnlyCore);
1446
1447            String customResolverActivity = Resources.getSystem().getString(
1448                    R.string.config_customResolverActivity);
1449            if (TextUtils.isEmpty(customResolverActivity)) {
1450                customResolverActivity = null;
1451            } else {
1452                mCustomResolverComponentName = ComponentName.unflattenFromString(
1453                        customResolverActivity);
1454            }
1455
1456            long startTime = SystemClock.uptimeMillis();
1457
1458            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1459                    startTime);
1460
1461            // Set flag to monitor and not change apk file paths when
1462            // scanning install directories.
1463            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1464
1465            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1466
1467            /**
1468             * Add everything in the in the boot class path to the
1469             * list of process files because dexopt will have been run
1470             * if necessary during zygote startup.
1471             */
1472            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1473            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1474
1475            if (bootClassPath != null) {
1476                String[] bootClassPathElements = splitString(bootClassPath, ':');
1477                for (String element : bootClassPathElements) {
1478                    alreadyDexOpted.add(element);
1479                }
1480            } else {
1481                Slog.w(TAG, "No BOOTCLASSPATH found!");
1482            }
1483
1484            if (systemServerClassPath != null) {
1485                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1486                for (String element : systemServerClassPathElements) {
1487                    alreadyDexOpted.add(element);
1488                }
1489            } else {
1490                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1491            }
1492
1493            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1494            final String[] dexCodeInstructionSets =
1495                    getDexCodeInstructionSets(
1496                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1497
1498            /**
1499             * Ensure all external libraries have had dexopt run on them.
1500             */
1501            if (mSharedLibraries.size() > 0) {
1502                // NOTE: For now, we're compiling these system "shared libraries"
1503                // (and framework jars) into all available architectures. It's possible
1504                // to compile them only when we come across an app that uses them (there's
1505                // already logic for that in scanPackageLI) but that adds some complexity.
1506                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1507                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1508                        final String lib = libEntry.path;
1509                        if (lib == null) {
1510                            continue;
1511                        }
1512
1513                        try {
1514                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1515                                                                                 dexCodeInstructionSet,
1516                                                                                 false);
1517                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1518                                alreadyDexOpted.add(lib);
1519
1520                                // The list of "shared libraries" we have at this point is
1521                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1522                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1523                                } else {
1524                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1525                                }
1526                            }
1527                        } catch (FileNotFoundException e) {
1528                            Slog.w(TAG, "Library not found: " + lib);
1529                        } catch (IOException e) {
1530                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1531                                    + e.getMessage());
1532                        }
1533                    }
1534                }
1535            }
1536
1537            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1538
1539            // Gross hack for now: we know this file doesn't contain any
1540            // code, so don't dexopt it to avoid the resulting log spew.
1541            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1542
1543            // Gross hack for now: we know this file is only part of
1544            // the boot class path for art, so don't dexopt it to
1545            // avoid the resulting log spew.
1546            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1547
1548            /**
1549             * And there are a number of commands implemented in Java, which
1550             * we currently need to do the dexopt on so that they can be
1551             * run from a non-root shell.
1552             */
1553            String[] frameworkFiles = frameworkDir.list();
1554            if (frameworkFiles != null) {
1555                // TODO: We could compile these only for the most preferred ABI. We should
1556                // first double check that the dex files for these commands are not referenced
1557                // by other system apps.
1558                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1559                    for (int i=0; i<frameworkFiles.length; i++) {
1560                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1561                        String path = libPath.getPath();
1562                        // Skip the file if we already did it.
1563                        if (alreadyDexOpted.contains(path)) {
1564                            continue;
1565                        }
1566                        // Skip the file if it is not a type we want to dexopt.
1567                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1568                            continue;
1569                        }
1570                        try {
1571                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1572                                                                                 dexCodeInstructionSet,
1573                                                                                 false);
1574                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1575                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1576                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1577                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1578                            }
1579                        } catch (FileNotFoundException e) {
1580                            Slog.w(TAG, "Jar not found: " + path);
1581                        } catch (IOException e) {
1582                            Slog.w(TAG, "Exception reading jar: " + path, e);
1583                        }
1584                    }
1585                }
1586            }
1587
1588            // Collect vendor overlay packages.
1589            // (Do this before scanning any apps.)
1590            // For security and version matching reason, only consider
1591            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1592            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1593            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1594                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1595
1596            // Find base frameworks (resource packages without code).
1597            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1598                    | PackageParser.PARSE_IS_SYSTEM_DIR
1599                    | PackageParser.PARSE_IS_PRIVILEGED,
1600                    scanFlags | SCAN_NO_DEX, 0);
1601
1602            // Collected privileged system packages.
1603            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1604            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1605                    | PackageParser.PARSE_IS_SYSTEM_DIR
1606                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1607
1608            // Collect ordinary system packages.
1609            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1610            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1611                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1612
1613            // Collect all vendor packages.
1614            File vendorAppDir = new File("/vendor/app");
1615            try {
1616                vendorAppDir = vendorAppDir.getCanonicalFile();
1617            } catch (IOException e) {
1618                // failed to look up canonical path, continue with original one
1619            }
1620            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1621                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1622
1623            // Collect all OEM packages.
1624            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1625            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1626                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1627
1628            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1629            mInstaller.moveFiles();
1630
1631            // Prune any system packages that no longer exist.
1632            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1633            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1634            if (!mOnlyCore) {
1635                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1636                while (psit.hasNext()) {
1637                    PackageSetting ps = psit.next();
1638
1639                    /*
1640                     * If this is not a system app, it can't be a
1641                     * disable system app.
1642                     */
1643                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1644                        continue;
1645                    }
1646
1647                    /*
1648                     * If the package is scanned, it's not erased.
1649                     */
1650                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1651                    if (scannedPkg != null) {
1652                        /*
1653                         * If the system app is both scanned and in the
1654                         * disabled packages list, then it must have been
1655                         * added via OTA. Remove it from the currently
1656                         * scanned package so the previously user-installed
1657                         * application can be scanned.
1658                         */
1659                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1660                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1661                                    + ps.name + "; removing system app.  Last known codePath="
1662                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1663                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1664                                    + scannedPkg.mVersionCode);
1665                            removePackageLI(ps, true);
1666                            expectingBetter.put(ps.name, ps.codePath);
1667                        }
1668
1669                        continue;
1670                    }
1671
1672                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1673                        psit.remove();
1674                        logCriticalInfo(Log.WARN, "System package " + ps.name
1675                                + " no longer exists; wiping its data");
1676                        removeDataDirsLI(ps.name);
1677                    } else {
1678                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1679                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1680                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1681                        }
1682                    }
1683                }
1684            }
1685
1686            //look for any incomplete package installations
1687            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1688            //clean up list
1689            for(int i = 0; i < deletePkgsList.size(); i++) {
1690                //clean up here
1691                cleanupInstallFailedPackage(deletePkgsList.get(i));
1692            }
1693            //delete tmp files
1694            deleteTempPackageFiles();
1695
1696            // Remove any shared userIDs that have no associated packages
1697            mSettings.pruneSharedUsersLPw();
1698
1699            if (!mOnlyCore) {
1700                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1701                        SystemClock.uptimeMillis());
1702                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1703
1704                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1705                        scanFlags, 0);
1706
1707                /**
1708                 * Remove disable package settings for any updated system
1709                 * apps that were removed via an OTA. If they're not a
1710                 * previously-updated app, remove them completely.
1711                 * Otherwise, just revoke their system-level permissions.
1712                 */
1713                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1714                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1715                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1716
1717                    String msg;
1718                    if (deletedPkg == null) {
1719                        msg = "Updated system package " + deletedAppName
1720                                + " no longer exists; wiping its data";
1721                        removeDataDirsLI(deletedAppName);
1722                    } else {
1723                        msg = "Updated system app + " + deletedAppName
1724                                + " no longer present; removing system privileges for "
1725                                + deletedAppName;
1726
1727                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1728
1729                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1730                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1731                    }
1732                    logCriticalInfo(Log.WARN, msg);
1733                }
1734
1735                /**
1736                 * Make sure all system apps that we expected to appear on
1737                 * the userdata partition actually showed up. If they never
1738                 * appeared, crawl back and revive the system version.
1739                 */
1740                for (int i = 0; i < expectingBetter.size(); i++) {
1741                    final String packageName = expectingBetter.keyAt(i);
1742                    if (!mPackages.containsKey(packageName)) {
1743                        final File scanFile = expectingBetter.valueAt(i);
1744
1745                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1746                                + " but never showed up; reverting to system");
1747
1748                        final int reparseFlags;
1749                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1750                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1751                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1752                                    | PackageParser.PARSE_IS_PRIVILEGED;
1753                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1754                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1755                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1756                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1757                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1758                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1759                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1760                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1761                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1762                        } else {
1763                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1764                            continue;
1765                        }
1766
1767                        mSettings.enableSystemPackageLPw(packageName);
1768
1769                        try {
1770                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1771                        } catch (PackageManagerException e) {
1772                            Slog.e(TAG, "Failed to parse original system package: "
1773                                    + e.getMessage());
1774                        }
1775                    }
1776                }
1777            }
1778
1779            // Now that we know all of the shared libraries, update all clients to have
1780            // the correct library paths.
1781            updateAllSharedLibrariesLPw();
1782
1783            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1784                // NOTE: We ignore potential failures here during a system scan (like
1785                // the rest of the commands above) because there's precious little we
1786                // can do about it. A settings error is reported, though.
1787                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1788                        false /* force dexopt */, false /* defer dexopt */);
1789            }
1790
1791            // Now that we know all the packages we are keeping,
1792            // read and update their last usage times.
1793            mPackageUsage.readLP();
1794
1795            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1796                    SystemClock.uptimeMillis());
1797            Slog.i(TAG, "Time to scan packages: "
1798                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1799                    + " seconds");
1800
1801            // If the platform SDK has changed since the last time we booted,
1802            // we need to re-grant app permission to catch any new ones that
1803            // appear.  This is really a hack, and means that apps can in some
1804            // cases get permissions that the user didn't initially explicitly
1805            // allow...  it would be nice to have some better way to handle
1806            // this situation.
1807            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1808                    != mSdkVersion;
1809            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1810                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1811                    + "; regranting permissions for internal storage");
1812            mSettings.mInternalSdkPlatform = mSdkVersion;
1813
1814
1815            // We keep track for which users we granted permissions to be able
1816            // to grant runtime permissions to system apps for newly appeared
1817            // users. If we supported runtime permissions during the previous
1818            // boot, then we already granted permissions for all device users.
1819            // In such a case we set the users for which we granted permissions
1820            // to avoid clobbering of runtime permissions we granted to system
1821            // apps but the user revoked later.
1822            if (PackageManagerService.RUNTIME_PERMISSIONS_ENABLED &&
1823                    mSettings.mRuntimePermissionEnabled) {
1824                final int[] userIds = UserManagerService.getInstance().getUserIds();
1825                for (PackageSetting ps : mSettings.mPackages.values()) {
1826                    ps.setPermissionsUpdatedForUserIds(userIds);
1827                }
1828                for (SharedUserSetting sus : mSettings.mSharedUsers.values()) {
1829                    sus.setPermissionsUpdatedForUserIds(userIds);
1830                }
1831            }
1832
1833            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1834                    | (regrantPermissions
1835                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1836                            : 0));
1837
1838            // If this is the first boot, and it is a normal boot, then
1839            // we need to initialize the default preferred apps.
1840            if (!mRestoredSettings && !onlyCore) {
1841                mSettings.readDefaultPreferredAppsLPw(this, 0);
1842            }
1843
1844            // If this is first boot after an OTA, and a normal boot, then
1845            // we need to clear code cache directories.
1846            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1847            if (mIsUpgrade && !onlyCore) {
1848                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1849                for (String pkgName : mSettings.mPackages.keySet()) {
1850                    deleteCodeCacheDirsLI(pkgName);
1851                }
1852                mSettings.mFingerprint = Build.FINGERPRINT;
1853            }
1854
1855            // All the changes are done during package scanning.
1856            mSettings.updateInternalDatabaseVersion();
1857
1858            // can downgrade to reader
1859            mSettings.writeLPr();
1860
1861            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1862                    SystemClock.uptimeMillis());
1863
1864            mRequiredVerifierPackage = getRequiredVerifierLPr();
1865        } // synchronized (mPackages)
1866        } // synchronized (mInstallLock)
1867
1868        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1869
1870        // Now after opening every single application zip, make sure they
1871        // are all flushed.  Not really needed, but keeps things nice and
1872        // tidy.
1873        Runtime.getRuntime().gc();
1874    }
1875
1876    @Override
1877    public boolean isFirstBoot() {
1878        return !mRestoredSettings;
1879    }
1880
1881    @Override
1882    public boolean isOnlyCoreApps() {
1883        return mOnlyCore;
1884    }
1885
1886    @Override
1887    public boolean isUpgrade() {
1888        return mIsUpgrade;
1889    }
1890
1891    private String getRequiredVerifierLPr() {
1892        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1893        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1894                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1895
1896        String requiredVerifier = null;
1897
1898        final int N = receivers.size();
1899        for (int i = 0; i < N; i++) {
1900            final ResolveInfo info = receivers.get(i);
1901
1902            if (info.activityInfo == null) {
1903                continue;
1904            }
1905
1906            final String packageName = info.activityInfo.packageName;
1907
1908            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
1909                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
1910                continue;
1911            }
1912
1913            if (requiredVerifier != null) {
1914                throw new RuntimeException("There can be only one required verifier");
1915            }
1916
1917            requiredVerifier = packageName;
1918        }
1919
1920        return requiredVerifier;
1921    }
1922
1923    @Override
1924    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1925            throws RemoteException {
1926        try {
1927            return super.onTransact(code, data, reply, flags);
1928        } catch (RuntimeException e) {
1929            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1930                Slog.wtf(TAG, "Package Manager Crash", e);
1931            }
1932            throw e;
1933        }
1934    }
1935
1936    void cleanupInstallFailedPackage(PackageSetting ps) {
1937        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1938
1939        removeDataDirsLI(ps.name);
1940        if (ps.codePath != null) {
1941            if (ps.codePath.isDirectory()) {
1942                FileUtils.deleteContents(ps.codePath);
1943            }
1944            ps.codePath.delete();
1945        }
1946        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1947            if (ps.resourcePath.isDirectory()) {
1948                FileUtils.deleteContents(ps.resourcePath);
1949            }
1950            ps.resourcePath.delete();
1951        }
1952        mSettings.removePackageLPw(ps.name);
1953    }
1954
1955    static int[] appendInts(int[] cur, int[] add) {
1956        if (add == null) return cur;
1957        if (cur == null) return add;
1958        final int N = add.length;
1959        for (int i=0; i<N; i++) {
1960            cur = appendInt(cur, add[i]);
1961        }
1962        return cur;
1963    }
1964
1965    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1966        if (!sUserManager.exists(userId)) return null;
1967        final PackageSetting ps = (PackageSetting) p.mExtras;
1968        if (ps == null) {
1969            return null;
1970        }
1971
1972        final PermissionsState permissionsState = ps.getPermissionsState();
1973
1974        final int[] gids = permissionsState.computeGids(userId);
1975        final Set<String> permissions = permissionsState.getPermissions(userId);
1976        final PackageUserState state = ps.readUserState(userId);
1977
1978        return PackageParser.generatePackageInfo(p, gids, flags,
1979                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
1980    }
1981
1982    @Override
1983    public boolean isPackageAvailable(String packageName, int userId) {
1984        if (!sUserManager.exists(userId)) return false;
1985        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1986        synchronized (mPackages) {
1987            PackageParser.Package p = mPackages.get(packageName);
1988            if (p != null) {
1989                final PackageSetting ps = (PackageSetting) p.mExtras;
1990                if (ps != null) {
1991                    final PackageUserState state = ps.readUserState(userId);
1992                    if (state != null) {
1993                        return PackageParser.isAvailable(state);
1994                    }
1995                }
1996            }
1997        }
1998        return false;
1999    }
2000
2001    @Override
2002    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2003        if (!sUserManager.exists(userId)) return null;
2004        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2005        // reader
2006        synchronized (mPackages) {
2007            PackageParser.Package p = mPackages.get(packageName);
2008            if (DEBUG_PACKAGE_INFO)
2009                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2010            if (p != null) {
2011                return generatePackageInfo(p, flags, userId);
2012            }
2013            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2014                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2015            }
2016        }
2017        return null;
2018    }
2019
2020    @Override
2021    public String[] currentToCanonicalPackageNames(String[] names) {
2022        String[] out = new String[names.length];
2023        // reader
2024        synchronized (mPackages) {
2025            for (int i=names.length-1; i>=0; i--) {
2026                PackageSetting ps = mSettings.mPackages.get(names[i]);
2027                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2028            }
2029        }
2030        return out;
2031    }
2032
2033    @Override
2034    public String[] canonicalToCurrentPackageNames(String[] names) {
2035        String[] out = new String[names.length];
2036        // reader
2037        synchronized (mPackages) {
2038            for (int i=names.length-1; i>=0; i--) {
2039                String cur = mSettings.mRenamedPackages.get(names[i]);
2040                out[i] = cur != null ? cur : names[i];
2041            }
2042        }
2043        return out;
2044    }
2045
2046    @Override
2047    public int getPackageUid(String packageName, int userId) {
2048        if (!sUserManager.exists(userId)) return -1;
2049        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2050
2051        // reader
2052        synchronized (mPackages) {
2053            PackageParser.Package p = mPackages.get(packageName);
2054            if(p != null) {
2055                return UserHandle.getUid(userId, p.applicationInfo.uid);
2056            }
2057            PackageSetting ps = mSettings.mPackages.get(packageName);
2058            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2059                return -1;
2060            }
2061            p = ps.pkg;
2062            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2063        }
2064    }
2065
2066    @Override
2067    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2068        if (!sUserManager.exists(userId)) {
2069            return null;
2070        }
2071
2072        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2073                "getPackageGids");
2074
2075        // reader
2076        synchronized (mPackages) {
2077            PackageParser.Package p = mPackages.get(packageName);
2078            if (DEBUG_PACKAGE_INFO) {
2079                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2080            }
2081            if (p != null) {
2082                PackageSetting ps = (PackageSetting) p.mExtras;
2083                return ps.getPermissionsState().computeGids(userId);
2084            }
2085        }
2086
2087        return null;
2088    }
2089
2090    static PermissionInfo generatePermissionInfo(
2091            BasePermission bp, int flags) {
2092        if (bp.perm != null) {
2093            return PackageParser.generatePermissionInfo(bp.perm, flags);
2094        }
2095        PermissionInfo pi = new PermissionInfo();
2096        pi.name = bp.name;
2097        pi.packageName = bp.sourcePackage;
2098        pi.nonLocalizedLabel = bp.name;
2099        pi.protectionLevel = bp.protectionLevel;
2100        return pi;
2101    }
2102
2103    @Override
2104    public PermissionInfo getPermissionInfo(String name, int flags) {
2105        // reader
2106        synchronized (mPackages) {
2107            final BasePermission p = mSettings.mPermissions.get(name);
2108            if (p != null) {
2109                return generatePermissionInfo(p, flags);
2110            }
2111            return null;
2112        }
2113    }
2114
2115    @Override
2116    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2117        // reader
2118        synchronized (mPackages) {
2119            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2120            for (BasePermission p : mSettings.mPermissions.values()) {
2121                if (group == null) {
2122                    if (p.perm == null || p.perm.info.group == null) {
2123                        out.add(generatePermissionInfo(p, flags));
2124                    }
2125                } else {
2126                    if (p.perm != null && group.equals(p.perm.info.group)) {
2127                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2128                    }
2129                }
2130            }
2131
2132            if (out.size() > 0) {
2133                return out;
2134            }
2135            return mPermissionGroups.containsKey(group) ? out : null;
2136        }
2137    }
2138
2139    @Override
2140    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2141        // reader
2142        synchronized (mPackages) {
2143            return PackageParser.generatePermissionGroupInfo(
2144                    mPermissionGroups.get(name), flags);
2145        }
2146    }
2147
2148    @Override
2149    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2150        // reader
2151        synchronized (mPackages) {
2152            final int N = mPermissionGroups.size();
2153            ArrayList<PermissionGroupInfo> out
2154                    = new ArrayList<PermissionGroupInfo>(N);
2155            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2156                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2157            }
2158            return out;
2159        }
2160    }
2161
2162    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2163            int userId) {
2164        if (!sUserManager.exists(userId)) return null;
2165        PackageSetting ps = mSettings.mPackages.get(packageName);
2166        if (ps != null) {
2167            if (ps.pkg == null) {
2168                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2169                        flags, userId);
2170                if (pInfo != null) {
2171                    return pInfo.applicationInfo;
2172                }
2173                return null;
2174            }
2175            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2176                    ps.readUserState(userId), userId);
2177        }
2178        return null;
2179    }
2180
2181    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2182            int userId) {
2183        if (!sUserManager.exists(userId)) return null;
2184        PackageSetting ps = mSettings.mPackages.get(packageName);
2185        if (ps != null) {
2186            PackageParser.Package pkg = ps.pkg;
2187            if (pkg == null) {
2188                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2189                    return null;
2190                }
2191                // Only data remains, so we aren't worried about code paths
2192                pkg = new PackageParser.Package(packageName);
2193                pkg.applicationInfo.packageName = packageName;
2194                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2195                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2196                pkg.applicationInfo.dataDir =
2197                        getDataPathForPackage(packageName, 0).getPath();
2198                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2199                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2200            }
2201            return generatePackageInfo(pkg, flags, userId);
2202        }
2203        return null;
2204    }
2205
2206    @Override
2207    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2208        if (!sUserManager.exists(userId)) return null;
2209        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2210        // writer
2211        synchronized (mPackages) {
2212            PackageParser.Package p = mPackages.get(packageName);
2213            if (DEBUG_PACKAGE_INFO) Log.v(
2214                    TAG, "getApplicationInfo " + packageName
2215                    + ": " + p);
2216            if (p != null) {
2217                PackageSetting ps = mSettings.mPackages.get(packageName);
2218                if (ps == null) return null;
2219                // Note: isEnabledLP() does not apply here - always return info
2220                return PackageParser.generateApplicationInfo(
2221                        p, flags, ps.readUserState(userId), userId);
2222            }
2223            if ("android".equals(packageName)||"system".equals(packageName)) {
2224                return mAndroidApplication;
2225            }
2226            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2227                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2228            }
2229        }
2230        return null;
2231    }
2232
2233
2234    @Override
2235    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2236        mContext.enforceCallingOrSelfPermission(
2237                android.Manifest.permission.CLEAR_APP_CACHE, null);
2238        // Queue up an async operation since clearing cache may take a little while.
2239        mHandler.post(new Runnable() {
2240            public void run() {
2241                mHandler.removeCallbacks(this);
2242                int retCode = -1;
2243                synchronized (mInstallLock) {
2244                    retCode = mInstaller.freeCache(freeStorageSize);
2245                    if (retCode < 0) {
2246                        Slog.w(TAG, "Couldn't clear application caches");
2247                    }
2248                }
2249                if (observer != null) {
2250                    try {
2251                        observer.onRemoveCompleted(null, (retCode >= 0));
2252                    } catch (RemoteException e) {
2253                        Slog.w(TAG, "RemoveException when invoking call back");
2254                    }
2255                }
2256            }
2257        });
2258    }
2259
2260    @Override
2261    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2262        mContext.enforceCallingOrSelfPermission(
2263                android.Manifest.permission.CLEAR_APP_CACHE, null);
2264        // Queue up an async operation since clearing cache may take a little while.
2265        mHandler.post(new Runnable() {
2266            public void run() {
2267                mHandler.removeCallbacks(this);
2268                int retCode = -1;
2269                synchronized (mInstallLock) {
2270                    retCode = mInstaller.freeCache(freeStorageSize);
2271                    if (retCode < 0) {
2272                        Slog.w(TAG, "Couldn't clear application caches");
2273                    }
2274                }
2275                if(pi != null) {
2276                    try {
2277                        // Callback via pending intent
2278                        int code = (retCode >= 0) ? 1 : 0;
2279                        pi.sendIntent(null, code, null,
2280                                null, null);
2281                    } catch (SendIntentException e1) {
2282                        Slog.i(TAG, "Failed to send pending intent");
2283                    }
2284                }
2285            }
2286        });
2287    }
2288
2289    void freeStorage(long freeStorageSize) throws IOException {
2290        synchronized (mInstallLock) {
2291            if (mInstaller.freeCache(freeStorageSize) < 0) {
2292                throw new IOException("Failed to free enough space");
2293            }
2294        }
2295    }
2296
2297    @Override
2298    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2299        if (!sUserManager.exists(userId)) return null;
2300        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2301        synchronized (mPackages) {
2302            PackageParser.Activity a = mActivities.mActivities.get(component);
2303
2304            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2305            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2306                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2307                if (ps == null) return null;
2308                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2309                        userId);
2310            }
2311            if (mResolveComponentName.equals(component)) {
2312                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2313                        new PackageUserState(), userId);
2314            }
2315        }
2316        return null;
2317    }
2318
2319    @Override
2320    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2321            String resolvedType) {
2322        synchronized (mPackages) {
2323            PackageParser.Activity a = mActivities.mActivities.get(component);
2324            if (a == null) {
2325                return false;
2326            }
2327            for (int i=0; i<a.intents.size(); i++) {
2328                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2329                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2330                    return true;
2331                }
2332            }
2333            return false;
2334        }
2335    }
2336
2337    @Override
2338    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2339        if (!sUserManager.exists(userId)) return null;
2340        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2341        synchronized (mPackages) {
2342            PackageParser.Activity a = mReceivers.mActivities.get(component);
2343            if (DEBUG_PACKAGE_INFO) Log.v(
2344                TAG, "getReceiverInfo " + component + ": " + a);
2345            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2346                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2347                if (ps == null) return null;
2348                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2349                        userId);
2350            }
2351        }
2352        return null;
2353    }
2354
2355    @Override
2356    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2357        if (!sUserManager.exists(userId)) return null;
2358        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2359        synchronized (mPackages) {
2360            PackageParser.Service s = mServices.mServices.get(component);
2361            if (DEBUG_PACKAGE_INFO) Log.v(
2362                TAG, "getServiceInfo " + component + ": " + s);
2363            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2364                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2365                if (ps == null) return null;
2366                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2367                        userId);
2368            }
2369        }
2370        return null;
2371    }
2372
2373    @Override
2374    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2375        if (!sUserManager.exists(userId)) return null;
2376        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2377        synchronized (mPackages) {
2378            PackageParser.Provider p = mProviders.mProviders.get(component);
2379            if (DEBUG_PACKAGE_INFO) Log.v(
2380                TAG, "getProviderInfo " + component + ": " + p);
2381            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2382                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2383                if (ps == null) return null;
2384                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2385                        userId);
2386            }
2387        }
2388        return null;
2389    }
2390
2391    @Override
2392    public String[] getSystemSharedLibraryNames() {
2393        Set<String> libSet;
2394        synchronized (mPackages) {
2395            libSet = mSharedLibraries.keySet();
2396            int size = libSet.size();
2397            if (size > 0) {
2398                String[] libs = new String[size];
2399                libSet.toArray(libs);
2400                return libs;
2401            }
2402        }
2403        return null;
2404    }
2405
2406    /**
2407     * @hide
2408     */
2409    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2410        synchronized (mPackages) {
2411            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2412            if (lib != null && lib.apk != null) {
2413                return mPackages.get(lib.apk);
2414            }
2415        }
2416        return null;
2417    }
2418
2419    @Override
2420    public FeatureInfo[] getSystemAvailableFeatures() {
2421        Collection<FeatureInfo> featSet;
2422        synchronized (mPackages) {
2423            featSet = mAvailableFeatures.values();
2424            int size = featSet.size();
2425            if (size > 0) {
2426                FeatureInfo[] features = new FeatureInfo[size+1];
2427                featSet.toArray(features);
2428                FeatureInfo fi = new FeatureInfo();
2429                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2430                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2431                features[size] = fi;
2432                return features;
2433            }
2434        }
2435        return null;
2436    }
2437
2438    @Override
2439    public boolean hasSystemFeature(String name) {
2440        synchronized (mPackages) {
2441            return mAvailableFeatures.containsKey(name);
2442        }
2443    }
2444
2445    private void checkValidCaller(int uid, int userId) {
2446        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2447            return;
2448
2449        throw new SecurityException("Caller uid=" + uid
2450                + " is not privileged to communicate with user=" + userId);
2451    }
2452
2453    @Override
2454    public int checkPermission(String permName, String pkgName, int userId) {
2455        if (!sUserManager.exists(userId)) {
2456            return PackageManager.PERMISSION_DENIED;
2457        }
2458
2459        synchronized (mPackages) {
2460            final PackageParser.Package p = mPackages.get(pkgName);
2461            if (p != null && p.mExtras != null) {
2462                final PackageSetting ps = (PackageSetting) p.mExtras;
2463                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2464                    return PackageManager.PERMISSION_GRANTED;
2465                }
2466            }
2467        }
2468
2469        return PackageManager.PERMISSION_DENIED;
2470    }
2471
2472    @Override
2473    public int checkUidPermission(String permName, int uid) {
2474        final int userId = UserHandle.getUserId(uid);
2475
2476        if (!sUserManager.exists(userId)) {
2477            return PackageManager.PERMISSION_DENIED;
2478        }
2479
2480        synchronized (mPackages) {
2481            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2482            if (obj != null) {
2483                final SettingBase ps = (SettingBase) obj;
2484                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2485                    return PackageManager.PERMISSION_GRANTED;
2486                }
2487            } else {
2488                ArraySet<String> perms = mSystemPermissions.get(uid);
2489                if (perms != null && perms.contains(permName)) {
2490                    return PackageManager.PERMISSION_GRANTED;
2491                }
2492            }
2493        }
2494
2495        return PackageManager.PERMISSION_DENIED;
2496    }
2497
2498    /**
2499     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2500     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2501     * @param checkShell TODO(yamasani):
2502     * @param message the message to log on security exception
2503     */
2504    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2505            boolean checkShell, String message) {
2506        if (userId < 0) {
2507            throw new IllegalArgumentException("Invalid userId " + userId);
2508        }
2509        if (checkShell) {
2510            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2511        }
2512        if (userId == UserHandle.getUserId(callingUid)) return;
2513        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2514            if (requireFullPermission) {
2515                mContext.enforceCallingOrSelfPermission(
2516                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2517            } else {
2518                try {
2519                    mContext.enforceCallingOrSelfPermission(
2520                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2521                } catch (SecurityException se) {
2522                    mContext.enforceCallingOrSelfPermission(
2523                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2524                }
2525            }
2526        }
2527    }
2528
2529    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2530        if (callingUid == Process.SHELL_UID) {
2531            if (userHandle >= 0
2532                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2533                throw new SecurityException("Shell does not have permission to access user "
2534                        + userHandle);
2535            } else if (userHandle < 0) {
2536                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2537                        + Debug.getCallers(3));
2538            }
2539        }
2540    }
2541
2542    private BasePermission findPermissionTreeLP(String permName) {
2543        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2544            if (permName.startsWith(bp.name) &&
2545                    permName.length() > bp.name.length() &&
2546                    permName.charAt(bp.name.length()) == '.') {
2547                return bp;
2548            }
2549        }
2550        return null;
2551    }
2552
2553    private BasePermission checkPermissionTreeLP(String permName) {
2554        if (permName != null) {
2555            BasePermission bp = findPermissionTreeLP(permName);
2556            if (bp != null) {
2557                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2558                    return bp;
2559                }
2560                throw new SecurityException("Calling uid "
2561                        + Binder.getCallingUid()
2562                        + " is not allowed to add to permission tree "
2563                        + bp.name + " owned by uid " + bp.uid);
2564            }
2565        }
2566        throw new SecurityException("No permission tree found for " + permName);
2567    }
2568
2569    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2570        if (s1 == null) {
2571            return s2 == null;
2572        }
2573        if (s2 == null) {
2574            return false;
2575        }
2576        if (s1.getClass() != s2.getClass()) {
2577            return false;
2578        }
2579        return s1.equals(s2);
2580    }
2581
2582    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2583        if (pi1.icon != pi2.icon) return false;
2584        if (pi1.logo != pi2.logo) return false;
2585        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2586        if (!compareStrings(pi1.name, pi2.name)) return false;
2587        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2588        // We'll take care of setting this one.
2589        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2590        // These are not currently stored in settings.
2591        //if (!compareStrings(pi1.group, pi2.group)) return false;
2592        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2593        //if (pi1.labelRes != pi2.labelRes) return false;
2594        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2595        return true;
2596    }
2597
2598    int permissionInfoFootprint(PermissionInfo info) {
2599        int size = info.name.length();
2600        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2601        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2602        return size;
2603    }
2604
2605    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2606        int size = 0;
2607        for (BasePermission perm : mSettings.mPermissions.values()) {
2608            if (perm.uid == tree.uid) {
2609                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2610            }
2611        }
2612        return size;
2613    }
2614
2615    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2616        // We calculate the max size of permissions defined by this uid and throw
2617        // if that plus the size of 'info' would exceed our stated maximum.
2618        if (tree.uid != Process.SYSTEM_UID) {
2619            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2620            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2621                throw new SecurityException("Permission tree size cap exceeded");
2622            }
2623        }
2624    }
2625
2626    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2627        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2628            throw new SecurityException("Label must be specified in permission");
2629        }
2630        BasePermission tree = checkPermissionTreeLP(info.name);
2631        BasePermission bp = mSettings.mPermissions.get(info.name);
2632        boolean added = bp == null;
2633        boolean changed = true;
2634        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2635        if (added) {
2636            enforcePermissionCapLocked(info, tree);
2637            bp = new BasePermission(info.name, tree.sourcePackage,
2638                    BasePermission.TYPE_DYNAMIC);
2639        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2640            throw new SecurityException(
2641                    "Not allowed to modify non-dynamic permission "
2642                    + info.name);
2643        } else {
2644            if (bp.protectionLevel == fixedLevel
2645                    && bp.perm.owner.equals(tree.perm.owner)
2646                    && bp.uid == tree.uid
2647                    && comparePermissionInfos(bp.perm.info, info)) {
2648                changed = false;
2649            }
2650        }
2651        bp.protectionLevel = fixedLevel;
2652        info = new PermissionInfo(info);
2653        info.protectionLevel = fixedLevel;
2654        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2655        bp.perm.info.packageName = tree.perm.info.packageName;
2656        bp.uid = tree.uid;
2657        if (added) {
2658            mSettings.mPermissions.put(info.name, bp);
2659        }
2660        if (changed) {
2661            if (!async) {
2662                mSettings.writeLPr();
2663            } else {
2664                scheduleWriteSettingsLocked();
2665            }
2666        }
2667        return added;
2668    }
2669
2670    @Override
2671    public boolean addPermission(PermissionInfo info) {
2672        synchronized (mPackages) {
2673            return addPermissionLocked(info, false);
2674        }
2675    }
2676
2677    @Override
2678    public boolean addPermissionAsync(PermissionInfo info) {
2679        synchronized (mPackages) {
2680            return addPermissionLocked(info, true);
2681        }
2682    }
2683
2684    @Override
2685    public void removePermission(String name) {
2686        synchronized (mPackages) {
2687            checkPermissionTreeLP(name);
2688            BasePermission bp = mSettings.mPermissions.get(name);
2689            if (bp != null) {
2690                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2691                    throw new SecurityException(
2692                            "Not allowed to modify non-dynamic permission "
2693                            + name);
2694                }
2695                mSettings.mPermissions.remove(name);
2696                mSettings.writeLPr();
2697            }
2698        }
2699    }
2700
2701    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
2702            BasePermission bp) {
2703        int index = pkg.requestedPermissions.indexOf(bp.name);
2704        if (index == -1) {
2705            throw new SecurityException("Package " + pkg.packageName
2706                    + " has not requested permission " + bp.name);
2707        }
2708        if (!bp.isRuntime()) {
2709            throw new SecurityException("Permission " + bp.name
2710                    + " is not a changeable permission type");
2711        }
2712    }
2713
2714    @Override
2715    public boolean grantPermission(String packageName, String name, int userId) {
2716        if (!sUserManager.exists(userId)) {
2717            return false;
2718        }
2719
2720        mContext.enforceCallingOrSelfPermission(
2721                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
2722                "grantPermission");
2723
2724        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
2725                "grantPermission");
2726
2727        synchronized (mPackages) {
2728            final PackageParser.Package pkg = mPackages.get(packageName);
2729            if (pkg == null) {
2730                throw new IllegalArgumentException("Unknown package: " + packageName);
2731            }
2732
2733            final BasePermission bp = mSettings.mPermissions.get(name);
2734            if (bp == null) {
2735                throw new IllegalArgumentException("Unknown permission: " + name);
2736            }
2737
2738            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
2739
2740            final SettingBase sb = (SettingBase) pkg.mExtras;
2741            if (sb == null) {
2742                throw new IllegalArgumentException("Unknown package: " + packageName);
2743            }
2744
2745            final PermissionsState permissionsState = sb.getPermissionsState();
2746
2747            final int result = permissionsState.grantRuntimePermission(bp, userId);
2748            switch (result) {
2749                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
2750                    return false;
2751                }
2752
2753                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
2754                    killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
2755                } break;
2756            }
2757
2758            // Not critical if that is lost - app has to request again.
2759            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
2760
2761            return true;
2762        }
2763    }
2764
2765    @Override
2766    public boolean revokePermission(String packageName, String name, int userId) {
2767        if (!sUserManager.exists(userId)) {
2768            return false;
2769        }
2770
2771        mContext.enforceCallingOrSelfPermission(
2772                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
2773                "revokePermission");
2774
2775        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
2776                "revokePermission");
2777
2778        synchronized (mPackages) {
2779            final PackageParser.Package pkg = mPackages.get(packageName);
2780            if (pkg == null) {
2781                throw new IllegalArgumentException("Unknown package: " + packageName);
2782            }
2783
2784            final BasePermission bp = mSettings.mPermissions.get(name);
2785            if (bp == null) {
2786                throw new IllegalArgumentException("Unknown permission: " + name);
2787            }
2788
2789            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
2790
2791            final SettingBase sb = (SettingBase) pkg.mExtras;
2792            if (sb == null) {
2793                throw new IllegalArgumentException("Unknown package: " + packageName);
2794            }
2795
2796            final PermissionsState permissionsState = sb.getPermissionsState();
2797
2798            if (permissionsState.revokeRuntimePermission(bp, userId) ==
2799                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
2800                return false;
2801            }
2802
2803            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
2804
2805            // Critical, after this call all should never have the permission.
2806            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
2807
2808            return true;
2809        }
2810    }
2811
2812    @Override
2813    public boolean isProtectedBroadcast(String actionName) {
2814        synchronized (mPackages) {
2815            return mProtectedBroadcasts.contains(actionName);
2816        }
2817    }
2818
2819    @Override
2820    public int checkSignatures(String pkg1, String pkg2) {
2821        synchronized (mPackages) {
2822            final PackageParser.Package p1 = mPackages.get(pkg1);
2823            final PackageParser.Package p2 = mPackages.get(pkg2);
2824            if (p1 == null || p1.mExtras == null
2825                    || p2 == null || p2.mExtras == null) {
2826                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2827            }
2828            return compareSignatures(p1.mSignatures, p2.mSignatures);
2829        }
2830    }
2831
2832    @Override
2833    public int checkUidSignatures(int uid1, int uid2) {
2834        // Map to base uids.
2835        uid1 = UserHandle.getAppId(uid1);
2836        uid2 = UserHandle.getAppId(uid2);
2837        // reader
2838        synchronized (mPackages) {
2839            Signature[] s1;
2840            Signature[] s2;
2841            Object obj = mSettings.getUserIdLPr(uid1);
2842            if (obj != null) {
2843                if (obj instanceof SharedUserSetting) {
2844                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2845                } else if (obj instanceof PackageSetting) {
2846                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2847                } else {
2848                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2849                }
2850            } else {
2851                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2852            }
2853            obj = mSettings.getUserIdLPr(uid2);
2854            if (obj != null) {
2855                if (obj instanceof SharedUserSetting) {
2856                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2857                } else if (obj instanceof PackageSetting) {
2858                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2859                } else {
2860                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2861                }
2862            } else {
2863                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2864            }
2865            return compareSignatures(s1, s2);
2866        }
2867    }
2868
2869    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
2870        final long identity = Binder.clearCallingIdentity();
2871        try {
2872            if (sb instanceof SharedUserSetting) {
2873                SharedUserSetting sus = (SharedUserSetting) sb;
2874                final int packageCount = sus.packages.size();
2875                for (int i = 0; i < packageCount; i++) {
2876                    PackageSetting susPs = sus.packages.valueAt(i);
2877                    if (userId == UserHandle.USER_ALL) {
2878                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
2879                    } else {
2880                        final int uid = UserHandle.getUid(userId, susPs.appId);
2881                        killUid(uid, reason);
2882                    }
2883                }
2884            } else if (sb instanceof PackageSetting) {
2885                PackageSetting ps = (PackageSetting) sb;
2886                if (userId == UserHandle.USER_ALL) {
2887                    killApplication(ps.pkg.packageName, ps.appId, reason);
2888                } else {
2889                    final int uid = UserHandle.getUid(userId, ps.appId);
2890                    killUid(uid, reason);
2891                }
2892            }
2893        } finally {
2894            Binder.restoreCallingIdentity(identity);
2895        }
2896    }
2897
2898    private static void killUid(int uid, String reason) {
2899        IActivityManager am = ActivityManagerNative.getDefault();
2900        if (am != null) {
2901            try {
2902                am.killUid(uid, reason);
2903            } catch (RemoteException e) {
2904                /* ignore - same process */
2905            }
2906        }
2907    }
2908
2909    /**
2910     * Compares two sets of signatures. Returns:
2911     * <br />
2912     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2913     * <br />
2914     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2915     * <br />
2916     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2917     * <br />
2918     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2919     * <br />
2920     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2921     */
2922    static int compareSignatures(Signature[] s1, Signature[] s2) {
2923        if (s1 == null) {
2924            return s2 == null
2925                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2926                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2927        }
2928
2929        if (s2 == null) {
2930            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2931        }
2932
2933        if (s1.length != s2.length) {
2934            return PackageManager.SIGNATURE_NO_MATCH;
2935        }
2936
2937        // Since both signature sets are of size 1, we can compare without HashSets.
2938        if (s1.length == 1) {
2939            return s1[0].equals(s2[0]) ?
2940                    PackageManager.SIGNATURE_MATCH :
2941                    PackageManager.SIGNATURE_NO_MATCH;
2942        }
2943
2944        ArraySet<Signature> set1 = new ArraySet<Signature>();
2945        for (Signature sig : s1) {
2946            set1.add(sig);
2947        }
2948        ArraySet<Signature> set2 = new ArraySet<Signature>();
2949        for (Signature sig : s2) {
2950            set2.add(sig);
2951        }
2952        // Make sure s2 contains all signatures in s1.
2953        if (set1.equals(set2)) {
2954            return PackageManager.SIGNATURE_MATCH;
2955        }
2956        return PackageManager.SIGNATURE_NO_MATCH;
2957    }
2958
2959    /**
2960     * If the database version for this type of package (internal storage or
2961     * external storage) is less than the version where package signatures
2962     * were updated, return true.
2963     */
2964    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2965        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2966                DatabaseVersion.SIGNATURE_END_ENTITY))
2967                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2968                        DatabaseVersion.SIGNATURE_END_ENTITY));
2969    }
2970
2971    /**
2972     * Used for backward compatibility to make sure any packages with
2973     * certificate chains get upgraded to the new style. {@code existingSigs}
2974     * will be in the old format (since they were stored on disk from before the
2975     * system upgrade) and {@code scannedSigs} will be in the newer format.
2976     */
2977    private int compareSignaturesCompat(PackageSignatures existingSigs,
2978            PackageParser.Package scannedPkg) {
2979        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2980            return PackageManager.SIGNATURE_NO_MATCH;
2981        }
2982
2983        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2984        for (Signature sig : existingSigs.mSignatures) {
2985            existingSet.add(sig);
2986        }
2987        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2988        for (Signature sig : scannedPkg.mSignatures) {
2989            try {
2990                Signature[] chainSignatures = sig.getChainSignatures();
2991                for (Signature chainSig : chainSignatures) {
2992                    scannedCompatSet.add(chainSig);
2993                }
2994            } catch (CertificateEncodingException e) {
2995                scannedCompatSet.add(sig);
2996            }
2997        }
2998        /*
2999         * Make sure the expanded scanned set contains all signatures in the
3000         * existing one.
3001         */
3002        if (scannedCompatSet.equals(existingSet)) {
3003            // Migrate the old signatures to the new scheme.
3004            existingSigs.assignSignatures(scannedPkg.mSignatures);
3005            // The new KeySets will be re-added later in the scanning process.
3006            synchronized (mPackages) {
3007                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3008            }
3009            return PackageManager.SIGNATURE_MATCH;
3010        }
3011        return PackageManager.SIGNATURE_NO_MATCH;
3012    }
3013
3014    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3015        if (isExternal(scannedPkg)) {
3016            return mSettings.isExternalDatabaseVersionOlderThan(
3017                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3018        } else {
3019            return mSettings.isInternalDatabaseVersionOlderThan(
3020                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3021        }
3022    }
3023
3024    private int compareSignaturesRecover(PackageSignatures existingSigs,
3025            PackageParser.Package scannedPkg) {
3026        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3027            return PackageManager.SIGNATURE_NO_MATCH;
3028        }
3029
3030        String msg = null;
3031        try {
3032            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3033                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3034                        + scannedPkg.packageName);
3035                return PackageManager.SIGNATURE_MATCH;
3036            }
3037        } catch (CertificateException e) {
3038            msg = e.getMessage();
3039        }
3040
3041        logCriticalInfo(Log.INFO,
3042                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3043        return PackageManager.SIGNATURE_NO_MATCH;
3044    }
3045
3046    @Override
3047    public String[] getPackagesForUid(int uid) {
3048        uid = UserHandle.getAppId(uid);
3049        // reader
3050        synchronized (mPackages) {
3051            Object obj = mSettings.getUserIdLPr(uid);
3052            if (obj instanceof SharedUserSetting) {
3053                final SharedUserSetting sus = (SharedUserSetting) obj;
3054                final int N = sus.packages.size();
3055                final String[] res = new String[N];
3056                final Iterator<PackageSetting> it = sus.packages.iterator();
3057                int i = 0;
3058                while (it.hasNext()) {
3059                    res[i++] = it.next().name;
3060                }
3061                return res;
3062            } else if (obj instanceof PackageSetting) {
3063                final PackageSetting ps = (PackageSetting) obj;
3064                return new String[] { ps.name };
3065            }
3066        }
3067        return null;
3068    }
3069
3070    @Override
3071    public String getNameForUid(int uid) {
3072        // reader
3073        synchronized (mPackages) {
3074            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3075            if (obj instanceof SharedUserSetting) {
3076                final SharedUserSetting sus = (SharedUserSetting) obj;
3077                return sus.name + ":" + sus.userId;
3078            } else if (obj instanceof PackageSetting) {
3079                final PackageSetting ps = (PackageSetting) obj;
3080                return ps.name;
3081            }
3082        }
3083        return null;
3084    }
3085
3086    @Override
3087    public int getUidForSharedUser(String sharedUserName) {
3088        if(sharedUserName == null) {
3089            return -1;
3090        }
3091        // reader
3092        synchronized (mPackages) {
3093            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3094            if (suid == null) {
3095                return -1;
3096            }
3097            return suid.userId;
3098        }
3099    }
3100
3101    @Override
3102    public int getFlagsForUid(int uid) {
3103        synchronized (mPackages) {
3104            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3105            if (obj instanceof SharedUserSetting) {
3106                final SharedUserSetting sus = (SharedUserSetting) obj;
3107                return sus.pkgFlags;
3108            } else if (obj instanceof PackageSetting) {
3109                final PackageSetting ps = (PackageSetting) obj;
3110                return ps.pkgFlags;
3111            }
3112        }
3113        return 0;
3114    }
3115
3116    @Override
3117    public int getPrivateFlagsForUid(int uid) {
3118        synchronized (mPackages) {
3119            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3120            if (obj instanceof SharedUserSetting) {
3121                final SharedUserSetting sus = (SharedUserSetting) obj;
3122                return sus.pkgPrivateFlags;
3123            } else if (obj instanceof PackageSetting) {
3124                final PackageSetting ps = (PackageSetting) obj;
3125                return ps.pkgPrivateFlags;
3126            }
3127        }
3128        return 0;
3129    }
3130
3131    @Override
3132    public boolean isUidPrivileged(int uid) {
3133        uid = UserHandle.getAppId(uid);
3134        // reader
3135        synchronized (mPackages) {
3136            Object obj = mSettings.getUserIdLPr(uid);
3137            if (obj instanceof SharedUserSetting) {
3138                final SharedUserSetting sus = (SharedUserSetting) obj;
3139                final Iterator<PackageSetting> it = sus.packages.iterator();
3140                while (it.hasNext()) {
3141                    if (it.next().isPrivileged()) {
3142                        return true;
3143                    }
3144                }
3145            } else if (obj instanceof PackageSetting) {
3146                final PackageSetting ps = (PackageSetting) obj;
3147                return ps.isPrivileged();
3148            }
3149        }
3150        return false;
3151    }
3152
3153    @Override
3154    public String[] getAppOpPermissionPackages(String permissionName) {
3155        synchronized (mPackages) {
3156            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3157            if (pkgs == null) {
3158                return null;
3159            }
3160            return pkgs.toArray(new String[pkgs.size()]);
3161        }
3162    }
3163
3164    @Override
3165    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3166            int flags, int userId) {
3167        if (!sUserManager.exists(userId)) return null;
3168        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3169        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3170        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3171    }
3172
3173    @Override
3174    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3175            IntentFilter filter, int match, ComponentName activity) {
3176        final int userId = UserHandle.getCallingUserId();
3177        if (DEBUG_PREFERRED) {
3178            Log.v(TAG, "setLastChosenActivity intent=" + intent
3179                + " resolvedType=" + resolvedType
3180                + " flags=" + flags
3181                + " filter=" + filter
3182                + " match=" + match
3183                + " activity=" + activity);
3184            filter.dump(new PrintStreamPrinter(System.out), "    ");
3185        }
3186        intent.setComponent(null);
3187        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3188        // Find any earlier preferred or last chosen entries and nuke them
3189        findPreferredActivity(intent, resolvedType,
3190                flags, query, 0, false, true, false, userId);
3191        // Add the new activity as the last chosen for this filter
3192        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3193                "Setting last chosen");
3194    }
3195
3196    @Override
3197    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3198        final int userId = UserHandle.getCallingUserId();
3199        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3200        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3201        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3202                false, false, false, userId);
3203    }
3204
3205    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3206            int flags, List<ResolveInfo> query, int userId) {
3207        if (query != null) {
3208            final int N = query.size();
3209            if (N == 1) {
3210                return query.get(0);
3211            } else if (N > 1) {
3212                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3213                // If there is more than one activity with the same priority,
3214                // then let the user decide between them.
3215                ResolveInfo r0 = query.get(0);
3216                ResolveInfo r1 = query.get(1);
3217                if (DEBUG_INTENT_MATCHING || debug) {
3218                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3219                            + r1.activityInfo.name + "=" + r1.priority);
3220                }
3221                // If the first activity has a higher priority, or a different
3222                // default, then it is always desireable to pick it.
3223                if (r0.priority != r1.priority
3224                        || r0.preferredOrder != r1.preferredOrder
3225                        || r0.isDefault != r1.isDefault) {
3226                    return query.get(0);
3227                }
3228                // If we have saved a preference for a preferred activity for
3229                // this Intent, use that.
3230                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3231                        flags, query, r0.priority, true, false, debug, userId);
3232                if (ri != null) {
3233                    return ri;
3234                }
3235                if (userId != 0) {
3236                    ri = new ResolveInfo(mResolveInfo);
3237                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3238                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3239                            ri.activityInfo.applicationInfo);
3240                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3241                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3242                    return ri;
3243                }
3244                return mResolveInfo;
3245            }
3246        }
3247        return null;
3248    }
3249
3250    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3251            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3252        final int N = query.size();
3253        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3254                .get(userId);
3255        // Get the list of persistent preferred activities that handle the intent
3256        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3257        List<PersistentPreferredActivity> pprefs = ppir != null
3258                ? ppir.queryIntent(intent, resolvedType,
3259                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3260                : null;
3261        if (pprefs != null && pprefs.size() > 0) {
3262            final int M = pprefs.size();
3263            for (int i=0; i<M; i++) {
3264                final PersistentPreferredActivity ppa = pprefs.get(i);
3265                if (DEBUG_PREFERRED || debug) {
3266                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3267                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3268                            + "\n  component=" + ppa.mComponent);
3269                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3270                }
3271                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3272                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3273                if (DEBUG_PREFERRED || debug) {
3274                    Slog.v(TAG, "Found persistent preferred activity:");
3275                    if (ai != null) {
3276                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3277                    } else {
3278                        Slog.v(TAG, "  null");
3279                    }
3280                }
3281                if (ai == null) {
3282                    // This previously registered persistent preferred activity
3283                    // component is no longer known. Ignore it and do NOT remove it.
3284                    continue;
3285                }
3286                for (int j=0; j<N; j++) {
3287                    final ResolveInfo ri = query.get(j);
3288                    if (!ri.activityInfo.applicationInfo.packageName
3289                            .equals(ai.applicationInfo.packageName)) {
3290                        continue;
3291                    }
3292                    if (!ri.activityInfo.name.equals(ai.name)) {
3293                        continue;
3294                    }
3295                    //  Found a persistent preference that can handle the intent.
3296                    if (DEBUG_PREFERRED || debug) {
3297                        Slog.v(TAG, "Returning persistent preferred activity: " +
3298                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3299                    }
3300                    return ri;
3301                }
3302            }
3303        }
3304        return null;
3305    }
3306
3307    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3308            List<ResolveInfo> query, int priority, boolean always,
3309            boolean removeMatches, boolean debug, int userId) {
3310        if (!sUserManager.exists(userId)) return null;
3311        // writer
3312        synchronized (mPackages) {
3313            if (intent.getSelector() != null) {
3314                intent = intent.getSelector();
3315            }
3316            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3317
3318            // Try to find a matching persistent preferred activity.
3319            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3320                    debug, userId);
3321
3322            // If a persistent preferred activity matched, use it.
3323            if (pri != null) {
3324                return pri;
3325            }
3326
3327            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3328            // Get the list of preferred activities that handle the intent
3329            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3330            List<PreferredActivity> prefs = pir != null
3331                    ? pir.queryIntent(intent, resolvedType,
3332                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3333                    : null;
3334            if (prefs != null && prefs.size() > 0) {
3335                boolean changed = false;
3336                try {
3337                    // First figure out how good the original match set is.
3338                    // We will only allow preferred activities that came
3339                    // from the same match quality.
3340                    int match = 0;
3341
3342                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3343
3344                    final int N = query.size();
3345                    for (int j=0; j<N; j++) {
3346                        final ResolveInfo ri = query.get(j);
3347                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3348                                + ": 0x" + Integer.toHexString(match));
3349                        if (ri.match > match) {
3350                            match = ri.match;
3351                        }
3352                    }
3353
3354                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3355                            + Integer.toHexString(match));
3356
3357                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3358                    final int M = prefs.size();
3359                    for (int i=0; i<M; i++) {
3360                        final PreferredActivity pa = prefs.get(i);
3361                        if (DEBUG_PREFERRED || debug) {
3362                            Slog.v(TAG, "Checking PreferredActivity ds="
3363                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3364                                    + "\n  component=" + pa.mPref.mComponent);
3365                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3366                        }
3367                        if (pa.mPref.mMatch != match) {
3368                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3369                                    + Integer.toHexString(pa.mPref.mMatch));
3370                            continue;
3371                        }
3372                        // If it's not an "always" type preferred activity and that's what we're
3373                        // looking for, skip it.
3374                        if (always && !pa.mPref.mAlways) {
3375                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3376                            continue;
3377                        }
3378                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3379                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3380                        if (DEBUG_PREFERRED || debug) {
3381                            Slog.v(TAG, "Found preferred activity:");
3382                            if (ai != null) {
3383                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3384                            } else {
3385                                Slog.v(TAG, "  null");
3386                            }
3387                        }
3388                        if (ai == null) {
3389                            // This previously registered preferred activity
3390                            // component is no longer known.  Most likely an update
3391                            // to the app was installed and in the new version this
3392                            // component no longer exists.  Clean it up by removing
3393                            // it from the preferred activities list, and skip it.
3394                            Slog.w(TAG, "Removing dangling preferred activity: "
3395                                    + pa.mPref.mComponent);
3396                            pir.removeFilter(pa);
3397                            changed = true;
3398                            continue;
3399                        }
3400                        for (int j=0; j<N; j++) {
3401                            final ResolveInfo ri = query.get(j);
3402                            if (!ri.activityInfo.applicationInfo.packageName
3403                                    .equals(ai.applicationInfo.packageName)) {
3404                                continue;
3405                            }
3406                            if (!ri.activityInfo.name.equals(ai.name)) {
3407                                continue;
3408                            }
3409
3410                            if (removeMatches) {
3411                                pir.removeFilter(pa);
3412                                changed = true;
3413                                if (DEBUG_PREFERRED) {
3414                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3415                                }
3416                                break;
3417                            }
3418
3419                            // Okay we found a previously set preferred or last chosen app.
3420                            // If the result set is different from when this
3421                            // was created, we need to clear it and re-ask the
3422                            // user their preference, if we're looking for an "always" type entry.
3423                            if (always && !pa.mPref.sameSet(query)) {
3424                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3425                                        + intent + " type " + resolvedType);
3426                                if (DEBUG_PREFERRED) {
3427                                    Slog.v(TAG, "Removing preferred activity since set changed "
3428                                            + pa.mPref.mComponent);
3429                                }
3430                                pir.removeFilter(pa);
3431                                // Re-add the filter as a "last chosen" entry (!always)
3432                                PreferredActivity lastChosen = new PreferredActivity(
3433                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3434                                pir.addFilter(lastChosen);
3435                                changed = true;
3436                                return null;
3437                            }
3438
3439                            // Yay! Either the set matched or we're looking for the last chosen
3440                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3441                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3442                            return ri;
3443                        }
3444                    }
3445                } finally {
3446                    if (changed) {
3447                        if (DEBUG_PREFERRED) {
3448                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3449                        }
3450                        scheduleWritePackageRestrictionsLocked(userId);
3451                    }
3452                }
3453            }
3454        }
3455        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3456        return null;
3457    }
3458
3459    /*
3460     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3461     */
3462    @Override
3463    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3464            int targetUserId) {
3465        mContext.enforceCallingOrSelfPermission(
3466                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3467        List<CrossProfileIntentFilter> matches =
3468                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3469        if (matches != null) {
3470            int size = matches.size();
3471            for (int i = 0; i < size; i++) {
3472                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3473            }
3474        }
3475        return false;
3476    }
3477
3478    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3479            String resolvedType, int userId) {
3480        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3481        if (resolver != null) {
3482            return resolver.queryIntent(intent, resolvedType, false, userId);
3483        }
3484        return null;
3485    }
3486
3487    @Override
3488    public List<ResolveInfo> queryIntentActivities(Intent intent,
3489            String resolvedType, int flags, int userId) {
3490        if (!sUserManager.exists(userId)) return Collections.emptyList();
3491        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3492        ComponentName comp = intent.getComponent();
3493        if (comp == null) {
3494            if (intent.getSelector() != null) {
3495                intent = intent.getSelector();
3496                comp = intent.getComponent();
3497            }
3498        }
3499
3500        if (comp != null) {
3501            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3502            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3503            if (ai != null) {
3504                final ResolveInfo ri = new ResolveInfo();
3505                ri.activityInfo = ai;
3506                list.add(ri);
3507            }
3508            return list;
3509        }
3510
3511        // reader
3512        synchronized (mPackages) {
3513            final String pkgName = intent.getPackage();
3514            if (pkgName == null) {
3515                List<CrossProfileIntentFilter> matchingFilters =
3516                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3517                // Check for results that need to skip the current profile.
3518                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3519                        resolvedType, flags, userId);
3520                if (resolveInfo != null) {
3521                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3522                    result.add(resolveInfo);
3523                    return filterIfNotPrimaryUser(result, userId);
3524                }
3525                // Check for cross profile results.
3526                resolveInfo = queryCrossProfileIntents(
3527                        matchingFilters, intent, resolvedType, flags, userId);
3528
3529                // Check for results in the current profile.
3530                List<ResolveInfo> result = mActivities.queryIntent(
3531                        intent, resolvedType, flags, userId);
3532                if (resolveInfo != null) {
3533                    result.add(resolveInfo);
3534                    Collections.sort(result, mResolvePrioritySorter);
3535                }
3536                return filterIfNotPrimaryUser(result, userId);
3537            }
3538            final PackageParser.Package pkg = mPackages.get(pkgName);
3539            if (pkg != null) {
3540                return filterIfNotPrimaryUser(
3541                        mActivities.queryIntentForPackage(
3542                                intent, resolvedType, flags, pkg.activities, userId),
3543                        userId);
3544            }
3545            return new ArrayList<ResolveInfo>();
3546        }
3547    }
3548
3549    /**
3550     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3551     *
3552     * @return filtered list
3553     */
3554    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3555        if (userId == UserHandle.USER_OWNER) {
3556            return resolveInfos;
3557        }
3558        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3559            ResolveInfo info = resolveInfos.get(i);
3560            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3561                resolveInfos.remove(i);
3562            }
3563        }
3564        return resolveInfos;
3565    }
3566
3567
3568    private ResolveInfo querySkipCurrentProfileIntents(
3569            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3570            int flags, int sourceUserId) {
3571        if (matchingFilters != null) {
3572            int size = matchingFilters.size();
3573            for (int i = 0; i < size; i ++) {
3574                CrossProfileIntentFilter filter = matchingFilters.get(i);
3575                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3576                    // Checking if there are activities in the target user that can handle the
3577                    // intent.
3578                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3579                            flags, sourceUserId);
3580                    if (resolveInfo != null) {
3581                        return resolveInfo;
3582                    }
3583                }
3584            }
3585        }
3586        return null;
3587    }
3588
3589    // Return matching ResolveInfo if any for skip current profile intent filters.
3590    private ResolveInfo queryCrossProfileIntents(
3591            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3592            int flags, int sourceUserId) {
3593        if (matchingFilters != null) {
3594            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3595            // match the same intent. For performance reasons, it is better not to
3596            // run queryIntent twice for the same userId
3597            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3598            int size = matchingFilters.size();
3599            for (int i = 0; i < size; i++) {
3600                CrossProfileIntentFilter filter = matchingFilters.get(i);
3601                int targetUserId = filter.getTargetUserId();
3602                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3603                        && !alreadyTriedUserIds.get(targetUserId)) {
3604                    // Checking if there are activities in the target user that can handle the
3605                    // intent.
3606                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3607                            flags, sourceUserId);
3608                    if (resolveInfo != null) return resolveInfo;
3609                    alreadyTriedUserIds.put(targetUserId, true);
3610                }
3611            }
3612        }
3613        return null;
3614    }
3615
3616    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3617            String resolvedType, int flags, int sourceUserId) {
3618        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3619                resolvedType, flags, filter.getTargetUserId());
3620        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3621            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3622        }
3623        return null;
3624    }
3625
3626    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3627            int sourceUserId, int targetUserId) {
3628        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3629        String className;
3630        if (targetUserId == UserHandle.USER_OWNER) {
3631            className = FORWARD_INTENT_TO_USER_OWNER;
3632        } else {
3633            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3634        }
3635        ComponentName forwardingActivityComponentName = new ComponentName(
3636                mAndroidApplication.packageName, className);
3637        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3638                sourceUserId);
3639        if (targetUserId == UserHandle.USER_OWNER) {
3640            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3641            forwardingResolveInfo.noResourceId = true;
3642        }
3643        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3644        forwardingResolveInfo.priority = 0;
3645        forwardingResolveInfo.preferredOrder = 0;
3646        forwardingResolveInfo.match = 0;
3647        forwardingResolveInfo.isDefault = true;
3648        forwardingResolveInfo.filter = filter;
3649        forwardingResolveInfo.targetUserId = targetUserId;
3650        return forwardingResolveInfo;
3651    }
3652
3653    @Override
3654    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3655            Intent[] specifics, String[] specificTypes, Intent intent,
3656            String resolvedType, int flags, int userId) {
3657        if (!sUserManager.exists(userId)) return Collections.emptyList();
3658        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3659                false, "query intent activity options");
3660        final String resultsAction = intent.getAction();
3661
3662        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3663                | PackageManager.GET_RESOLVED_FILTER, userId);
3664
3665        if (DEBUG_INTENT_MATCHING) {
3666            Log.v(TAG, "Query " + intent + ": " + results);
3667        }
3668
3669        int specificsPos = 0;
3670        int N;
3671
3672        // todo: note that the algorithm used here is O(N^2).  This
3673        // isn't a problem in our current environment, but if we start running
3674        // into situations where we have more than 5 or 10 matches then this
3675        // should probably be changed to something smarter...
3676
3677        // First we go through and resolve each of the specific items
3678        // that were supplied, taking care of removing any corresponding
3679        // duplicate items in the generic resolve list.
3680        if (specifics != null) {
3681            for (int i=0; i<specifics.length; i++) {
3682                final Intent sintent = specifics[i];
3683                if (sintent == null) {
3684                    continue;
3685                }
3686
3687                if (DEBUG_INTENT_MATCHING) {
3688                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3689                }
3690
3691                String action = sintent.getAction();
3692                if (resultsAction != null && resultsAction.equals(action)) {
3693                    // If this action was explicitly requested, then don't
3694                    // remove things that have it.
3695                    action = null;
3696                }
3697
3698                ResolveInfo ri = null;
3699                ActivityInfo ai = null;
3700
3701                ComponentName comp = sintent.getComponent();
3702                if (comp == null) {
3703                    ri = resolveIntent(
3704                        sintent,
3705                        specificTypes != null ? specificTypes[i] : null,
3706                            flags, userId);
3707                    if (ri == null) {
3708                        continue;
3709                    }
3710                    if (ri == mResolveInfo) {
3711                        // ACK!  Must do something better with this.
3712                    }
3713                    ai = ri.activityInfo;
3714                    comp = new ComponentName(ai.applicationInfo.packageName,
3715                            ai.name);
3716                } else {
3717                    ai = getActivityInfo(comp, flags, userId);
3718                    if (ai == null) {
3719                        continue;
3720                    }
3721                }
3722
3723                // Look for any generic query activities that are duplicates
3724                // of this specific one, and remove them from the results.
3725                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3726                N = results.size();
3727                int j;
3728                for (j=specificsPos; j<N; j++) {
3729                    ResolveInfo sri = results.get(j);
3730                    if ((sri.activityInfo.name.equals(comp.getClassName())
3731                            && sri.activityInfo.applicationInfo.packageName.equals(
3732                                    comp.getPackageName()))
3733                        || (action != null && sri.filter.matchAction(action))) {
3734                        results.remove(j);
3735                        if (DEBUG_INTENT_MATCHING) Log.v(
3736                            TAG, "Removing duplicate item from " + j
3737                            + " due to specific " + specificsPos);
3738                        if (ri == null) {
3739                            ri = sri;
3740                        }
3741                        j--;
3742                        N--;
3743                    }
3744                }
3745
3746                // Add this specific item to its proper place.
3747                if (ri == null) {
3748                    ri = new ResolveInfo();
3749                    ri.activityInfo = ai;
3750                }
3751                results.add(specificsPos, ri);
3752                ri.specificIndex = i;
3753                specificsPos++;
3754            }
3755        }
3756
3757        // Now we go through the remaining generic results and remove any
3758        // duplicate actions that are found here.
3759        N = results.size();
3760        for (int i=specificsPos; i<N-1; i++) {
3761            final ResolveInfo rii = results.get(i);
3762            if (rii.filter == null) {
3763                continue;
3764            }
3765
3766            // Iterate over all of the actions of this result's intent
3767            // filter...  typically this should be just one.
3768            final Iterator<String> it = rii.filter.actionsIterator();
3769            if (it == null) {
3770                continue;
3771            }
3772            while (it.hasNext()) {
3773                final String action = it.next();
3774                if (resultsAction != null && resultsAction.equals(action)) {
3775                    // If this action was explicitly requested, then don't
3776                    // remove things that have it.
3777                    continue;
3778                }
3779                for (int j=i+1; j<N; j++) {
3780                    final ResolveInfo rij = results.get(j);
3781                    if (rij.filter != null && rij.filter.hasAction(action)) {
3782                        results.remove(j);
3783                        if (DEBUG_INTENT_MATCHING) Log.v(
3784                            TAG, "Removing duplicate item from " + j
3785                            + " due to action " + action + " at " + i);
3786                        j--;
3787                        N--;
3788                    }
3789                }
3790            }
3791
3792            // If the caller didn't request filter information, drop it now
3793            // so we don't have to marshall/unmarshall it.
3794            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3795                rii.filter = null;
3796            }
3797        }
3798
3799        // Filter out the caller activity if so requested.
3800        if (caller != null) {
3801            N = results.size();
3802            for (int i=0; i<N; i++) {
3803                ActivityInfo ainfo = results.get(i).activityInfo;
3804                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3805                        && caller.getClassName().equals(ainfo.name)) {
3806                    results.remove(i);
3807                    break;
3808                }
3809            }
3810        }
3811
3812        // If the caller didn't request filter information,
3813        // drop them now so we don't have to
3814        // marshall/unmarshall it.
3815        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3816            N = results.size();
3817            for (int i=0; i<N; i++) {
3818                results.get(i).filter = null;
3819            }
3820        }
3821
3822        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3823        return results;
3824    }
3825
3826    @Override
3827    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3828            int userId) {
3829        if (!sUserManager.exists(userId)) return Collections.emptyList();
3830        ComponentName comp = intent.getComponent();
3831        if (comp == null) {
3832            if (intent.getSelector() != null) {
3833                intent = intent.getSelector();
3834                comp = intent.getComponent();
3835            }
3836        }
3837        if (comp != null) {
3838            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3839            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3840            if (ai != null) {
3841                ResolveInfo ri = new ResolveInfo();
3842                ri.activityInfo = ai;
3843                list.add(ri);
3844            }
3845            return list;
3846        }
3847
3848        // reader
3849        synchronized (mPackages) {
3850            String pkgName = intent.getPackage();
3851            if (pkgName == null) {
3852                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3853            }
3854            final PackageParser.Package pkg = mPackages.get(pkgName);
3855            if (pkg != null) {
3856                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3857                        userId);
3858            }
3859            return null;
3860        }
3861    }
3862
3863    @Override
3864    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3865        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3866        if (!sUserManager.exists(userId)) return null;
3867        if (query != null) {
3868            if (query.size() >= 1) {
3869                // If there is more than one service with the same priority,
3870                // just arbitrarily pick the first one.
3871                return query.get(0);
3872            }
3873        }
3874        return null;
3875    }
3876
3877    @Override
3878    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3879            int userId) {
3880        if (!sUserManager.exists(userId)) return Collections.emptyList();
3881        ComponentName comp = intent.getComponent();
3882        if (comp == null) {
3883            if (intent.getSelector() != null) {
3884                intent = intent.getSelector();
3885                comp = intent.getComponent();
3886            }
3887        }
3888        if (comp != null) {
3889            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3890            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3891            if (si != null) {
3892                final ResolveInfo ri = new ResolveInfo();
3893                ri.serviceInfo = si;
3894                list.add(ri);
3895            }
3896            return list;
3897        }
3898
3899        // reader
3900        synchronized (mPackages) {
3901            String pkgName = intent.getPackage();
3902            if (pkgName == null) {
3903                return mServices.queryIntent(intent, resolvedType, flags, userId);
3904            }
3905            final PackageParser.Package pkg = mPackages.get(pkgName);
3906            if (pkg != null) {
3907                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3908                        userId);
3909            }
3910            return null;
3911        }
3912    }
3913
3914    @Override
3915    public List<ResolveInfo> queryIntentContentProviders(
3916            Intent intent, String resolvedType, int flags, int userId) {
3917        if (!sUserManager.exists(userId)) return Collections.emptyList();
3918        ComponentName comp = intent.getComponent();
3919        if (comp == null) {
3920            if (intent.getSelector() != null) {
3921                intent = intent.getSelector();
3922                comp = intent.getComponent();
3923            }
3924        }
3925        if (comp != null) {
3926            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3927            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3928            if (pi != null) {
3929                final ResolveInfo ri = new ResolveInfo();
3930                ri.providerInfo = pi;
3931                list.add(ri);
3932            }
3933            return list;
3934        }
3935
3936        // reader
3937        synchronized (mPackages) {
3938            String pkgName = intent.getPackage();
3939            if (pkgName == null) {
3940                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3941            }
3942            final PackageParser.Package pkg = mPackages.get(pkgName);
3943            if (pkg != null) {
3944                return mProviders.queryIntentForPackage(
3945                        intent, resolvedType, flags, pkg.providers, userId);
3946            }
3947            return null;
3948        }
3949    }
3950
3951    @Override
3952    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3953        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3954
3955        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3956
3957        // writer
3958        synchronized (mPackages) {
3959            ArrayList<PackageInfo> list;
3960            if (listUninstalled) {
3961                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3962                for (PackageSetting ps : mSettings.mPackages.values()) {
3963                    PackageInfo pi;
3964                    if (ps.pkg != null) {
3965                        pi = generatePackageInfo(ps.pkg, flags, userId);
3966                    } else {
3967                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3968                    }
3969                    if (pi != null) {
3970                        list.add(pi);
3971                    }
3972                }
3973            } else {
3974                list = new ArrayList<PackageInfo>(mPackages.size());
3975                for (PackageParser.Package p : mPackages.values()) {
3976                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3977                    if (pi != null) {
3978                        list.add(pi);
3979                    }
3980                }
3981            }
3982
3983            return new ParceledListSlice<PackageInfo>(list);
3984        }
3985    }
3986
3987    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3988            String[] permissions, boolean[] tmp, int flags, int userId) {
3989        int numMatch = 0;
3990        final PermissionsState permissionsState = ps.getPermissionsState();
3991        for (int i=0; i<permissions.length; i++) {
3992            final String permission = permissions[i];
3993            if (permissionsState.hasPermission(permission, userId)) {
3994                tmp[i] = true;
3995                numMatch++;
3996            } else {
3997                tmp[i] = false;
3998            }
3999        }
4000        if (numMatch == 0) {
4001            return;
4002        }
4003        PackageInfo pi;
4004        if (ps.pkg != null) {
4005            pi = generatePackageInfo(ps.pkg, flags, userId);
4006        } else {
4007            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4008        }
4009        // The above might return null in cases of uninstalled apps or install-state
4010        // skew across users/profiles.
4011        if (pi != null) {
4012            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4013                if (numMatch == permissions.length) {
4014                    pi.requestedPermissions = permissions;
4015                } else {
4016                    pi.requestedPermissions = new String[numMatch];
4017                    numMatch = 0;
4018                    for (int i=0; i<permissions.length; i++) {
4019                        if (tmp[i]) {
4020                            pi.requestedPermissions[numMatch] = permissions[i];
4021                            numMatch++;
4022                        }
4023                    }
4024                }
4025            }
4026            list.add(pi);
4027        }
4028    }
4029
4030    @Override
4031    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4032            String[] permissions, int flags, int userId) {
4033        if (!sUserManager.exists(userId)) return null;
4034        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4035
4036        // writer
4037        synchronized (mPackages) {
4038            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4039            boolean[] tmpBools = new boolean[permissions.length];
4040            if (listUninstalled) {
4041                for (PackageSetting ps : mSettings.mPackages.values()) {
4042                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4043                }
4044            } else {
4045                for (PackageParser.Package pkg : mPackages.values()) {
4046                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4047                    if (ps != null) {
4048                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4049                                userId);
4050                    }
4051                }
4052            }
4053
4054            return new ParceledListSlice<PackageInfo>(list);
4055        }
4056    }
4057
4058    @Override
4059    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4060        if (!sUserManager.exists(userId)) return null;
4061        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4062
4063        // writer
4064        synchronized (mPackages) {
4065            ArrayList<ApplicationInfo> list;
4066            if (listUninstalled) {
4067                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4068                for (PackageSetting ps : mSettings.mPackages.values()) {
4069                    ApplicationInfo ai;
4070                    if (ps.pkg != null) {
4071                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4072                                ps.readUserState(userId), userId);
4073                    } else {
4074                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4075                    }
4076                    if (ai != null) {
4077                        list.add(ai);
4078                    }
4079                }
4080            } else {
4081                list = new ArrayList<ApplicationInfo>(mPackages.size());
4082                for (PackageParser.Package p : mPackages.values()) {
4083                    if (p.mExtras != null) {
4084                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4085                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4086                        if (ai != null) {
4087                            list.add(ai);
4088                        }
4089                    }
4090                }
4091            }
4092
4093            return new ParceledListSlice<ApplicationInfo>(list);
4094        }
4095    }
4096
4097    public List<ApplicationInfo> getPersistentApplications(int flags) {
4098        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4099
4100        // reader
4101        synchronized (mPackages) {
4102            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4103            final int userId = UserHandle.getCallingUserId();
4104            while (i.hasNext()) {
4105                final PackageParser.Package p = i.next();
4106                if (p.applicationInfo != null
4107                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4108                        && (!mSafeMode || isSystemApp(p))) {
4109                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4110                    if (ps != null) {
4111                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4112                                ps.readUserState(userId), userId);
4113                        if (ai != null) {
4114                            finalList.add(ai);
4115                        }
4116                    }
4117                }
4118            }
4119        }
4120
4121        return finalList;
4122    }
4123
4124    @Override
4125    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4126        if (!sUserManager.exists(userId)) return null;
4127        // reader
4128        synchronized (mPackages) {
4129            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4130            PackageSetting ps = provider != null
4131                    ? mSettings.mPackages.get(provider.owner.packageName)
4132                    : null;
4133            return ps != null
4134                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4135                    && (!mSafeMode || (provider.info.applicationInfo.flags
4136                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4137                    ? PackageParser.generateProviderInfo(provider, flags,
4138                            ps.readUserState(userId), userId)
4139                    : null;
4140        }
4141    }
4142
4143    /**
4144     * @deprecated
4145     */
4146    @Deprecated
4147    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4148        // reader
4149        synchronized (mPackages) {
4150            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4151                    .entrySet().iterator();
4152            final int userId = UserHandle.getCallingUserId();
4153            while (i.hasNext()) {
4154                Map.Entry<String, PackageParser.Provider> entry = i.next();
4155                PackageParser.Provider p = entry.getValue();
4156                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4157
4158                if (ps != null && p.syncable
4159                        && (!mSafeMode || (p.info.applicationInfo.flags
4160                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4161                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4162                            ps.readUserState(userId), userId);
4163                    if (info != null) {
4164                        outNames.add(entry.getKey());
4165                        outInfo.add(info);
4166                    }
4167                }
4168            }
4169        }
4170    }
4171
4172    @Override
4173    public List<ProviderInfo> queryContentProviders(String processName,
4174            int uid, int flags) {
4175        ArrayList<ProviderInfo> finalList = null;
4176        // reader
4177        synchronized (mPackages) {
4178            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4179            final int userId = processName != null ?
4180                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4181            while (i.hasNext()) {
4182                final PackageParser.Provider p = i.next();
4183                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4184                if (ps != null && p.info.authority != null
4185                        && (processName == null
4186                                || (p.info.processName.equals(processName)
4187                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4188                        && mSettings.isEnabledLPr(p.info, flags, userId)
4189                        && (!mSafeMode
4190                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4191                    if (finalList == null) {
4192                        finalList = new ArrayList<ProviderInfo>(3);
4193                    }
4194                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4195                            ps.readUserState(userId), userId);
4196                    if (info != null) {
4197                        finalList.add(info);
4198                    }
4199                }
4200            }
4201        }
4202
4203        if (finalList != null) {
4204            Collections.sort(finalList, mProviderInitOrderSorter);
4205        }
4206
4207        return finalList;
4208    }
4209
4210    @Override
4211    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4212            int flags) {
4213        // reader
4214        synchronized (mPackages) {
4215            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4216            return PackageParser.generateInstrumentationInfo(i, flags);
4217        }
4218    }
4219
4220    @Override
4221    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4222            int flags) {
4223        ArrayList<InstrumentationInfo> finalList =
4224            new ArrayList<InstrumentationInfo>();
4225
4226        // reader
4227        synchronized (mPackages) {
4228            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4229            while (i.hasNext()) {
4230                final PackageParser.Instrumentation p = i.next();
4231                if (targetPackage == null
4232                        || targetPackage.equals(p.info.targetPackage)) {
4233                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4234                            flags);
4235                    if (ii != null) {
4236                        finalList.add(ii);
4237                    }
4238                }
4239            }
4240        }
4241
4242        return finalList;
4243    }
4244
4245    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4246        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4247        if (overlays == null) {
4248            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4249            return;
4250        }
4251        for (PackageParser.Package opkg : overlays.values()) {
4252            // Not much to do if idmap fails: we already logged the error
4253            // and we certainly don't want to abort installation of pkg simply
4254            // because an overlay didn't fit properly. For these reasons,
4255            // ignore the return value of createIdmapForPackagePairLI.
4256            createIdmapForPackagePairLI(pkg, opkg);
4257        }
4258    }
4259
4260    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4261            PackageParser.Package opkg) {
4262        if (!opkg.mTrustedOverlay) {
4263            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4264                    opkg.baseCodePath + ": overlay not trusted");
4265            return false;
4266        }
4267        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4268        if (overlaySet == null) {
4269            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4270                    opkg.baseCodePath + " but target package has no known overlays");
4271            return false;
4272        }
4273        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4274        // TODO: generate idmap for split APKs
4275        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4276            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4277                    + opkg.baseCodePath);
4278            return false;
4279        }
4280        PackageParser.Package[] overlayArray =
4281            overlaySet.values().toArray(new PackageParser.Package[0]);
4282        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4283            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4284                return p1.mOverlayPriority - p2.mOverlayPriority;
4285            }
4286        };
4287        Arrays.sort(overlayArray, cmp);
4288
4289        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4290        int i = 0;
4291        for (PackageParser.Package p : overlayArray) {
4292            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4293        }
4294        return true;
4295    }
4296
4297    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4298        final File[] files = dir.listFiles();
4299        if (ArrayUtils.isEmpty(files)) {
4300            Log.d(TAG, "No files in app dir " + dir);
4301            return;
4302        }
4303
4304        if (DEBUG_PACKAGE_SCANNING) {
4305            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4306                    + " flags=0x" + Integer.toHexString(parseFlags));
4307        }
4308
4309        for (File file : files) {
4310            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4311                    && !PackageInstallerService.isStageName(file.getName());
4312            if (!isPackage) {
4313                // Ignore entries which are not packages
4314                continue;
4315            }
4316            try {
4317                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4318                        scanFlags, currentTime, null);
4319            } catch (PackageManagerException e) {
4320                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4321
4322                // Delete invalid userdata apps
4323                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4324                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4325                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4326                    if (file.isDirectory()) {
4327                        FileUtils.deleteContents(file);
4328                    }
4329                    file.delete();
4330                }
4331            }
4332        }
4333    }
4334
4335    private static File getSettingsProblemFile() {
4336        File dataDir = Environment.getDataDirectory();
4337        File systemDir = new File(dataDir, "system");
4338        File fname = new File(systemDir, "uiderrors.txt");
4339        return fname;
4340    }
4341
4342    static void reportSettingsProblem(int priority, String msg) {
4343        logCriticalInfo(priority, msg);
4344    }
4345
4346    static void logCriticalInfo(int priority, String msg) {
4347        Slog.println(priority, TAG, msg);
4348        EventLogTags.writePmCriticalInfo(msg);
4349        try {
4350            File fname = getSettingsProblemFile();
4351            FileOutputStream out = new FileOutputStream(fname, true);
4352            PrintWriter pw = new FastPrintWriter(out);
4353            SimpleDateFormat formatter = new SimpleDateFormat();
4354            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4355            pw.println(dateString + ": " + msg);
4356            pw.close();
4357            FileUtils.setPermissions(
4358                    fname.toString(),
4359                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4360                    -1, -1);
4361        } catch (java.io.IOException e) {
4362        }
4363    }
4364
4365    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4366            PackageParser.Package pkg, File srcFile, int parseFlags)
4367            throws PackageManagerException {
4368        if (ps != null
4369                && ps.codePath.equals(srcFile)
4370                && ps.timeStamp == srcFile.lastModified()
4371                && !isCompatSignatureUpdateNeeded(pkg)
4372                && !isRecoverSignatureUpdateNeeded(pkg)) {
4373            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4374            if (ps.signatures.mSignatures != null
4375                    && ps.signatures.mSignatures.length != 0
4376                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4377                // Optimization: reuse the existing cached certificates
4378                // if the package appears to be unchanged.
4379                pkg.mSignatures = ps.signatures.mSignatures;
4380                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4381                synchronized (mPackages) {
4382                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4383                }
4384                return;
4385            }
4386
4387            Slog.w(TAG, "PackageSetting for " + ps.name
4388                    + " is missing signatures.  Collecting certs again to recover them.");
4389        } else {
4390            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4391        }
4392
4393        try {
4394            pp.collectCertificates(pkg, parseFlags);
4395            pp.collectManifestDigest(pkg);
4396        } catch (PackageParserException e) {
4397            throw PackageManagerException.from(e);
4398        }
4399    }
4400
4401    /*
4402     *  Scan a package and return the newly parsed package.
4403     *  Returns null in case of errors and the error code is stored in mLastScanError
4404     */
4405    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4406            long currentTime, UserHandle user) throws PackageManagerException {
4407        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4408        parseFlags |= mDefParseFlags;
4409        PackageParser pp = new PackageParser();
4410        pp.setSeparateProcesses(mSeparateProcesses);
4411        pp.setOnlyCoreApps(mOnlyCore);
4412        pp.setDisplayMetrics(mMetrics);
4413
4414        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4415            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4416        }
4417
4418        final PackageParser.Package pkg;
4419        try {
4420            pkg = pp.parsePackage(scanFile, parseFlags);
4421        } catch (PackageParserException e) {
4422            throw PackageManagerException.from(e);
4423        }
4424
4425        PackageSetting ps = null;
4426        PackageSetting updatedPkg;
4427        // reader
4428        synchronized (mPackages) {
4429            // Look to see if we already know about this package.
4430            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4431            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4432                // This package has been renamed to its original name.  Let's
4433                // use that.
4434                ps = mSettings.peekPackageLPr(oldName);
4435            }
4436            // If there was no original package, see one for the real package name.
4437            if (ps == null) {
4438                ps = mSettings.peekPackageLPr(pkg.packageName);
4439            }
4440            // Check to see if this package could be hiding/updating a system
4441            // package.  Must look for it either under the original or real
4442            // package name depending on our state.
4443            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4444            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4445        }
4446        boolean updatedPkgBetter = false;
4447        // First check if this is a system package that may involve an update
4448        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4449            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4450            // it needs to drop FLAG_PRIVILEGED.
4451            if (locationIsPrivileged(scanFile)) {
4452                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4453            } else {
4454                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4455            }
4456
4457            if (ps != null && !ps.codePath.equals(scanFile)) {
4458                // The path has changed from what was last scanned...  check the
4459                // version of the new path against what we have stored to determine
4460                // what to do.
4461                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4462                if (pkg.mVersionCode <= ps.versionCode) {
4463                    // The system package has been updated and the code path does not match
4464                    // Ignore entry. Skip it.
4465                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4466                            + " ignored: updated version " + ps.versionCode
4467                            + " better than this " + pkg.mVersionCode);
4468                    if (!updatedPkg.codePath.equals(scanFile)) {
4469                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4470                                + ps.name + " changing from " + updatedPkg.codePathString
4471                                + " to " + scanFile);
4472                        updatedPkg.codePath = scanFile;
4473                        updatedPkg.codePathString = scanFile.toString();
4474                        updatedPkg.resourcePath = scanFile;
4475                        updatedPkg.resourcePathString = scanFile.toString();
4476                    }
4477                    updatedPkg.pkg = pkg;
4478                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4479                } else {
4480                    // The current app on the system partition is better than
4481                    // what we have updated to on the data partition; switch
4482                    // back to the system partition version.
4483                    // At this point, its safely assumed that package installation for
4484                    // apps in system partition will go through. If not there won't be a working
4485                    // version of the app
4486                    // writer
4487                    synchronized (mPackages) {
4488                        // Just remove the loaded entries from package lists.
4489                        mPackages.remove(ps.name);
4490                    }
4491
4492                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4493                            + " reverting from " + ps.codePathString
4494                            + ": new version " + pkg.mVersionCode
4495                            + " better than installed " + ps.versionCode);
4496
4497                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4498                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4499                            getAppDexInstructionSets(ps));
4500                    synchronized (mInstallLock) {
4501                        args.cleanUpResourcesLI();
4502                    }
4503                    synchronized (mPackages) {
4504                        mSettings.enableSystemPackageLPw(ps.name);
4505                    }
4506                    updatedPkgBetter = true;
4507                }
4508            }
4509        }
4510
4511        if (updatedPkg != null) {
4512            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4513            // initially
4514            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4515
4516            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4517            // flag set initially
4518            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4519                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4520            }
4521        }
4522
4523        // Verify certificates against what was last scanned
4524        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4525
4526        /*
4527         * A new system app appeared, but we already had a non-system one of the
4528         * same name installed earlier.
4529         */
4530        boolean shouldHideSystemApp = false;
4531        if (updatedPkg == null && ps != null
4532                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4533            /*
4534             * Check to make sure the signatures match first. If they don't,
4535             * wipe the installed application and its data.
4536             */
4537            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4538                    != PackageManager.SIGNATURE_MATCH) {
4539                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4540                        + " signatures don't match existing userdata copy; removing");
4541                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4542                ps = null;
4543            } else {
4544                /*
4545                 * If the newly-added system app is an older version than the
4546                 * already installed version, hide it. It will be scanned later
4547                 * and re-added like an update.
4548                 */
4549                if (pkg.mVersionCode <= ps.versionCode) {
4550                    shouldHideSystemApp = true;
4551                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4552                            + " but new version " + pkg.mVersionCode + " better than installed "
4553                            + ps.versionCode + "; hiding system");
4554                } else {
4555                    /*
4556                     * The newly found system app is a newer version that the
4557                     * one previously installed. Simply remove the
4558                     * already-installed application and replace it with our own
4559                     * while keeping the application data.
4560                     */
4561                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4562                            + " reverting from " + ps.codePathString + ": new version "
4563                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4564                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4565                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4566                            getAppDexInstructionSets(ps));
4567                    synchronized (mInstallLock) {
4568                        args.cleanUpResourcesLI();
4569                    }
4570                }
4571            }
4572        }
4573
4574        // The apk is forward locked (not public) if its code and resources
4575        // are kept in different files. (except for app in either system or
4576        // vendor path).
4577        // TODO grab this value from PackageSettings
4578        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4579            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4580                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4581            }
4582        }
4583
4584        // TODO: extend to support forward-locked splits
4585        String resourcePath = null;
4586        String baseResourcePath = null;
4587        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4588            if (ps != null && ps.resourcePathString != null) {
4589                resourcePath = ps.resourcePathString;
4590                baseResourcePath = ps.resourcePathString;
4591            } else {
4592                // Should not happen at all. Just log an error.
4593                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4594            }
4595        } else {
4596            resourcePath = pkg.codePath;
4597            baseResourcePath = pkg.baseCodePath;
4598        }
4599
4600        // Set application objects path explicitly.
4601        pkg.applicationInfo.setCodePath(pkg.codePath);
4602        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4603        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4604        pkg.applicationInfo.setResourcePath(resourcePath);
4605        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4606        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4607
4608        // Note that we invoke the following method only if we are about to unpack an application
4609        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4610                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4611
4612        /*
4613         * If the system app should be overridden by a previously installed
4614         * data, hide the system app now and let the /data/app scan pick it up
4615         * again.
4616         */
4617        if (shouldHideSystemApp) {
4618            synchronized (mPackages) {
4619                /*
4620                 * We have to grant systems permissions before we hide, because
4621                 * grantPermissions will assume the package update is trying to
4622                 * expand its permissions.
4623                 */
4624                grantPermissionsLPw(pkg, true, pkg.packageName);
4625                mSettings.disableSystemPackageLPw(pkg.packageName);
4626            }
4627        }
4628
4629        return scannedPkg;
4630    }
4631
4632    private static String fixProcessName(String defProcessName,
4633            String processName, int uid) {
4634        if (processName == null) {
4635            return defProcessName;
4636        }
4637        return processName;
4638    }
4639
4640    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4641            throws PackageManagerException {
4642        if (pkgSetting.signatures.mSignatures != null) {
4643            // Already existing package. Make sure signatures match
4644            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4645                    == PackageManager.SIGNATURE_MATCH;
4646            if (!match) {
4647                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4648                        == PackageManager.SIGNATURE_MATCH;
4649            }
4650            if (!match) {
4651                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4652                        == PackageManager.SIGNATURE_MATCH;
4653            }
4654            if (!match) {
4655                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4656                        + pkg.packageName + " signatures do not match the "
4657                        + "previously installed version; ignoring!");
4658            }
4659        }
4660
4661        // Check for shared user signatures
4662        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4663            // Already existing package. Make sure signatures match
4664            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4665                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4666            if (!match) {
4667                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4668                        == PackageManager.SIGNATURE_MATCH;
4669            }
4670            if (!match) {
4671                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4672                        == PackageManager.SIGNATURE_MATCH;
4673            }
4674            if (!match) {
4675                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4676                        "Package " + pkg.packageName
4677                        + " has no signatures that match those in shared user "
4678                        + pkgSetting.sharedUser.name + "; ignoring!");
4679            }
4680        }
4681    }
4682
4683    /**
4684     * Enforces that only the system UID or root's UID can call a method exposed
4685     * via Binder.
4686     *
4687     * @param message used as message if SecurityException is thrown
4688     * @throws SecurityException if the caller is not system or root
4689     */
4690    private static final void enforceSystemOrRoot(String message) {
4691        final int uid = Binder.getCallingUid();
4692        if (uid != Process.SYSTEM_UID && uid != 0) {
4693            throw new SecurityException(message);
4694        }
4695    }
4696
4697    @Override
4698    public void performBootDexOpt() {
4699        enforceSystemOrRoot("Only the system can request dexopt be performed");
4700
4701        // Before everything else, see whether we need to fstrim.
4702        try {
4703            IMountService ms = PackageHelper.getMountService();
4704            if (ms != null) {
4705                final boolean isUpgrade = isUpgrade();
4706                boolean doTrim = isUpgrade;
4707                if (doTrim) {
4708                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
4709                } else {
4710                    final long interval = android.provider.Settings.Global.getLong(
4711                            mContext.getContentResolver(),
4712                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
4713                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
4714                    if (interval > 0) {
4715                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
4716                        if (timeSinceLast > interval) {
4717                            doTrim = true;
4718                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
4719                                    + "; running immediately");
4720                        }
4721                    }
4722                }
4723                if (doTrim) {
4724                    if (!isFirstBoot()) {
4725                        try {
4726                            ActivityManagerNative.getDefault().showBootMessage(
4727                                    mContext.getResources().getString(
4728                                            R.string.android_upgrading_fstrim), true);
4729                        } catch (RemoteException e) {
4730                        }
4731                    }
4732                    ms.runMaintenance();
4733                }
4734            } else {
4735                Slog.e(TAG, "Mount service unavailable!");
4736            }
4737        } catch (RemoteException e) {
4738            // Can't happen; MountService is local
4739        }
4740
4741        final ArraySet<PackageParser.Package> pkgs;
4742        synchronized (mPackages) {
4743            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
4744        }
4745
4746        if (pkgs != null) {
4747            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4748            // in case the device runs out of space.
4749            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4750            // Give priority to core apps.
4751            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4752                PackageParser.Package pkg = it.next();
4753                if (pkg.coreApp) {
4754                    if (DEBUG_DEXOPT) {
4755                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4756                    }
4757                    sortedPkgs.add(pkg);
4758                    it.remove();
4759                }
4760            }
4761            // Give priority to system apps that listen for pre boot complete.
4762            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4763            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4764            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4765                PackageParser.Package pkg = it.next();
4766                if (pkgNames.contains(pkg.packageName)) {
4767                    if (DEBUG_DEXOPT) {
4768                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4769                    }
4770                    sortedPkgs.add(pkg);
4771                    it.remove();
4772                }
4773            }
4774            // Give priority to system apps.
4775            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4776                PackageParser.Package pkg = it.next();
4777                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4778                    if (DEBUG_DEXOPT) {
4779                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4780                    }
4781                    sortedPkgs.add(pkg);
4782                    it.remove();
4783                }
4784            }
4785            // Give priority to updated system apps.
4786            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4787                PackageParser.Package pkg = it.next();
4788                if (isUpdatedSystemApp(pkg)) {
4789                    if (DEBUG_DEXOPT) {
4790                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4791                    }
4792                    sortedPkgs.add(pkg);
4793                    it.remove();
4794                }
4795            }
4796            // Give priority to apps that listen for boot complete.
4797            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4798            pkgNames = getPackageNamesForIntent(intent);
4799            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4800                PackageParser.Package pkg = it.next();
4801                if (pkgNames.contains(pkg.packageName)) {
4802                    if (DEBUG_DEXOPT) {
4803                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4804                    }
4805                    sortedPkgs.add(pkg);
4806                    it.remove();
4807                }
4808            }
4809            // Filter out packages that aren't recently used.
4810            filterRecentlyUsedApps(pkgs);
4811            // Add all remaining apps.
4812            for (PackageParser.Package pkg : pkgs) {
4813                if (DEBUG_DEXOPT) {
4814                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4815                }
4816                sortedPkgs.add(pkg);
4817            }
4818
4819            // If we want to be lazy, filter everything that wasn't recently used.
4820            if (mLazyDexOpt) {
4821                filterRecentlyUsedApps(sortedPkgs);
4822            }
4823
4824            int i = 0;
4825            int total = sortedPkgs.size();
4826            File dataDir = Environment.getDataDirectory();
4827            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4828            if (lowThreshold == 0) {
4829                throw new IllegalStateException("Invalid low memory threshold");
4830            }
4831            for (PackageParser.Package pkg : sortedPkgs) {
4832                long usableSpace = dataDir.getUsableSpace();
4833                if (usableSpace < lowThreshold) {
4834                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4835                    break;
4836                }
4837                performBootDexOpt(pkg, ++i, total);
4838            }
4839        }
4840    }
4841
4842    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4843        // Filter out packages that aren't recently used.
4844        //
4845        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4846        // should do a full dexopt.
4847        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4848            int total = pkgs.size();
4849            int skipped = 0;
4850            long now = System.currentTimeMillis();
4851            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4852                PackageParser.Package pkg = i.next();
4853                long then = pkg.mLastPackageUsageTimeInMills;
4854                if (then + mDexOptLRUThresholdInMills < now) {
4855                    if (DEBUG_DEXOPT) {
4856                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4857                              ((then == 0) ? "never" : new Date(then)));
4858                    }
4859                    i.remove();
4860                    skipped++;
4861                }
4862            }
4863            if (DEBUG_DEXOPT) {
4864                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4865            }
4866        }
4867    }
4868
4869    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4870        List<ResolveInfo> ris = null;
4871        try {
4872            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4873                    intent, null, 0, UserHandle.USER_OWNER);
4874        } catch (RemoteException e) {
4875        }
4876        ArraySet<String> pkgNames = new ArraySet<String>();
4877        if (ris != null) {
4878            for (ResolveInfo ri : ris) {
4879                pkgNames.add(ri.activityInfo.packageName);
4880            }
4881        }
4882        return pkgNames;
4883    }
4884
4885    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4886        if (DEBUG_DEXOPT) {
4887            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4888        }
4889        if (!isFirstBoot()) {
4890            try {
4891                ActivityManagerNative.getDefault().showBootMessage(
4892                        mContext.getResources().getString(R.string.android_upgrading_apk,
4893                                curr, total), true);
4894            } catch (RemoteException e) {
4895            }
4896        }
4897        PackageParser.Package p = pkg;
4898        synchronized (mInstallLock) {
4899            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
4900                    false /* force dex */, false /* defer */, true /* include dependencies */);
4901        }
4902    }
4903
4904    @Override
4905    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4906        return performDexOpt(packageName, instructionSet, false);
4907    }
4908
4909    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4910        if (info.primaryCpuAbi == null) {
4911            return getPreferredInstructionSet();
4912        }
4913
4914        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4915    }
4916
4917    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4918        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4919        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4920        if (!dexopt && !updateUsage) {
4921            // We aren't going to dexopt or update usage, so bail early.
4922            return false;
4923        }
4924        PackageParser.Package p;
4925        final String targetInstructionSet;
4926        synchronized (mPackages) {
4927            p = mPackages.get(packageName);
4928            if (p == null) {
4929                return false;
4930            }
4931            if (updateUsage) {
4932                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4933            }
4934            mPackageUsage.write(false);
4935            if (!dexopt) {
4936                // We aren't going to dexopt, so bail early.
4937                return false;
4938            }
4939
4940            targetInstructionSet = instructionSet != null ? instructionSet :
4941                    getPrimaryInstructionSet(p.applicationInfo);
4942            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4943                return false;
4944            }
4945        }
4946
4947        synchronized (mInstallLock) {
4948            final String[] instructionSets = new String[] { targetInstructionSet };
4949            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
4950                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
4951            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
4952        }
4953    }
4954
4955    public ArraySet<String> getPackagesThatNeedDexOpt() {
4956        ArraySet<String> pkgs = null;
4957        synchronized (mPackages) {
4958            for (PackageParser.Package p : mPackages.values()) {
4959                if (DEBUG_DEXOPT) {
4960                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4961                }
4962                if (!p.mDexOptPerformed.isEmpty()) {
4963                    continue;
4964                }
4965                if (pkgs == null) {
4966                    pkgs = new ArraySet<String>();
4967                }
4968                pkgs.add(p.packageName);
4969            }
4970        }
4971        return pkgs;
4972    }
4973
4974    public void shutdown() {
4975        mPackageUsage.write(true);
4976    }
4977
4978    @Override
4979    public void forceDexOpt(String packageName) {
4980        enforceSystemOrRoot("forceDexOpt");
4981
4982        PackageParser.Package pkg;
4983        synchronized (mPackages) {
4984            pkg = mPackages.get(packageName);
4985            if (pkg == null) {
4986                throw new IllegalArgumentException("Missing package: " + packageName);
4987            }
4988        }
4989
4990        synchronized (mInstallLock) {
4991            final String[] instructionSets = new String[] {
4992                    getPrimaryInstructionSet(pkg.applicationInfo) };
4993            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
4994                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
4995            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
4996                throw new IllegalStateException("Failed to dexopt: " + res);
4997            }
4998        }
4999    }
5000
5001    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5002        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5003            Slog.w(TAG, "Unable to update from " + oldPkg.name
5004                    + " to " + newPkg.packageName
5005                    + ": old package not in system partition");
5006            return false;
5007        } else if (mPackages.get(oldPkg.name) != null) {
5008            Slog.w(TAG, "Unable to update from " + oldPkg.name
5009                    + " to " + newPkg.packageName
5010                    + ": old package still exists");
5011            return false;
5012        }
5013        return true;
5014    }
5015
5016    private File getDataPathForPackage(String packageName, int userId) {
5017        /*
5018         * Until we fully support multiple users, return the directory we
5019         * previously would have. The PackageManagerTests will need to be
5020         * revised when this is changed back..
5021         */
5022        if (userId == 0) {
5023            return new File(mAppDataDir, packageName);
5024        } else {
5025            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5026                + File.separator + packageName);
5027        }
5028    }
5029
5030    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5031        int[] users = sUserManager.getUserIds();
5032        int res = mInstaller.install(packageName, uid, uid, seinfo);
5033        if (res < 0) {
5034            return res;
5035        }
5036        for (int user : users) {
5037            if (user != 0) {
5038                res = mInstaller.createUserData(packageName,
5039                        UserHandle.getUid(user, uid), user, seinfo);
5040                if (res < 0) {
5041                    return res;
5042                }
5043            }
5044        }
5045        return res;
5046    }
5047
5048    private int removeDataDirsLI(String packageName) {
5049        int[] users = sUserManager.getUserIds();
5050        int res = 0;
5051        for (int user : users) {
5052            int resInner = mInstaller.remove(packageName, user);
5053            if (resInner < 0) {
5054                res = resInner;
5055            }
5056        }
5057
5058        return res;
5059    }
5060
5061    private int deleteCodeCacheDirsLI(String packageName) {
5062        int[] users = sUserManager.getUserIds();
5063        int res = 0;
5064        for (int user : users) {
5065            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5066            if (resInner < 0) {
5067                res = resInner;
5068            }
5069        }
5070        return res;
5071    }
5072
5073    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5074            PackageParser.Package changingLib) {
5075        if (file.path != null) {
5076            usesLibraryFiles.add(file.path);
5077            return;
5078        }
5079        PackageParser.Package p = mPackages.get(file.apk);
5080        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5081            // If we are doing this while in the middle of updating a library apk,
5082            // then we need to make sure to use that new apk for determining the
5083            // dependencies here.  (We haven't yet finished committing the new apk
5084            // to the package manager state.)
5085            if (p == null || p.packageName.equals(changingLib.packageName)) {
5086                p = changingLib;
5087            }
5088        }
5089        if (p != null) {
5090            usesLibraryFiles.addAll(p.getAllCodePaths());
5091        }
5092    }
5093
5094    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5095            PackageParser.Package changingLib) throws PackageManagerException {
5096        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5097            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5098            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5099            for (int i=0; i<N; i++) {
5100                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5101                if (file == null) {
5102                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5103                            "Package " + pkg.packageName + " requires unavailable shared library "
5104                            + pkg.usesLibraries.get(i) + "; failing!");
5105                }
5106                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5107            }
5108            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5109            for (int i=0; i<N; i++) {
5110                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5111                if (file == null) {
5112                    Slog.w(TAG, "Package " + pkg.packageName
5113                            + " desires unavailable shared library "
5114                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5115                } else {
5116                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5117                }
5118            }
5119            N = usesLibraryFiles.size();
5120            if (N > 0) {
5121                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5122            } else {
5123                pkg.usesLibraryFiles = null;
5124            }
5125        }
5126    }
5127
5128    private static boolean hasString(List<String> list, List<String> which) {
5129        if (list == null) {
5130            return false;
5131        }
5132        for (int i=list.size()-1; i>=0; i--) {
5133            for (int j=which.size()-1; j>=0; j--) {
5134                if (which.get(j).equals(list.get(i))) {
5135                    return true;
5136                }
5137            }
5138        }
5139        return false;
5140    }
5141
5142    private void updateAllSharedLibrariesLPw() {
5143        for (PackageParser.Package pkg : mPackages.values()) {
5144            try {
5145                updateSharedLibrariesLPw(pkg, null);
5146            } catch (PackageManagerException e) {
5147                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5148            }
5149        }
5150    }
5151
5152    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5153            PackageParser.Package changingPkg) {
5154        ArrayList<PackageParser.Package> res = null;
5155        for (PackageParser.Package pkg : mPackages.values()) {
5156            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5157                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5158                if (res == null) {
5159                    res = new ArrayList<PackageParser.Package>();
5160                }
5161                res.add(pkg);
5162                try {
5163                    updateSharedLibrariesLPw(pkg, changingPkg);
5164                } catch (PackageManagerException e) {
5165                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5166                }
5167            }
5168        }
5169        return res;
5170    }
5171
5172    /**
5173     * Derive the value of the {@code cpuAbiOverride} based on the provided
5174     * value and an optional stored value from the package settings.
5175     */
5176    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5177        String cpuAbiOverride = null;
5178
5179        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5180            cpuAbiOverride = null;
5181        } else if (abiOverride != null) {
5182            cpuAbiOverride = abiOverride;
5183        } else if (settings != null) {
5184            cpuAbiOverride = settings.cpuAbiOverrideString;
5185        }
5186
5187        return cpuAbiOverride;
5188    }
5189
5190    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5191            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5192        boolean success = false;
5193        try {
5194            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5195                    currentTime, user);
5196            success = true;
5197            return res;
5198        } finally {
5199            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5200                removeDataDirsLI(pkg.packageName);
5201            }
5202        }
5203    }
5204
5205    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5206            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5207        final File scanFile = new File(pkg.codePath);
5208        if (pkg.applicationInfo.getCodePath() == null ||
5209                pkg.applicationInfo.getResourcePath() == null) {
5210            // Bail out. The resource and code paths haven't been set.
5211            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5212                    "Code and resource paths haven't been set correctly");
5213        }
5214
5215        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5216            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5217        } else {
5218            // Only allow system apps to be flagged as core apps.
5219            pkg.coreApp = false;
5220        }
5221
5222        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5223            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5224        }
5225
5226        if (mCustomResolverComponentName != null &&
5227                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5228            setUpCustomResolverActivity(pkg);
5229        }
5230
5231        if (pkg.packageName.equals("android")) {
5232            synchronized (mPackages) {
5233                if (mAndroidApplication != null) {
5234                    Slog.w(TAG, "*************************************************");
5235                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5236                    Slog.w(TAG, " file=" + scanFile);
5237                    Slog.w(TAG, "*************************************************");
5238                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5239                            "Core android package being redefined.  Skipping.");
5240                }
5241
5242                // Set up information for our fall-back user intent resolution activity.
5243                mPlatformPackage = pkg;
5244                pkg.mVersionCode = mSdkVersion;
5245                mAndroidApplication = pkg.applicationInfo;
5246
5247                if (!mResolverReplaced) {
5248                    mResolveActivity.applicationInfo = mAndroidApplication;
5249                    mResolveActivity.name = ResolverActivity.class.getName();
5250                    mResolveActivity.packageName = mAndroidApplication.packageName;
5251                    mResolveActivity.processName = "system:ui";
5252                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5253                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5254                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5255                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5256                    mResolveActivity.exported = true;
5257                    mResolveActivity.enabled = true;
5258                    mResolveInfo.activityInfo = mResolveActivity;
5259                    mResolveInfo.priority = 0;
5260                    mResolveInfo.preferredOrder = 0;
5261                    mResolveInfo.match = 0;
5262                    mResolveComponentName = new ComponentName(
5263                            mAndroidApplication.packageName, mResolveActivity.name);
5264                }
5265            }
5266        }
5267
5268        if (DEBUG_PACKAGE_SCANNING) {
5269            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5270                Log.d(TAG, "Scanning package " + pkg.packageName);
5271        }
5272
5273        if (mPackages.containsKey(pkg.packageName)
5274                || mSharedLibraries.containsKey(pkg.packageName)) {
5275            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5276                    "Application package " + pkg.packageName
5277                    + " already installed.  Skipping duplicate.");
5278        }
5279
5280        // Initialize package source and resource directories
5281        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5282        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5283
5284        SharedUserSetting suid = null;
5285        PackageSetting pkgSetting = null;
5286
5287        if (!isSystemApp(pkg)) {
5288            // Only system apps can use these features.
5289            pkg.mOriginalPackages = null;
5290            pkg.mRealPackage = null;
5291            pkg.mAdoptPermissions = null;
5292        }
5293
5294        // writer
5295        synchronized (mPackages) {
5296            if (pkg.mSharedUserId != null) {
5297                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5298                if (suid == null) {
5299                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5300                            "Creating application package " + pkg.packageName
5301                            + " for shared user failed");
5302                }
5303                if (DEBUG_PACKAGE_SCANNING) {
5304                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5305                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5306                                + "): packages=" + suid.packages);
5307                }
5308            }
5309
5310            // Check if we are renaming from an original package name.
5311            PackageSetting origPackage = null;
5312            String realName = null;
5313            if (pkg.mOriginalPackages != null) {
5314                // This package may need to be renamed to a previously
5315                // installed name.  Let's check on that...
5316                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5317                if (pkg.mOriginalPackages.contains(renamed)) {
5318                    // This package had originally been installed as the
5319                    // original name, and we have already taken care of
5320                    // transitioning to the new one.  Just update the new
5321                    // one to continue using the old name.
5322                    realName = pkg.mRealPackage;
5323                    if (!pkg.packageName.equals(renamed)) {
5324                        // Callers into this function may have already taken
5325                        // care of renaming the package; only do it here if
5326                        // it is not already done.
5327                        pkg.setPackageName(renamed);
5328                    }
5329
5330                } else {
5331                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5332                        if ((origPackage = mSettings.peekPackageLPr(
5333                                pkg.mOriginalPackages.get(i))) != null) {
5334                            // We do have the package already installed under its
5335                            // original name...  should we use it?
5336                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5337                                // New package is not compatible with original.
5338                                origPackage = null;
5339                                continue;
5340                            } else if (origPackage.sharedUser != null) {
5341                                // Make sure uid is compatible between packages.
5342                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5343                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5344                                            + " to " + pkg.packageName + ": old uid "
5345                                            + origPackage.sharedUser.name
5346                                            + " differs from " + pkg.mSharedUserId);
5347                                    origPackage = null;
5348                                    continue;
5349                                }
5350                            } else {
5351                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5352                                        + pkg.packageName + " to old name " + origPackage.name);
5353                            }
5354                            break;
5355                        }
5356                    }
5357                }
5358            }
5359
5360            if (mTransferedPackages.contains(pkg.packageName)) {
5361                Slog.w(TAG, "Package " + pkg.packageName
5362                        + " was transferred to another, but its .apk remains");
5363            }
5364
5365            // Just create the setting, don't add it yet. For already existing packages
5366            // the PkgSetting exists already and doesn't have to be created.
5367            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5368                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5369                    pkg.applicationInfo.primaryCpuAbi,
5370                    pkg.applicationInfo.secondaryCpuAbi,
5371                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5372                    user, false);
5373            if (pkgSetting == null) {
5374                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5375                        "Creating application package " + pkg.packageName + " failed");
5376            }
5377
5378            if (pkgSetting.origPackage != null) {
5379                // If we are first transitioning from an original package,
5380                // fix up the new package's name now.  We need to do this after
5381                // looking up the package under its new name, so getPackageLP
5382                // can take care of fiddling things correctly.
5383                pkg.setPackageName(origPackage.name);
5384
5385                // File a report about this.
5386                String msg = "New package " + pkgSetting.realName
5387                        + " renamed to replace old package " + pkgSetting.name;
5388                reportSettingsProblem(Log.WARN, msg);
5389
5390                // Make a note of it.
5391                mTransferedPackages.add(origPackage.name);
5392
5393                // No longer need to retain this.
5394                pkgSetting.origPackage = null;
5395            }
5396
5397            if (realName != null) {
5398                // Make a note of it.
5399                mTransferedPackages.add(pkg.packageName);
5400            }
5401
5402            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5403                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5404            }
5405
5406            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5407                // Check all shared libraries and map to their actual file path.
5408                // We only do this here for apps not on a system dir, because those
5409                // are the only ones that can fail an install due to this.  We
5410                // will take care of the system apps by updating all of their
5411                // library paths after the scan is done.
5412                updateSharedLibrariesLPw(pkg, null);
5413            }
5414
5415            if (mFoundPolicyFile) {
5416                SELinuxMMAC.assignSeinfoValue(pkg);
5417            }
5418
5419            pkg.applicationInfo.uid = pkgSetting.appId;
5420            pkg.mExtras = pkgSetting;
5421            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5422                try {
5423                    verifySignaturesLP(pkgSetting, pkg);
5424                    // We just determined the app is signed correctly, so bring
5425                    // over the latest parsed certs.
5426                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5427                } catch (PackageManagerException e) {
5428                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5429                        throw e;
5430                    }
5431                    // The signature has changed, but this package is in the system
5432                    // image...  let's recover!
5433                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5434                    // However...  if this package is part of a shared user, but it
5435                    // doesn't match the signature of the shared user, let's fail.
5436                    // What this means is that you can't change the signatures
5437                    // associated with an overall shared user, which doesn't seem all
5438                    // that unreasonable.
5439                    if (pkgSetting.sharedUser != null) {
5440                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5441                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5442                            throw new PackageManagerException(
5443                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5444                                            "Signature mismatch for shared user : "
5445                                            + pkgSetting.sharedUser);
5446                        }
5447                    }
5448                    // File a report about this.
5449                    String msg = "System package " + pkg.packageName
5450                        + " signature changed; retaining data.";
5451                    reportSettingsProblem(Log.WARN, msg);
5452                }
5453            } else {
5454                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5455                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5456                            + pkg.packageName + " upgrade keys do not match the "
5457                            + "previously installed version");
5458                } else {
5459                    // We just determined the app is signed correctly, so bring
5460                    // over the latest parsed certs.
5461                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5462                }
5463            }
5464            // Verify that this new package doesn't have any content providers
5465            // that conflict with existing packages.  Only do this if the
5466            // package isn't already installed, since we don't want to break
5467            // things that are installed.
5468            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5469                final int N = pkg.providers.size();
5470                int i;
5471                for (i=0; i<N; i++) {
5472                    PackageParser.Provider p = pkg.providers.get(i);
5473                    if (p.info.authority != null) {
5474                        String names[] = p.info.authority.split(";");
5475                        for (int j = 0; j < names.length; j++) {
5476                            if (mProvidersByAuthority.containsKey(names[j])) {
5477                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5478                                final String otherPackageName =
5479                                        ((other != null && other.getComponentName() != null) ?
5480                                                other.getComponentName().getPackageName() : "?");
5481                                throw new PackageManagerException(
5482                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5483                                                "Can't install because provider name " + names[j]
5484                                                + " (in package " + pkg.applicationInfo.packageName
5485                                                + ") is already used by " + otherPackageName);
5486                            }
5487                        }
5488                    }
5489                }
5490            }
5491
5492            if (pkg.mAdoptPermissions != null) {
5493                // This package wants to adopt ownership of permissions from
5494                // another package.
5495                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5496                    final String origName = pkg.mAdoptPermissions.get(i);
5497                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5498                    if (orig != null) {
5499                        if (verifyPackageUpdateLPr(orig, pkg)) {
5500                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5501                                    + pkg.packageName);
5502                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5503                        }
5504                    }
5505                }
5506            }
5507        }
5508
5509        final String pkgName = pkg.packageName;
5510
5511        final long scanFileTime = scanFile.lastModified();
5512        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5513        pkg.applicationInfo.processName = fixProcessName(
5514                pkg.applicationInfo.packageName,
5515                pkg.applicationInfo.processName,
5516                pkg.applicationInfo.uid);
5517
5518        File dataPath;
5519        if (mPlatformPackage == pkg) {
5520            // The system package is special.
5521            dataPath = new File(Environment.getDataDirectory(), "system");
5522
5523            pkg.applicationInfo.dataDir = dataPath.getPath();
5524
5525        } else {
5526            // This is a normal package, need to make its data directory.
5527            dataPath = getDataPathForPackage(pkg.packageName, 0);
5528
5529            boolean uidError = false;
5530            if (dataPath.exists()) {
5531                int currentUid = 0;
5532                try {
5533                    StructStat stat = Os.stat(dataPath.getPath());
5534                    currentUid = stat.st_uid;
5535                } catch (ErrnoException e) {
5536                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5537                }
5538
5539                // If we have mismatched owners for the data path, we have a problem.
5540                if (currentUid != pkg.applicationInfo.uid) {
5541                    boolean recovered = false;
5542                    if (currentUid == 0) {
5543                        // The directory somehow became owned by root.  Wow.
5544                        // This is probably because the system was stopped while
5545                        // installd was in the middle of messing with its libs
5546                        // directory.  Ask installd to fix that.
5547                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5548                                pkg.applicationInfo.uid);
5549                        if (ret >= 0) {
5550                            recovered = true;
5551                            String msg = "Package " + pkg.packageName
5552                                    + " unexpectedly changed to uid 0; recovered to " +
5553                                    + pkg.applicationInfo.uid;
5554                            reportSettingsProblem(Log.WARN, msg);
5555                        }
5556                    }
5557                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5558                            || (scanFlags&SCAN_BOOTING) != 0)) {
5559                        // If this is a system app, we can at least delete its
5560                        // current data so the application will still work.
5561                        int ret = removeDataDirsLI(pkgName);
5562                        if (ret >= 0) {
5563                            // TODO: Kill the processes first
5564                            // Old data gone!
5565                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5566                                    ? "System package " : "Third party package ";
5567                            String msg = prefix + pkg.packageName
5568                                    + " has changed from uid: "
5569                                    + currentUid + " to "
5570                                    + pkg.applicationInfo.uid + "; old data erased";
5571                            reportSettingsProblem(Log.WARN, msg);
5572                            recovered = true;
5573
5574                            // And now re-install the app.
5575                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5576                                                   pkg.applicationInfo.seinfo);
5577                            if (ret == -1) {
5578                                // Ack should not happen!
5579                                msg = prefix + pkg.packageName
5580                                        + " could not have data directory re-created after delete.";
5581                                reportSettingsProblem(Log.WARN, msg);
5582                                throw new PackageManagerException(
5583                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5584                            }
5585                        }
5586                        if (!recovered) {
5587                            mHasSystemUidErrors = true;
5588                        }
5589                    } else if (!recovered) {
5590                        // If we allow this install to proceed, we will be broken.
5591                        // Abort, abort!
5592                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5593                                "scanPackageLI");
5594                    }
5595                    if (!recovered) {
5596                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5597                            + pkg.applicationInfo.uid + "/fs_"
5598                            + currentUid;
5599                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5600                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5601                        String msg = "Package " + pkg.packageName
5602                                + " has mismatched uid: "
5603                                + currentUid + " on disk, "
5604                                + pkg.applicationInfo.uid + " in settings";
5605                        // writer
5606                        synchronized (mPackages) {
5607                            mSettings.mReadMessages.append(msg);
5608                            mSettings.mReadMessages.append('\n');
5609                            uidError = true;
5610                            if (!pkgSetting.uidError) {
5611                                reportSettingsProblem(Log.ERROR, msg);
5612                            }
5613                        }
5614                    }
5615                }
5616                pkg.applicationInfo.dataDir = dataPath.getPath();
5617                if (mShouldRestoreconData) {
5618                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5619                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5620                                pkg.applicationInfo.uid);
5621                }
5622            } else {
5623                if (DEBUG_PACKAGE_SCANNING) {
5624                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5625                        Log.v(TAG, "Want this data dir: " + dataPath);
5626                }
5627                //invoke installer to do the actual installation
5628                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5629                                           pkg.applicationInfo.seinfo);
5630                if (ret < 0) {
5631                    // Error from installer
5632                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5633                            "Unable to create data dirs [errorCode=" + ret + "]");
5634                }
5635
5636                if (dataPath.exists()) {
5637                    pkg.applicationInfo.dataDir = dataPath.getPath();
5638                } else {
5639                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5640                    pkg.applicationInfo.dataDir = null;
5641                }
5642            }
5643
5644            pkgSetting.uidError = uidError;
5645        }
5646
5647        final String path = scanFile.getPath();
5648        final String codePath = pkg.applicationInfo.getCodePath();
5649        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5650        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5651            setBundledAppAbisAndRoots(pkg, pkgSetting);
5652
5653            // If we haven't found any native libraries for the app, check if it has
5654            // renderscript code. We'll need to force the app to 32 bit if it has
5655            // renderscript bitcode.
5656            if (pkg.applicationInfo.primaryCpuAbi == null
5657                    && pkg.applicationInfo.secondaryCpuAbi == null
5658                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5659                NativeLibraryHelper.Handle handle = null;
5660                try {
5661                    handle = NativeLibraryHelper.Handle.create(scanFile);
5662                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5663                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5664                    }
5665                } catch (IOException ioe) {
5666                    Slog.w(TAG, "Error scanning system app : " + ioe);
5667                } finally {
5668                    IoUtils.closeQuietly(handle);
5669                }
5670            }
5671
5672            setNativeLibraryPaths(pkg);
5673        } else {
5674            // TODO: We can probably be smarter about this stuff. For installed apps,
5675            // we can calculate this information at install time once and for all. For
5676            // system apps, we can probably assume that this information doesn't change
5677            // after the first boot scan. As things stand, we do lots of unnecessary work.
5678
5679            // Give ourselves some initial paths; we'll come back for another
5680            // pass once we've determined ABI below.
5681            setNativeLibraryPaths(pkg);
5682
5683            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
5684            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5685            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5686
5687            NativeLibraryHelper.Handle handle = null;
5688            try {
5689                handle = NativeLibraryHelper.Handle.create(scanFile);
5690                // TODO(multiArch): This can be null for apps that didn't go through the
5691                // usual installation process. We can calculate it again, like we
5692                // do during install time.
5693                //
5694                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5695                // unnecessary.
5696                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5697
5698                // Null out the abis so that they can be recalculated.
5699                pkg.applicationInfo.primaryCpuAbi = null;
5700                pkg.applicationInfo.secondaryCpuAbi = null;
5701                if (isMultiArch(pkg.applicationInfo)) {
5702                    // Warn if we've set an abiOverride for multi-lib packages..
5703                    // By definition, we need to copy both 32 and 64 bit libraries for
5704                    // such packages.
5705                    if (pkg.cpuAbiOverride != null
5706                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5707                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5708                    }
5709
5710                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5711                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5712                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5713                        if (isAsec) {
5714                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5715                        } else {
5716                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5717                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5718                                    useIsaSpecificSubdirs);
5719                        }
5720                    }
5721
5722                    maybeThrowExceptionForMultiArchCopy(
5723                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5724
5725                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5726                        if (isAsec) {
5727                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5728                        } else {
5729                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5730                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5731                                    useIsaSpecificSubdirs);
5732                        }
5733                    }
5734
5735                    maybeThrowExceptionForMultiArchCopy(
5736                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5737
5738                    if (abi64 >= 0) {
5739                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5740                    }
5741
5742                    if (abi32 >= 0) {
5743                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5744                        if (abi64 >= 0) {
5745                            pkg.applicationInfo.secondaryCpuAbi = abi;
5746                        } else {
5747                            pkg.applicationInfo.primaryCpuAbi = abi;
5748                        }
5749                    }
5750                } else {
5751                    String[] abiList = (cpuAbiOverride != null) ?
5752                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5753
5754                    // Enable gross and lame hacks for apps that are built with old
5755                    // SDK tools. We must scan their APKs for renderscript bitcode and
5756                    // not launch them if it's present. Don't bother checking on devices
5757                    // that don't have 64 bit support.
5758                    boolean needsRenderScriptOverride = false;
5759                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5760                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5761                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5762                        needsRenderScriptOverride = true;
5763                    }
5764
5765                    final int copyRet;
5766                    if (isAsec) {
5767                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5768                    } else {
5769                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5770                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5771                    }
5772
5773                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5774                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5775                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5776                    }
5777
5778                    if (copyRet >= 0) {
5779                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5780                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5781                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5782                    } else if (needsRenderScriptOverride) {
5783                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5784                    }
5785                }
5786            } catch (IOException ioe) {
5787                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5788            } finally {
5789                IoUtils.closeQuietly(handle);
5790            }
5791
5792            // Now that we've calculated the ABIs and determined if it's an internal app,
5793            // we will go ahead and populate the nativeLibraryPath.
5794            setNativeLibraryPaths(pkg);
5795
5796            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5797            final int[] userIds = sUserManager.getUserIds();
5798            synchronized (mInstallLock) {
5799                // Create a native library symlink only if we have native libraries
5800                // and if the native libraries are 32 bit libraries. We do not provide
5801                // this symlink for 64 bit libraries.
5802                if (pkg.applicationInfo.primaryCpuAbi != null &&
5803                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5804                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5805                    for (int userId : userIds) {
5806                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5807                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5808                                    "Failed linking native library dir (user=" + userId + ")");
5809                        }
5810                    }
5811                }
5812            }
5813        }
5814
5815        // This is a special case for the "system" package, where the ABI is
5816        // dictated by the zygote configuration (and init.rc). We should keep track
5817        // of this ABI so that we can deal with "normal" applications that run under
5818        // the same UID correctly.
5819        if (mPlatformPackage == pkg) {
5820            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5821                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5822        }
5823
5824        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5825        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5826        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5827        // Copy the derived override back to the parsed package, so that we can
5828        // update the package settings accordingly.
5829        pkg.cpuAbiOverride = cpuAbiOverride;
5830
5831        if (DEBUG_ABI_SELECTION) {
5832            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5833                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5834                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5835        }
5836
5837        // Push the derived path down into PackageSettings so we know what to
5838        // clean up at uninstall time.
5839        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5840
5841        if (DEBUG_ABI_SELECTION) {
5842            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5843                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5844                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5845        }
5846
5847        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5848            // We don't do this here during boot because we can do it all
5849            // at once after scanning all existing packages.
5850            //
5851            // We also do this *before* we perform dexopt on this package, so that
5852            // we can avoid redundant dexopts, and also to make sure we've got the
5853            // code and package path correct.
5854            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5855                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5856        }
5857
5858        if ((scanFlags & SCAN_NO_DEX) == 0) {
5859            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
5860                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
5861            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5862                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5863            }
5864        }
5865
5866        if (mFactoryTest && pkg.requestedPermissions.contains(
5867                android.Manifest.permission.FACTORY_TEST)) {
5868            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5869        }
5870
5871        ArrayList<PackageParser.Package> clientLibPkgs = null;
5872
5873        // writer
5874        synchronized (mPackages) {
5875            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5876                // Only system apps can add new shared libraries.
5877                if (pkg.libraryNames != null) {
5878                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5879                        String name = pkg.libraryNames.get(i);
5880                        boolean allowed = false;
5881                        if (isUpdatedSystemApp(pkg)) {
5882                            // New library entries can only be added through the
5883                            // system image.  This is important to get rid of a lot
5884                            // of nasty edge cases: for example if we allowed a non-
5885                            // system update of the app to add a library, then uninstalling
5886                            // the update would make the library go away, and assumptions
5887                            // we made such as through app install filtering would now
5888                            // have allowed apps on the device which aren't compatible
5889                            // with it.  Better to just have the restriction here, be
5890                            // conservative, and create many fewer cases that can negatively
5891                            // impact the user experience.
5892                            final PackageSetting sysPs = mSettings
5893                                    .getDisabledSystemPkgLPr(pkg.packageName);
5894                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5895                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5896                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5897                                        allowed = true;
5898                                        allowed = true;
5899                                        break;
5900                                    }
5901                                }
5902                            }
5903                        } else {
5904                            allowed = true;
5905                        }
5906                        if (allowed) {
5907                            if (!mSharedLibraries.containsKey(name)) {
5908                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5909                            } else if (!name.equals(pkg.packageName)) {
5910                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5911                                        + name + " already exists; skipping");
5912                            }
5913                        } else {
5914                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5915                                    + name + " that is not declared on system image; skipping");
5916                        }
5917                    }
5918                    if ((scanFlags&SCAN_BOOTING) == 0) {
5919                        // If we are not booting, we need to update any applications
5920                        // that are clients of our shared library.  If we are booting,
5921                        // this will all be done once the scan is complete.
5922                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5923                    }
5924                }
5925            }
5926        }
5927
5928        // We also need to dexopt any apps that are dependent on this library.  Note that
5929        // if these fail, we should abort the install since installing the library will
5930        // result in some apps being broken.
5931        if (clientLibPkgs != null) {
5932            if ((scanFlags & SCAN_NO_DEX) == 0) {
5933                for (int i = 0; i < clientLibPkgs.size(); i++) {
5934                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5935                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
5936                            null /* instruction sets */, forceDex,
5937                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
5938                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5939                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5940                                "scanPackageLI failed to dexopt clientLibPkgs");
5941                    }
5942                }
5943            }
5944        }
5945
5946        // Request the ActivityManager to kill the process(only for existing packages)
5947        // so that we do not end up in a confused state while the user is still using the older
5948        // version of the application while the new one gets installed.
5949        if ((scanFlags & SCAN_REPLACING) != 0) {
5950            killApplication(pkg.applicationInfo.packageName,
5951                        pkg.applicationInfo.uid, "update pkg");
5952        }
5953
5954        // Also need to kill any apps that are dependent on the library.
5955        if (clientLibPkgs != null) {
5956            for (int i=0; i<clientLibPkgs.size(); i++) {
5957                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5958                killApplication(clientPkg.applicationInfo.packageName,
5959                        clientPkg.applicationInfo.uid, "update lib");
5960            }
5961        }
5962
5963        // writer
5964        synchronized (mPackages) {
5965            // We don't expect installation to fail beyond this point
5966
5967            // Add the new setting to mSettings
5968            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5969            // Add the new setting to mPackages
5970            mPackages.put(pkg.applicationInfo.packageName, pkg);
5971            // Make sure we don't accidentally delete its data.
5972            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5973            while (iter.hasNext()) {
5974                PackageCleanItem item = iter.next();
5975                if (pkgName.equals(item.packageName)) {
5976                    iter.remove();
5977                }
5978            }
5979
5980            // Take care of first install / last update times.
5981            if (currentTime != 0) {
5982                if (pkgSetting.firstInstallTime == 0) {
5983                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5984                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5985                    pkgSetting.lastUpdateTime = currentTime;
5986                }
5987            } else if (pkgSetting.firstInstallTime == 0) {
5988                // We need *something*.  Take time time stamp of the file.
5989                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5990            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5991                if (scanFileTime != pkgSetting.timeStamp) {
5992                    // A package on the system image has changed; consider this
5993                    // to be an update.
5994                    pkgSetting.lastUpdateTime = scanFileTime;
5995                }
5996            }
5997
5998            // Add the package's KeySets to the global KeySetManagerService
5999            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6000            try {
6001                // Old KeySetData no longer valid.
6002                ksms.removeAppKeySetDataLPw(pkg.packageName);
6003                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6004                if (pkg.mKeySetMapping != null) {
6005                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
6006                            pkg.mKeySetMapping.entrySet()) {
6007                        if (entry.getValue() != null) {
6008                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
6009                                                          entry.getValue(), entry.getKey());
6010                        }
6011                    }
6012                    if (pkg.mUpgradeKeySets != null) {
6013                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
6014                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
6015                        }
6016                    }
6017                }
6018            } catch (NullPointerException e) {
6019                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6020            } catch (IllegalArgumentException e) {
6021                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6022            }
6023
6024            int N = pkg.providers.size();
6025            StringBuilder r = null;
6026            int i;
6027            for (i=0; i<N; i++) {
6028                PackageParser.Provider p = pkg.providers.get(i);
6029                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6030                        p.info.processName, pkg.applicationInfo.uid);
6031                mProviders.addProvider(p);
6032                p.syncable = p.info.isSyncable;
6033                if (p.info.authority != null) {
6034                    String names[] = p.info.authority.split(";");
6035                    p.info.authority = null;
6036                    for (int j = 0; j < names.length; j++) {
6037                        if (j == 1 && p.syncable) {
6038                            // We only want the first authority for a provider to possibly be
6039                            // syncable, so if we already added this provider using a different
6040                            // authority clear the syncable flag. We copy the provider before
6041                            // changing it because the mProviders object contains a reference
6042                            // to a provider that we don't want to change.
6043                            // Only do this for the second authority since the resulting provider
6044                            // object can be the same for all future authorities for this provider.
6045                            p = new PackageParser.Provider(p);
6046                            p.syncable = false;
6047                        }
6048                        if (!mProvidersByAuthority.containsKey(names[j])) {
6049                            mProvidersByAuthority.put(names[j], p);
6050                            if (p.info.authority == null) {
6051                                p.info.authority = names[j];
6052                            } else {
6053                                p.info.authority = p.info.authority + ";" + names[j];
6054                            }
6055                            if (DEBUG_PACKAGE_SCANNING) {
6056                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6057                                    Log.d(TAG, "Registered content provider: " + names[j]
6058                                            + ", className = " + p.info.name + ", isSyncable = "
6059                                            + p.info.isSyncable);
6060                            }
6061                        } else {
6062                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6063                            Slog.w(TAG, "Skipping provider name " + names[j] +
6064                                    " (in package " + pkg.applicationInfo.packageName +
6065                                    "): name already used by "
6066                                    + ((other != null && other.getComponentName() != null)
6067                                            ? other.getComponentName().getPackageName() : "?"));
6068                        }
6069                    }
6070                }
6071                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6072                    if (r == null) {
6073                        r = new StringBuilder(256);
6074                    } else {
6075                        r.append(' ');
6076                    }
6077                    r.append(p.info.name);
6078                }
6079            }
6080            if (r != null) {
6081                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6082            }
6083
6084            N = pkg.services.size();
6085            r = null;
6086            for (i=0; i<N; i++) {
6087                PackageParser.Service s = pkg.services.get(i);
6088                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6089                        s.info.processName, pkg.applicationInfo.uid);
6090                mServices.addService(s);
6091                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6092                    if (r == null) {
6093                        r = new StringBuilder(256);
6094                    } else {
6095                        r.append(' ');
6096                    }
6097                    r.append(s.info.name);
6098                }
6099            }
6100            if (r != null) {
6101                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6102            }
6103
6104            N = pkg.receivers.size();
6105            r = null;
6106            for (i=0; i<N; i++) {
6107                PackageParser.Activity a = pkg.receivers.get(i);
6108                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6109                        a.info.processName, pkg.applicationInfo.uid);
6110                mReceivers.addActivity(a, "receiver");
6111                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6112                    if (r == null) {
6113                        r = new StringBuilder(256);
6114                    } else {
6115                        r.append(' ');
6116                    }
6117                    r.append(a.info.name);
6118                }
6119            }
6120            if (r != null) {
6121                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6122            }
6123
6124            N = pkg.activities.size();
6125            r = null;
6126            for (i=0; i<N; i++) {
6127                PackageParser.Activity a = pkg.activities.get(i);
6128                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6129                        a.info.processName, pkg.applicationInfo.uid);
6130                mActivities.addActivity(a, "activity");
6131                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6132                    if (r == null) {
6133                        r = new StringBuilder(256);
6134                    } else {
6135                        r.append(' ');
6136                    }
6137                    r.append(a.info.name);
6138                }
6139            }
6140            if (r != null) {
6141                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6142            }
6143
6144            N = pkg.permissionGroups.size();
6145            r = null;
6146            for (i=0; i<N; i++) {
6147                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6148                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6149                if (cur == null) {
6150                    mPermissionGroups.put(pg.info.name, pg);
6151                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6152                        if (r == null) {
6153                            r = new StringBuilder(256);
6154                        } else {
6155                            r.append(' ');
6156                        }
6157                        r.append(pg.info.name);
6158                    }
6159                } else {
6160                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6161                            + pg.info.packageName + " ignored: original from "
6162                            + cur.info.packageName);
6163                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6164                        if (r == null) {
6165                            r = new StringBuilder(256);
6166                        } else {
6167                            r.append(' ');
6168                        }
6169                        r.append("DUP:");
6170                        r.append(pg.info.name);
6171                    }
6172                }
6173            }
6174            if (r != null) {
6175                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6176            }
6177
6178            N = pkg.permissions.size();
6179            r = null;
6180            for (i=0; i<N; i++) {
6181                PackageParser.Permission p = pkg.permissions.get(i);
6182                ArrayMap<String, BasePermission> permissionMap =
6183                        p.tree ? mSettings.mPermissionTrees
6184                        : mSettings.mPermissions;
6185                p.group = mPermissionGroups.get(p.info.group);
6186                if (p.info.group == null || p.group != null) {
6187                    BasePermission bp = permissionMap.get(p.info.name);
6188
6189                    // Allow system apps to redefine non-system permissions
6190                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6191                        final boolean currentOwnerIsSystem = (bp.perm != null
6192                                && isSystemApp(bp.perm.owner));
6193                        if (isSystemApp(p.owner)) {
6194                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6195                                // It's a built-in permission and no owner, take ownership now
6196                                bp.packageSetting = pkgSetting;
6197                                bp.perm = p;
6198                                bp.uid = pkg.applicationInfo.uid;
6199                                bp.sourcePackage = p.info.packageName;
6200                            } else if (!currentOwnerIsSystem) {
6201                                String msg = "New decl " + p.owner + " of permission  "
6202                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6203                                reportSettingsProblem(Log.WARN, msg);
6204                                bp = null;
6205                            }
6206                        }
6207                    }
6208
6209                    if (bp == null) {
6210                        bp = new BasePermission(p.info.name, p.info.packageName,
6211                                BasePermission.TYPE_NORMAL);
6212                        permissionMap.put(p.info.name, bp);
6213                    }
6214
6215                    if (bp.perm == null) {
6216                        if (bp.sourcePackage == null
6217                                || bp.sourcePackage.equals(p.info.packageName)) {
6218                            BasePermission tree = findPermissionTreeLP(p.info.name);
6219                            if (tree == null
6220                                    || tree.sourcePackage.equals(p.info.packageName)) {
6221                                bp.packageSetting = pkgSetting;
6222                                bp.perm = p;
6223                                bp.uid = pkg.applicationInfo.uid;
6224                                bp.sourcePackage = p.info.packageName;
6225                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6226                                    if (r == null) {
6227                                        r = new StringBuilder(256);
6228                                    } else {
6229                                        r.append(' ');
6230                                    }
6231                                    r.append(p.info.name);
6232                                }
6233                            } else {
6234                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6235                                        + p.info.packageName + " ignored: base tree "
6236                                        + tree.name + " is from package "
6237                                        + tree.sourcePackage);
6238                            }
6239                        } else {
6240                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6241                                    + p.info.packageName + " ignored: original from "
6242                                    + bp.sourcePackage);
6243                        }
6244                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6245                        if (r == null) {
6246                            r = new StringBuilder(256);
6247                        } else {
6248                            r.append(' ');
6249                        }
6250                        r.append("DUP:");
6251                        r.append(p.info.name);
6252                    }
6253                    if (bp.perm == p) {
6254                        bp.protectionLevel = p.info.protectionLevel;
6255                    }
6256                } else {
6257                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6258                            + p.info.packageName + " ignored: no group "
6259                            + p.group);
6260                }
6261            }
6262            if (r != null) {
6263                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6264            }
6265
6266            N = pkg.instrumentation.size();
6267            r = null;
6268            for (i=0; i<N; i++) {
6269                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6270                a.info.packageName = pkg.applicationInfo.packageName;
6271                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6272                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6273                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6274                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6275                a.info.dataDir = pkg.applicationInfo.dataDir;
6276
6277                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6278                // need other information about the application, like the ABI and what not ?
6279                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6280                mInstrumentation.put(a.getComponentName(), a);
6281                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6282                    if (r == null) {
6283                        r = new StringBuilder(256);
6284                    } else {
6285                        r.append(' ');
6286                    }
6287                    r.append(a.info.name);
6288                }
6289            }
6290            if (r != null) {
6291                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6292            }
6293
6294            if (pkg.protectedBroadcasts != null) {
6295                N = pkg.protectedBroadcasts.size();
6296                for (i=0; i<N; i++) {
6297                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6298                }
6299            }
6300
6301            pkgSetting.setTimeStamp(scanFileTime);
6302
6303            // Create idmap files for pairs of (packages, overlay packages).
6304            // Note: "android", ie framework-res.apk, is handled by native layers.
6305            if (pkg.mOverlayTarget != null) {
6306                // This is an overlay package.
6307                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6308                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6309                        mOverlays.put(pkg.mOverlayTarget,
6310                                new ArrayMap<String, PackageParser.Package>());
6311                    }
6312                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6313                    map.put(pkg.packageName, pkg);
6314                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6315                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6316                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6317                                "scanPackageLI failed to createIdmap");
6318                    }
6319                }
6320            } else if (mOverlays.containsKey(pkg.packageName) &&
6321                    !pkg.packageName.equals("android")) {
6322                // This is a regular package, with one or more known overlay packages.
6323                createIdmapsForPackageLI(pkg);
6324            }
6325        }
6326
6327        return pkg;
6328    }
6329
6330    /**
6331     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6332     * i.e, so that all packages can be run inside a single process if required.
6333     *
6334     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6335     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6336     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6337     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6338     * updating a package that belongs to a shared user.
6339     *
6340     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6341     * adds unnecessary complexity.
6342     */
6343    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6344            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6345        String requiredInstructionSet = null;
6346        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6347            requiredInstructionSet = VMRuntime.getInstructionSet(
6348                     scannedPackage.applicationInfo.primaryCpuAbi);
6349        }
6350
6351        PackageSetting requirer = null;
6352        for (PackageSetting ps : packagesForUser) {
6353            // If packagesForUser contains scannedPackage, we skip it. This will happen
6354            // when scannedPackage is an update of an existing package. Without this check,
6355            // we will never be able to change the ABI of any package belonging to a shared
6356            // user, even if it's compatible with other packages.
6357            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6358                if (ps.primaryCpuAbiString == null) {
6359                    continue;
6360                }
6361
6362                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6363                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6364                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6365                    // this but there's not much we can do.
6366                    String errorMessage = "Instruction set mismatch, "
6367                            + ((requirer == null) ? "[caller]" : requirer)
6368                            + " requires " + requiredInstructionSet + " whereas " + ps
6369                            + " requires " + instructionSet;
6370                    Slog.w(TAG, errorMessage);
6371                }
6372
6373                if (requiredInstructionSet == null) {
6374                    requiredInstructionSet = instructionSet;
6375                    requirer = ps;
6376                }
6377            }
6378        }
6379
6380        if (requiredInstructionSet != null) {
6381            String adjustedAbi;
6382            if (requirer != null) {
6383                // requirer != null implies that either scannedPackage was null or that scannedPackage
6384                // did not require an ABI, in which case we have to adjust scannedPackage to match
6385                // the ABI of the set (which is the same as requirer's ABI)
6386                adjustedAbi = requirer.primaryCpuAbiString;
6387                if (scannedPackage != null) {
6388                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6389                }
6390            } else {
6391                // requirer == null implies that we're updating all ABIs in the set to
6392                // match scannedPackage.
6393                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6394            }
6395
6396            for (PackageSetting ps : packagesForUser) {
6397                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6398                    if (ps.primaryCpuAbiString != null) {
6399                        continue;
6400                    }
6401
6402                    ps.primaryCpuAbiString = adjustedAbi;
6403                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6404                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6405                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6406
6407                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6408                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6409                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6410                            ps.primaryCpuAbiString = null;
6411                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6412                            return;
6413                        } else {
6414                            mInstaller.rmdex(ps.codePathString,
6415                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6416                        }
6417                    }
6418                }
6419            }
6420        }
6421    }
6422
6423    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6424        synchronized (mPackages) {
6425            mResolverReplaced = true;
6426            // Set up information for custom user intent resolution activity.
6427            mResolveActivity.applicationInfo = pkg.applicationInfo;
6428            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6429            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6430            mResolveActivity.processName = pkg.applicationInfo.packageName;
6431            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6432            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6433                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6434            mResolveActivity.theme = 0;
6435            mResolveActivity.exported = true;
6436            mResolveActivity.enabled = true;
6437            mResolveInfo.activityInfo = mResolveActivity;
6438            mResolveInfo.priority = 0;
6439            mResolveInfo.preferredOrder = 0;
6440            mResolveInfo.match = 0;
6441            mResolveComponentName = mCustomResolverComponentName;
6442            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6443                    mResolveComponentName);
6444        }
6445    }
6446
6447    private static String calculateBundledApkRoot(final String codePathString) {
6448        final File codePath = new File(codePathString);
6449        final File codeRoot;
6450        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6451            codeRoot = Environment.getRootDirectory();
6452        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6453            codeRoot = Environment.getOemDirectory();
6454        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6455            codeRoot = Environment.getVendorDirectory();
6456        } else {
6457            // Unrecognized code path; take its top real segment as the apk root:
6458            // e.g. /something/app/blah.apk => /something
6459            try {
6460                File f = codePath.getCanonicalFile();
6461                File parent = f.getParentFile();    // non-null because codePath is a file
6462                File tmp;
6463                while ((tmp = parent.getParentFile()) != null) {
6464                    f = parent;
6465                    parent = tmp;
6466                }
6467                codeRoot = f;
6468                Slog.w(TAG, "Unrecognized code path "
6469                        + codePath + " - using " + codeRoot);
6470            } catch (IOException e) {
6471                // Can't canonicalize the code path -- shenanigans?
6472                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6473                return Environment.getRootDirectory().getPath();
6474            }
6475        }
6476        return codeRoot.getPath();
6477    }
6478
6479    /**
6480     * Derive and set the location of native libraries for the given package,
6481     * which varies depending on where and how the package was installed.
6482     */
6483    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6484        final ApplicationInfo info = pkg.applicationInfo;
6485        final String codePath = pkg.codePath;
6486        final File codeFile = new File(codePath);
6487        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6488        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6489
6490        info.nativeLibraryRootDir = null;
6491        info.nativeLibraryRootRequiresIsa = false;
6492        info.nativeLibraryDir = null;
6493        info.secondaryNativeLibraryDir = null;
6494
6495        if (isApkFile(codeFile)) {
6496            // Monolithic install
6497            if (bundledApp) {
6498                // If "/system/lib64/apkname" exists, assume that is the per-package
6499                // native library directory to use; otherwise use "/system/lib/apkname".
6500                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6501                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6502                        getPrimaryInstructionSet(info));
6503
6504                // This is a bundled system app so choose the path based on the ABI.
6505                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6506                // is just the default path.
6507                final String apkName = deriveCodePathName(codePath);
6508                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6509                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6510                        apkName).getAbsolutePath();
6511
6512                if (info.secondaryCpuAbi != null) {
6513                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6514                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6515                            secondaryLibDir, apkName).getAbsolutePath();
6516                }
6517            } else if (asecApp) {
6518                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6519                        .getAbsolutePath();
6520            } else {
6521                final String apkName = deriveCodePathName(codePath);
6522                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6523                        .getAbsolutePath();
6524            }
6525
6526            info.nativeLibraryRootRequiresIsa = false;
6527            info.nativeLibraryDir = info.nativeLibraryRootDir;
6528        } else {
6529            // Cluster install
6530            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6531            info.nativeLibraryRootRequiresIsa = true;
6532
6533            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6534                    getPrimaryInstructionSet(info)).getAbsolutePath();
6535
6536            if (info.secondaryCpuAbi != null) {
6537                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6538                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6539            }
6540        }
6541    }
6542
6543    /**
6544     * Calculate the abis and roots for a bundled app. These can uniquely
6545     * be determined from the contents of the system partition, i.e whether
6546     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6547     * of this information, and instead assume that the system was built
6548     * sensibly.
6549     */
6550    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6551                                           PackageSetting pkgSetting) {
6552        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6553
6554        // If "/system/lib64/apkname" exists, assume that is the per-package
6555        // native library directory to use; otherwise use "/system/lib/apkname".
6556        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6557        setBundledAppAbi(pkg, apkRoot, apkName);
6558        // pkgSetting might be null during rescan following uninstall of updates
6559        // to a bundled app, so accommodate that possibility.  The settings in
6560        // that case will be established later from the parsed package.
6561        //
6562        // If the settings aren't null, sync them up with what we've just derived.
6563        // note that apkRoot isn't stored in the package settings.
6564        if (pkgSetting != null) {
6565            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6566            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6567        }
6568    }
6569
6570    /**
6571     * Deduces the ABI of a bundled app and sets the relevant fields on the
6572     * parsed pkg object.
6573     *
6574     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6575     *        under which system libraries are installed.
6576     * @param apkName the name of the installed package.
6577     */
6578    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6579        final File codeFile = new File(pkg.codePath);
6580
6581        final boolean has64BitLibs;
6582        final boolean has32BitLibs;
6583        if (isApkFile(codeFile)) {
6584            // Monolithic install
6585            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6586            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6587        } else {
6588            // Cluster install
6589            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6590            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6591                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6592                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6593                has64BitLibs = (new File(rootDir, isa)).exists();
6594            } else {
6595                has64BitLibs = false;
6596            }
6597            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6598                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6599                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6600                has32BitLibs = (new File(rootDir, isa)).exists();
6601            } else {
6602                has32BitLibs = false;
6603            }
6604        }
6605
6606        if (has64BitLibs && !has32BitLibs) {
6607            // The package has 64 bit libs, but not 32 bit libs. Its primary
6608            // ABI should be 64 bit. We can safely assume here that the bundled
6609            // native libraries correspond to the most preferred ABI in the list.
6610
6611            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6612            pkg.applicationInfo.secondaryCpuAbi = null;
6613        } else if (has32BitLibs && !has64BitLibs) {
6614            // The package has 32 bit libs but not 64 bit libs. Its primary
6615            // ABI should be 32 bit.
6616
6617            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6618            pkg.applicationInfo.secondaryCpuAbi = null;
6619        } else if (has32BitLibs && has64BitLibs) {
6620            // The application has both 64 and 32 bit bundled libraries. We check
6621            // here that the app declares multiArch support, and warn if it doesn't.
6622            //
6623            // We will be lenient here and record both ABIs. The primary will be the
6624            // ABI that's higher on the list, i.e, a device that's configured to prefer
6625            // 64 bit apps will see a 64 bit primary ABI,
6626
6627            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6628                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6629            }
6630
6631            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6632                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6633                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6634            } else {
6635                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6636                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6637            }
6638        } else {
6639            pkg.applicationInfo.primaryCpuAbi = null;
6640            pkg.applicationInfo.secondaryCpuAbi = null;
6641        }
6642    }
6643
6644    private void killApplication(String pkgName, int appId, String reason) {
6645        // Request the ActivityManager to kill the process(only for existing packages)
6646        // so that we do not end up in a confused state while the user is still using the older
6647        // version of the application while the new one gets installed.
6648        IActivityManager am = ActivityManagerNative.getDefault();
6649        if (am != null) {
6650            try {
6651                am.killApplicationWithAppId(pkgName, appId, reason);
6652            } catch (RemoteException e) {
6653            }
6654        }
6655    }
6656
6657    void removePackageLI(PackageSetting ps, boolean chatty) {
6658        if (DEBUG_INSTALL) {
6659            if (chatty)
6660                Log.d(TAG, "Removing package " + ps.name);
6661        }
6662
6663        // writer
6664        synchronized (mPackages) {
6665            mPackages.remove(ps.name);
6666            final PackageParser.Package pkg = ps.pkg;
6667            if (pkg != null) {
6668                cleanPackageDataStructuresLILPw(pkg, chatty);
6669            }
6670        }
6671    }
6672
6673    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6674        if (DEBUG_INSTALL) {
6675            if (chatty)
6676                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6677        }
6678
6679        // writer
6680        synchronized (mPackages) {
6681            mPackages.remove(pkg.applicationInfo.packageName);
6682            cleanPackageDataStructuresLILPw(pkg, chatty);
6683        }
6684    }
6685
6686    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6687        int N = pkg.providers.size();
6688        StringBuilder r = null;
6689        int i;
6690        for (i=0; i<N; i++) {
6691            PackageParser.Provider p = pkg.providers.get(i);
6692            mProviders.removeProvider(p);
6693            if (p.info.authority == null) {
6694
6695                /* There was another ContentProvider with this authority when
6696                 * this app was installed so this authority is null,
6697                 * Ignore it as we don't have to unregister the provider.
6698                 */
6699                continue;
6700            }
6701            String names[] = p.info.authority.split(";");
6702            for (int j = 0; j < names.length; j++) {
6703                if (mProvidersByAuthority.get(names[j]) == p) {
6704                    mProvidersByAuthority.remove(names[j]);
6705                    if (DEBUG_REMOVE) {
6706                        if (chatty)
6707                            Log.d(TAG, "Unregistered content provider: " + names[j]
6708                                    + ", className = " + p.info.name + ", isSyncable = "
6709                                    + p.info.isSyncable);
6710                    }
6711                }
6712            }
6713            if (DEBUG_REMOVE && chatty) {
6714                if (r == null) {
6715                    r = new StringBuilder(256);
6716                } else {
6717                    r.append(' ');
6718                }
6719                r.append(p.info.name);
6720            }
6721        }
6722        if (r != null) {
6723            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6724        }
6725
6726        N = pkg.services.size();
6727        r = null;
6728        for (i=0; i<N; i++) {
6729            PackageParser.Service s = pkg.services.get(i);
6730            mServices.removeService(s);
6731            if (chatty) {
6732                if (r == null) {
6733                    r = new StringBuilder(256);
6734                } else {
6735                    r.append(' ');
6736                }
6737                r.append(s.info.name);
6738            }
6739        }
6740        if (r != null) {
6741            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6742        }
6743
6744        N = pkg.receivers.size();
6745        r = null;
6746        for (i=0; i<N; i++) {
6747            PackageParser.Activity a = pkg.receivers.get(i);
6748            mReceivers.removeActivity(a, "receiver");
6749            if (DEBUG_REMOVE && chatty) {
6750                if (r == null) {
6751                    r = new StringBuilder(256);
6752                } else {
6753                    r.append(' ');
6754                }
6755                r.append(a.info.name);
6756            }
6757        }
6758        if (r != null) {
6759            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6760        }
6761
6762        N = pkg.activities.size();
6763        r = null;
6764        for (i=0; i<N; i++) {
6765            PackageParser.Activity a = pkg.activities.get(i);
6766            mActivities.removeActivity(a, "activity");
6767            if (DEBUG_REMOVE && chatty) {
6768                if (r == null) {
6769                    r = new StringBuilder(256);
6770                } else {
6771                    r.append(' ');
6772                }
6773                r.append(a.info.name);
6774            }
6775        }
6776        if (r != null) {
6777            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6778        }
6779
6780        N = pkg.permissions.size();
6781        r = null;
6782        for (i=0; i<N; i++) {
6783            PackageParser.Permission p = pkg.permissions.get(i);
6784            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6785            if (bp == null) {
6786                bp = mSettings.mPermissionTrees.get(p.info.name);
6787            }
6788            if (bp != null && bp.perm == p) {
6789                bp.perm = null;
6790                if (DEBUG_REMOVE && chatty) {
6791                    if (r == null) {
6792                        r = new StringBuilder(256);
6793                    } else {
6794                        r.append(' ');
6795                    }
6796                    r.append(p.info.name);
6797                }
6798            }
6799            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6800                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6801                if (appOpPerms != null) {
6802                    appOpPerms.remove(pkg.packageName);
6803                }
6804            }
6805        }
6806        if (r != null) {
6807            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6808        }
6809
6810        N = pkg.requestedPermissions.size();
6811        r = null;
6812        for (i=0; i<N; i++) {
6813            String perm = pkg.requestedPermissions.get(i);
6814            BasePermission bp = mSettings.mPermissions.get(perm);
6815            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6816                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6817                if (appOpPerms != null) {
6818                    appOpPerms.remove(pkg.packageName);
6819                    if (appOpPerms.isEmpty()) {
6820                        mAppOpPermissionPackages.remove(perm);
6821                    }
6822                }
6823            }
6824        }
6825        if (r != null) {
6826            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6827        }
6828
6829        N = pkg.instrumentation.size();
6830        r = null;
6831        for (i=0; i<N; i++) {
6832            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6833            mInstrumentation.remove(a.getComponentName());
6834            if (DEBUG_REMOVE && chatty) {
6835                if (r == null) {
6836                    r = new StringBuilder(256);
6837                } else {
6838                    r.append(' ');
6839                }
6840                r.append(a.info.name);
6841            }
6842        }
6843        if (r != null) {
6844            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6845        }
6846
6847        r = null;
6848        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6849            // Only system apps can hold shared libraries.
6850            if (pkg.libraryNames != null) {
6851                for (i=0; i<pkg.libraryNames.size(); i++) {
6852                    String name = pkg.libraryNames.get(i);
6853                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6854                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6855                        mSharedLibraries.remove(name);
6856                        if (DEBUG_REMOVE && chatty) {
6857                            if (r == null) {
6858                                r = new StringBuilder(256);
6859                            } else {
6860                                r.append(' ');
6861                            }
6862                            r.append(name);
6863                        }
6864                    }
6865                }
6866            }
6867        }
6868        if (r != null) {
6869            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6870        }
6871    }
6872
6873    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6874        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6875            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6876                return true;
6877            }
6878        }
6879        return false;
6880    }
6881
6882    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6883    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6884    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6885
6886    private void updatePermissionsLPw(String changingPkg,
6887            PackageParser.Package pkgInfo, int flags) {
6888        // Make sure there are no dangling permission trees.
6889        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6890        while (it.hasNext()) {
6891            final BasePermission bp = it.next();
6892            if (bp.packageSetting == null) {
6893                // We may not yet have parsed the package, so just see if
6894                // we still know about its settings.
6895                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6896            }
6897            if (bp.packageSetting == null) {
6898                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6899                        + " from package " + bp.sourcePackage);
6900                it.remove();
6901            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6902                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6903                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6904                            + " from package " + bp.sourcePackage);
6905                    flags |= UPDATE_PERMISSIONS_ALL;
6906                    it.remove();
6907                }
6908            }
6909        }
6910
6911        // Make sure all dynamic permissions have been assigned to a package,
6912        // and make sure there are no dangling permissions.
6913        it = mSettings.mPermissions.values().iterator();
6914        while (it.hasNext()) {
6915            final BasePermission bp = it.next();
6916            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6917                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6918                        + bp.name + " pkg=" + bp.sourcePackage
6919                        + " info=" + bp.pendingInfo);
6920                if (bp.packageSetting == null && bp.pendingInfo != null) {
6921                    final BasePermission tree = findPermissionTreeLP(bp.name);
6922                    if (tree != null && tree.perm != null) {
6923                        bp.packageSetting = tree.packageSetting;
6924                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6925                                new PermissionInfo(bp.pendingInfo));
6926                        bp.perm.info.packageName = tree.perm.info.packageName;
6927                        bp.perm.info.name = bp.name;
6928                        bp.uid = tree.uid;
6929                    }
6930                }
6931            }
6932            if (bp.packageSetting == null) {
6933                // We may not yet have parsed the package, so just see if
6934                // we still know about its settings.
6935                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6936            }
6937            if (bp.packageSetting == null) {
6938                Slog.w(TAG, "Removing dangling permission: " + bp.name
6939                        + " from package " + bp.sourcePackage);
6940                it.remove();
6941            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6942                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6943                    Slog.i(TAG, "Removing old permission: " + bp.name
6944                            + " from package " + bp.sourcePackage);
6945                    flags |= UPDATE_PERMISSIONS_ALL;
6946                    it.remove();
6947                }
6948            }
6949        }
6950
6951        // Now update the permissions for all packages, in particular
6952        // replace the granted permissions of the system packages.
6953        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6954            for (PackageParser.Package pkg : mPackages.values()) {
6955                if (pkg != pkgInfo) {
6956                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6957                            changingPkg);
6958                }
6959            }
6960        }
6961
6962        if (pkgInfo != null) {
6963            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6964        }
6965    }
6966
6967    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6968            String packageOfInterest) {
6969        // IMPORTANT: There are two types of permissions: install and runtime.
6970        // Install time permissions are granted when the app is installed to
6971        // all device users and users added in the future. Runtime permissions
6972        // are granted at runtime explicitly to specific users. Normal and signature
6973        // protected permissions are install time permissions. Dangerous permissions
6974        // are install permissions if the app's target SDK is Lollipop MR1 or older,
6975        // otherwise they are runtime permissions. This function does not manage
6976        // runtime permissions except for the case an app targeting Lollipop MR1
6977        // being upgraded to target a newer SDK, in which case dangerous permissions
6978        // are transformed from install time to runtime ones.
6979
6980        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6981        if (ps == null) {
6982            return;
6983        }
6984
6985        PermissionsState permissionsState = ps.getPermissionsState();
6986        PermissionsState origPermissions = permissionsState;
6987
6988        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
6989
6990        int[] upgradeUserIds = PermissionsState.USERS_NONE;
6991        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
6992
6993        boolean changedInstallPermission = false;
6994
6995        if (replace) {
6996            ps.installPermissionsFixed = false;
6997            origPermissions = new PermissionsState(permissionsState);
6998            permissionsState.reset();
6999        }
7000
7001        permissionsState.setGlobalGids(mGlobalGids);
7002
7003        final int N = pkg.requestedPermissions.size();
7004        for (int i=0; i<N; i++) {
7005            final String name = pkg.requestedPermissions.get(i);
7006            final BasePermission bp = mSettings.mPermissions.get(name);
7007
7008            if (DEBUG_INSTALL) {
7009                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7010            }
7011
7012            if (bp == null || bp.packageSetting == null) {
7013                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7014                    Slog.w(TAG, "Unknown permission " + name
7015                            + " in package " + pkg.packageName);
7016                }
7017                continue;
7018            }
7019
7020            final String perm = bp.name;
7021            boolean allowedSig = false;
7022            int grant = GRANT_DENIED;
7023
7024            // Keep track of app op permissions.
7025            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7026                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7027                if (pkgs == null) {
7028                    pkgs = new ArraySet<>();
7029                    mAppOpPermissionPackages.put(bp.name, pkgs);
7030                }
7031                pkgs.add(pkg.packageName);
7032            }
7033
7034            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7035            switch (level) {
7036                case PermissionInfo.PROTECTION_NORMAL: {
7037                    // For all apps normal permissions are install time ones.
7038                    grant = GRANT_INSTALL;
7039                } break;
7040
7041                case PermissionInfo.PROTECTION_DANGEROUS: {
7042                    if (!RUNTIME_PERMISSIONS_ENABLED
7043                            || pkg.applicationInfo.targetSdkVersion
7044                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7045                        // For legacy apps dangerous permissions are install time ones.
7046                        grant = GRANT_INSTALL;
7047                    } else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7048                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7049                        if (origPermissions.hasInstallPermission(bp.name)) {
7050                            // If a system app had an install permission, then the app was
7051                            // upgraded and we grant the permissions as runtime to all users.
7052                            grant = GRANT_UPGRADE;
7053                            upgradeUserIds = currentUserIds;
7054                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7055                            // If users changed since the last permissions update for a
7056                            // system app, we grant the permission as runtime to the new users.
7057                            grant = GRANT_UPGRADE;
7058                            upgradeUserIds = currentUserIds;
7059                            for (int userId : updatedUserIds) {
7060                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7061                            }
7062                        } else {
7063                            // Otherwise, we grant the permission as runtime if the app
7064                            // already had it, i.e. we preserve runtime permissions.
7065                            grant = GRANT_RUNTIME;
7066                        }
7067                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7068                        // For legacy apps that became modern, install becomes runtime.
7069                        grant = GRANT_UPGRADE;
7070                        upgradeUserIds = currentUserIds;
7071                    } else if (replace) {
7072                        // For upgraded modern apps keep runtime permissions unchanged.
7073                        grant = GRANT_RUNTIME;
7074                    }
7075                } break;
7076
7077                case PermissionInfo.PROTECTION_SIGNATURE: {
7078                    // For all apps signature permissions are install time ones.
7079                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7080                    if (allowedSig) {
7081                        grant = GRANT_INSTALL;
7082                    }
7083                } break;
7084            }
7085
7086            if (DEBUG_INSTALL) {
7087                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7088            }
7089
7090            if (grant != GRANT_DENIED) {
7091                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7092                    // If this is an existing, non-system package, then
7093                    // we can't add any new permissions to it.
7094                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7095                        // Except...  if this is a permission that was added
7096                        // to the platform (note: need to only do this when
7097                        // updating the platform).
7098                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7099                            grant = GRANT_DENIED;
7100                        }
7101                    }
7102                }
7103
7104                switch (grant) {
7105                    case GRANT_INSTALL: {
7106                        // Grant an install permission.
7107                        if (permissionsState.grantInstallPermission(bp) !=
7108                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7109                            changedInstallPermission = true;
7110                        }
7111                    } break;
7112
7113                    case GRANT_RUNTIME: {
7114                        // Grant previously granted runtime permissions.
7115                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7116                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7117                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7118                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7119                                    // If we cannot put the permission as it was, we have to write.
7120                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7121                                            changedRuntimePermissionUserIds, userId);
7122                                }
7123                            }
7124                        }
7125                    } break;
7126
7127                    case GRANT_UPGRADE: {
7128                        // Grant runtime permissions for a previously held install permission.
7129                        permissionsState.revokeInstallPermission(bp);
7130                        for (int userId : upgradeUserIds) {
7131                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7132                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7133                                // If we granted the permission, we have to write.
7134                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7135                                        changedRuntimePermissionUserIds, userId);
7136                            }
7137                        }
7138                    } break;
7139
7140                    default: {
7141                        if (packageOfInterest == null
7142                                || packageOfInterest.equals(pkg.packageName)) {
7143                            Slog.w(TAG, "Not granting permission " + perm
7144                                    + " to package " + pkg.packageName
7145                                    + " because it was previously installed without");
7146                        }
7147                    } break;
7148                }
7149            } else {
7150                if (permissionsState.revokeInstallPermission(bp) !=
7151                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7152                    changedInstallPermission = true;
7153                    Slog.i(TAG, "Un-granting permission " + perm
7154                            + " from package " + pkg.packageName
7155                            + " (protectionLevel=" + bp.protectionLevel
7156                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7157                            + ")");
7158                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7159                    // Don't print warning for app op permissions, since it is fine for them
7160                    // not to be granted, there is a UI for the user to decide.
7161                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7162                        Slog.w(TAG, "Not granting permission " + perm
7163                                + " to package " + pkg.packageName
7164                                + " (protectionLevel=" + bp.protectionLevel
7165                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7166                                + ")");
7167                    }
7168                }
7169            }
7170        }
7171
7172        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7173                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7174            // This is the first that we have heard about this package, so the
7175            // permissions we have now selected are fixed until explicitly
7176            // changed.
7177            ps.installPermissionsFixed = true;
7178        }
7179
7180        ps.setPermissionsUpdatedForUserIds(changedRuntimePermissionUserIds);
7181
7182        // Persist the runtime permissions state for users with changes.
7183        for (int userId : changedRuntimePermissionUserIds) {
7184           mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7185        }
7186    }
7187
7188    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7189        boolean allowed = false;
7190        final int NP = PackageParser.NEW_PERMISSIONS.length;
7191        for (int ip=0; ip<NP; ip++) {
7192            final PackageParser.NewPermissionInfo npi
7193                    = PackageParser.NEW_PERMISSIONS[ip];
7194            if (npi.name.equals(perm)
7195                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7196                allowed = true;
7197                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7198                        + pkg.packageName);
7199                break;
7200            }
7201        }
7202        return allowed;
7203    }
7204
7205    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7206            BasePermission bp, PermissionsState origPermissions) {
7207        boolean allowed;
7208        allowed = (compareSignatures(
7209                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7210                        == PackageManager.SIGNATURE_MATCH)
7211                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7212                        == PackageManager.SIGNATURE_MATCH);
7213        if (!allowed && (bp.protectionLevel
7214                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7215            if (isSystemApp(pkg)) {
7216                // For updated system applications, a system permission
7217                // is granted only if it had been defined by the original application.
7218                if (isUpdatedSystemApp(pkg)) {
7219                    final PackageSetting sysPs = mSettings
7220                            .getDisabledSystemPkgLPr(pkg.packageName);
7221                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7222                        // If the original was granted this permission, we take
7223                        // that grant decision as read and propagate it to the
7224                        // update.
7225                        if (sysPs.isPrivileged()) {
7226                            allowed = true;
7227                        }
7228                    } else {
7229                        // The system apk may have been updated with an older
7230                        // version of the one on the data partition, but which
7231                        // granted a new system permission that it didn't have
7232                        // before.  In this case we do want to allow the app to
7233                        // now get the new permission if the ancestral apk is
7234                        // privileged to get it.
7235                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7236                            for (int j=0;
7237                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7238                                if (perm.equals(
7239                                        sysPs.pkg.requestedPermissions.get(j))) {
7240                                    allowed = true;
7241                                    break;
7242                                }
7243                            }
7244                        }
7245                    }
7246                } else {
7247                    allowed = isPrivilegedApp(pkg);
7248                }
7249            }
7250        }
7251        if (!allowed && (bp.protectionLevel
7252                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7253            // For development permissions, a development permission
7254            // is granted only if it was already granted.
7255            allowed = origPermissions.hasInstallPermission(perm);
7256        }
7257        return allowed;
7258    }
7259
7260    final class ActivityIntentResolver
7261            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7262        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7263                boolean defaultOnly, int userId) {
7264            if (!sUserManager.exists(userId)) return null;
7265            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7266            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7267        }
7268
7269        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7270                int userId) {
7271            if (!sUserManager.exists(userId)) return null;
7272            mFlags = flags;
7273            return super.queryIntent(intent, resolvedType,
7274                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7275        }
7276
7277        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7278                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7279            if (!sUserManager.exists(userId)) return null;
7280            if (packageActivities == null) {
7281                return null;
7282            }
7283            mFlags = flags;
7284            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7285            final int N = packageActivities.size();
7286            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7287                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7288
7289            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7290            for (int i = 0; i < N; ++i) {
7291                intentFilters = packageActivities.get(i).intents;
7292                if (intentFilters != null && intentFilters.size() > 0) {
7293                    PackageParser.ActivityIntentInfo[] array =
7294                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7295                    intentFilters.toArray(array);
7296                    listCut.add(array);
7297                }
7298            }
7299            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7300        }
7301
7302        public final void addActivity(PackageParser.Activity a, String type) {
7303            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7304            mActivities.put(a.getComponentName(), a);
7305            if (DEBUG_SHOW_INFO)
7306                Log.v(
7307                TAG, "  " + type + " " +
7308                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7309            if (DEBUG_SHOW_INFO)
7310                Log.v(TAG, "    Class=" + a.info.name);
7311            final int NI = a.intents.size();
7312            for (int j=0; j<NI; j++) {
7313                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7314                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7315                    intent.setPriority(0);
7316                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7317                            + a.className + " with priority > 0, forcing to 0");
7318                }
7319                if (DEBUG_SHOW_INFO) {
7320                    Log.v(TAG, "    IntentFilter:");
7321                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7322                }
7323                if (!intent.debugCheck()) {
7324                    Log.w(TAG, "==> For Activity " + a.info.name);
7325                }
7326                addFilter(intent);
7327            }
7328        }
7329
7330        public final void removeActivity(PackageParser.Activity a, String type) {
7331            mActivities.remove(a.getComponentName());
7332            if (DEBUG_SHOW_INFO) {
7333                Log.v(TAG, "  " + type + " "
7334                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7335                                : a.info.name) + ":");
7336                Log.v(TAG, "    Class=" + a.info.name);
7337            }
7338            final int NI = a.intents.size();
7339            for (int j=0; j<NI; j++) {
7340                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7341                if (DEBUG_SHOW_INFO) {
7342                    Log.v(TAG, "    IntentFilter:");
7343                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7344                }
7345                removeFilter(intent);
7346            }
7347        }
7348
7349        @Override
7350        protected boolean allowFilterResult(
7351                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7352            ActivityInfo filterAi = filter.activity.info;
7353            for (int i=dest.size()-1; i>=0; i--) {
7354                ActivityInfo destAi = dest.get(i).activityInfo;
7355                if (destAi.name == filterAi.name
7356                        && destAi.packageName == filterAi.packageName) {
7357                    return false;
7358                }
7359            }
7360            return true;
7361        }
7362
7363        @Override
7364        protected ActivityIntentInfo[] newArray(int size) {
7365            return new ActivityIntentInfo[size];
7366        }
7367
7368        @Override
7369        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7370            if (!sUserManager.exists(userId)) return true;
7371            PackageParser.Package p = filter.activity.owner;
7372            if (p != null) {
7373                PackageSetting ps = (PackageSetting)p.mExtras;
7374                if (ps != null) {
7375                    // System apps are never considered stopped for purposes of
7376                    // filtering, because there may be no way for the user to
7377                    // actually re-launch them.
7378                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7379                            && ps.getStopped(userId);
7380                }
7381            }
7382            return false;
7383        }
7384
7385        @Override
7386        protected boolean isPackageForFilter(String packageName,
7387                PackageParser.ActivityIntentInfo info) {
7388            return packageName.equals(info.activity.owner.packageName);
7389        }
7390
7391        @Override
7392        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7393                int match, int userId) {
7394            if (!sUserManager.exists(userId)) return null;
7395            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7396                return null;
7397            }
7398            final PackageParser.Activity activity = info.activity;
7399            if (mSafeMode && (activity.info.applicationInfo.flags
7400                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7401                return null;
7402            }
7403            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7404            if (ps == null) {
7405                return null;
7406            }
7407            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7408                    ps.readUserState(userId), userId);
7409            if (ai == null) {
7410                return null;
7411            }
7412            final ResolveInfo res = new ResolveInfo();
7413            res.activityInfo = ai;
7414            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7415                res.filter = info;
7416            }
7417            res.priority = info.getPriority();
7418            res.preferredOrder = activity.owner.mPreferredOrder;
7419            //System.out.println("Result: " + res.activityInfo.className +
7420            //                   " = " + res.priority);
7421            res.match = match;
7422            res.isDefault = info.hasDefault;
7423            res.labelRes = info.labelRes;
7424            res.nonLocalizedLabel = info.nonLocalizedLabel;
7425            if (userNeedsBadging(userId)) {
7426                res.noResourceId = true;
7427            } else {
7428                res.icon = info.icon;
7429            }
7430            res.system = isSystemApp(res.activityInfo.applicationInfo);
7431            return res;
7432        }
7433
7434        @Override
7435        protected void sortResults(List<ResolveInfo> results) {
7436            Collections.sort(results, mResolvePrioritySorter);
7437        }
7438
7439        @Override
7440        protected void dumpFilter(PrintWriter out, String prefix,
7441                PackageParser.ActivityIntentInfo filter) {
7442            out.print(prefix); out.print(
7443                    Integer.toHexString(System.identityHashCode(filter.activity)));
7444                    out.print(' ');
7445                    filter.activity.printComponentShortName(out);
7446                    out.print(" filter ");
7447                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7448        }
7449
7450        @Override
7451        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7452            return filter.activity;
7453        }
7454
7455        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7456            PackageParser.Activity activity = (PackageParser.Activity)label;
7457            out.print(prefix); out.print(
7458                    Integer.toHexString(System.identityHashCode(activity)));
7459                    out.print(' ');
7460                    activity.printComponentShortName(out);
7461            if (count > 1) {
7462                out.print(" ("); out.print(count); out.print(" filters)");
7463            }
7464            out.println();
7465        }
7466
7467//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7468//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7469//            final List<ResolveInfo> retList = Lists.newArrayList();
7470//            while (i.hasNext()) {
7471//                final ResolveInfo resolveInfo = i.next();
7472//                if (isEnabledLP(resolveInfo.activityInfo)) {
7473//                    retList.add(resolveInfo);
7474//                }
7475//            }
7476//            return retList;
7477//        }
7478
7479        // Keys are String (activity class name), values are Activity.
7480        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7481                = new ArrayMap<ComponentName, PackageParser.Activity>();
7482        private int mFlags;
7483    }
7484
7485    private final class ServiceIntentResolver
7486            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7487        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7488                boolean defaultOnly, int userId) {
7489            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7490            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7491        }
7492
7493        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7494                int userId) {
7495            if (!sUserManager.exists(userId)) return null;
7496            mFlags = flags;
7497            return super.queryIntent(intent, resolvedType,
7498                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7499        }
7500
7501        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7502                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7503            if (!sUserManager.exists(userId)) return null;
7504            if (packageServices == null) {
7505                return null;
7506            }
7507            mFlags = flags;
7508            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7509            final int N = packageServices.size();
7510            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7511                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7512
7513            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7514            for (int i = 0; i < N; ++i) {
7515                intentFilters = packageServices.get(i).intents;
7516                if (intentFilters != null && intentFilters.size() > 0) {
7517                    PackageParser.ServiceIntentInfo[] array =
7518                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7519                    intentFilters.toArray(array);
7520                    listCut.add(array);
7521                }
7522            }
7523            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7524        }
7525
7526        public final void addService(PackageParser.Service s) {
7527            mServices.put(s.getComponentName(), s);
7528            if (DEBUG_SHOW_INFO) {
7529                Log.v(TAG, "  "
7530                        + (s.info.nonLocalizedLabel != null
7531                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7532                Log.v(TAG, "    Class=" + s.info.name);
7533            }
7534            final int NI = s.intents.size();
7535            int j;
7536            for (j=0; j<NI; j++) {
7537                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7538                if (DEBUG_SHOW_INFO) {
7539                    Log.v(TAG, "    IntentFilter:");
7540                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7541                }
7542                if (!intent.debugCheck()) {
7543                    Log.w(TAG, "==> For Service " + s.info.name);
7544                }
7545                addFilter(intent);
7546            }
7547        }
7548
7549        public final void removeService(PackageParser.Service s) {
7550            mServices.remove(s.getComponentName());
7551            if (DEBUG_SHOW_INFO) {
7552                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7553                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7554                Log.v(TAG, "    Class=" + s.info.name);
7555            }
7556            final int NI = s.intents.size();
7557            int j;
7558            for (j=0; j<NI; j++) {
7559                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7560                if (DEBUG_SHOW_INFO) {
7561                    Log.v(TAG, "    IntentFilter:");
7562                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7563                }
7564                removeFilter(intent);
7565            }
7566        }
7567
7568        @Override
7569        protected boolean allowFilterResult(
7570                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7571            ServiceInfo filterSi = filter.service.info;
7572            for (int i=dest.size()-1; i>=0; i--) {
7573                ServiceInfo destAi = dest.get(i).serviceInfo;
7574                if (destAi.name == filterSi.name
7575                        && destAi.packageName == filterSi.packageName) {
7576                    return false;
7577                }
7578            }
7579            return true;
7580        }
7581
7582        @Override
7583        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7584            return new PackageParser.ServiceIntentInfo[size];
7585        }
7586
7587        @Override
7588        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7589            if (!sUserManager.exists(userId)) return true;
7590            PackageParser.Package p = filter.service.owner;
7591            if (p != null) {
7592                PackageSetting ps = (PackageSetting)p.mExtras;
7593                if (ps != null) {
7594                    // System apps are never considered stopped for purposes of
7595                    // filtering, because there may be no way for the user to
7596                    // actually re-launch them.
7597                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7598                            && ps.getStopped(userId);
7599                }
7600            }
7601            return false;
7602        }
7603
7604        @Override
7605        protected boolean isPackageForFilter(String packageName,
7606                PackageParser.ServiceIntentInfo info) {
7607            return packageName.equals(info.service.owner.packageName);
7608        }
7609
7610        @Override
7611        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7612                int match, int userId) {
7613            if (!sUserManager.exists(userId)) return null;
7614            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7615            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7616                return null;
7617            }
7618            final PackageParser.Service service = info.service;
7619            if (mSafeMode && (service.info.applicationInfo.flags
7620                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7621                return null;
7622            }
7623            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7624            if (ps == null) {
7625                return null;
7626            }
7627            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7628                    ps.readUserState(userId), userId);
7629            if (si == null) {
7630                return null;
7631            }
7632            final ResolveInfo res = new ResolveInfo();
7633            res.serviceInfo = si;
7634            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7635                res.filter = filter;
7636            }
7637            res.priority = info.getPriority();
7638            res.preferredOrder = service.owner.mPreferredOrder;
7639            //System.out.println("Result: " + res.activityInfo.className +
7640            //                   " = " + res.priority);
7641            res.match = match;
7642            res.isDefault = info.hasDefault;
7643            res.labelRes = info.labelRes;
7644            res.nonLocalizedLabel = info.nonLocalizedLabel;
7645            res.icon = info.icon;
7646            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7647            return res;
7648        }
7649
7650        @Override
7651        protected void sortResults(List<ResolveInfo> results) {
7652            Collections.sort(results, mResolvePrioritySorter);
7653        }
7654
7655        @Override
7656        protected void dumpFilter(PrintWriter out, String prefix,
7657                PackageParser.ServiceIntentInfo filter) {
7658            out.print(prefix); out.print(
7659                    Integer.toHexString(System.identityHashCode(filter.service)));
7660                    out.print(' ');
7661                    filter.service.printComponentShortName(out);
7662                    out.print(" filter ");
7663                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7664        }
7665
7666        @Override
7667        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7668            return filter.service;
7669        }
7670
7671        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7672            PackageParser.Service service = (PackageParser.Service)label;
7673            out.print(prefix); out.print(
7674                    Integer.toHexString(System.identityHashCode(service)));
7675                    out.print(' ');
7676                    service.printComponentShortName(out);
7677            if (count > 1) {
7678                out.print(" ("); out.print(count); out.print(" filters)");
7679            }
7680            out.println();
7681        }
7682
7683//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7684//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7685//            final List<ResolveInfo> retList = Lists.newArrayList();
7686//            while (i.hasNext()) {
7687//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7688//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7689//                    retList.add(resolveInfo);
7690//                }
7691//            }
7692//            return retList;
7693//        }
7694
7695        // Keys are String (activity class name), values are Activity.
7696        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7697                = new ArrayMap<ComponentName, PackageParser.Service>();
7698        private int mFlags;
7699    };
7700
7701    private final class ProviderIntentResolver
7702            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7703        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7704                boolean defaultOnly, int userId) {
7705            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7706            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7707        }
7708
7709        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7710                int userId) {
7711            if (!sUserManager.exists(userId))
7712                return null;
7713            mFlags = flags;
7714            return super.queryIntent(intent, resolvedType,
7715                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7716        }
7717
7718        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7719                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7720            if (!sUserManager.exists(userId))
7721                return null;
7722            if (packageProviders == null) {
7723                return null;
7724            }
7725            mFlags = flags;
7726            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7727            final int N = packageProviders.size();
7728            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7729                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7730
7731            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7732            for (int i = 0; i < N; ++i) {
7733                intentFilters = packageProviders.get(i).intents;
7734                if (intentFilters != null && intentFilters.size() > 0) {
7735                    PackageParser.ProviderIntentInfo[] array =
7736                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7737                    intentFilters.toArray(array);
7738                    listCut.add(array);
7739                }
7740            }
7741            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7742        }
7743
7744        public final void addProvider(PackageParser.Provider p) {
7745            if (mProviders.containsKey(p.getComponentName())) {
7746                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7747                return;
7748            }
7749
7750            mProviders.put(p.getComponentName(), p);
7751            if (DEBUG_SHOW_INFO) {
7752                Log.v(TAG, "  "
7753                        + (p.info.nonLocalizedLabel != null
7754                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7755                Log.v(TAG, "    Class=" + p.info.name);
7756            }
7757            final int NI = p.intents.size();
7758            int j;
7759            for (j = 0; j < NI; j++) {
7760                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7761                if (DEBUG_SHOW_INFO) {
7762                    Log.v(TAG, "    IntentFilter:");
7763                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7764                }
7765                if (!intent.debugCheck()) {
7766                    Log.w(TAG, "==> For Provider " + p.info.name);
7767                }
7768                addFilter(intent);
7769            }
7770        }
7771
7772        public final void removeProvider(PackageParser.Provider p) {
7773            mProviders.remove(p.getComponentName());
7774            if (DEBUG_SHOW_INFO) {
7775                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7776                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7777                Log.v(TAG, "    Class=" + p.info.name);
7778            }
7779            final int NI = p.intents.size();
7780            int j;
7781            for (j = 0; j < NI; j++) {
7782                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7783                if (DEBUG_SHOW_INFO) {
7784                    Log.v(TAG, "    IntentFilter:");
7785                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7786                }
7787                removeFilter(intent);
7788            }
7789        }
7790
7791        @Override
7792        protected boolean allowFilterResult(
7793                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7794            ProviderInfo filterPi = filter.provider.info;
7795            for (int i = dest.size() - 1; i >= 0; i--) {
7796                ProviderInfo destPi = dest.get(i).providerInfo;
7797                if (destPi.name == filterPi.name
7798                        && destPi.packageName == filterPi.packageName) {
7799                    return false;
7800                }
7801            }
7802            return true;
7803        }
7804
7805        @Override
7806        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7807            return new PackageParser.ProviderIntentInfo[size];
7808        }
7809
7810        @Override
7811        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7812            if (!sUserManager.exists(userId))
7813                return true;
7814            PackageParser.Package p = filter.provider.owner;
7815            if (p != null) {
7816                PackageSetting ps = (PackageSetting) p.mExtras;
7817                if (ps != null) {
7818                    // System apps are never considered stopped for purposes of
7819                    // filtering, because there may be no way for the user to
7820                    // actually re-launch them.
7821                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7822                            && ps.getStopped(userId);
7823                }
7824            }
7825            return false;
7826        }
7827
7828        @Override
7829        protected boolean isPackageForFilter(String packageName,
7830                PackageParser.ProviderIntentInfo info) {
7831            return packageName.equals(info.provider.owner.packageName);
7832        }
7833
7834        @Override
7835        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7836                int match, int userId) {
7837            if (!sUserManager.exists(userId))
7838                return null;
7839            final PackageParser.ProviderIntentInfo info = filter;
7840            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7841                return null;
7842            }
7843            final PackageParser.Provider provider = info.provider;
7844            if (mSafeMode && (provider.info.applicationInfo.flags
7845                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7846                return null;
7847            }
7848            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7849            if (ps == null) {
7850                return null;
7851            }
7852            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7853                    ps.readUserState(userId), userId);
7854            if (pi == null) {
7855                return null;
7856            }
7857            final ResolveInfo res = new ResolveInfo();
7858            res.providerInfo = pi;
7859            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7860                res.filter = filter;
7861            }
7862            res.priority = info.getPriority();
7863            res.preferredOrder = provider.owner.mPreferredOrder;
7864            res.match = match;
7865            res.isDefault = info.hasDefault;
7866            res.labelRes = info.labelRes;
7867            res.nonLocalizedLabel = info.nonLocalizedLabel;
7868            res.icon = info.icon;
7869            res.system = isSystemApp(res.providerInfo.applicationInfo);
7870            return res;
7871        }
7872
7873        @Override
7874        protected void sortResults(List<ResolveInfo> results) {
7875            Collections.sort(results, mResolvePrioritySorter);
7876        }
7877
7878        @Override
7879        protected void dumpFilter(PrintWriter out, String prefix,
7880                PackageParser.ProviderIntentInfo filter) {
7881            out.print(prefix);
7882            out.print(
7883                    Integer.toHexString(System.identityHashCode(filter.provider)));
7884            out.print(' ');
7885            filter.provider.printComponentShortName(out);
7886            out.print(" filter ");
7887            out.println(Integer.toHexString(System.identityHashCode(filter)));
7888        }
7889
7890        @Override
7891        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7892            return filter.provider;
7893        }
7894
7895        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7896            PackageParser.Provider provider = (PackageParser.Provider)label;
7897            out.print(prefix); out.print(
7898                    Integer.toHexString(System.identityHashCode(provider)));
7899                    out.print(' ');
7900                    provider.printComponentShortName(out);
7901            if (count > 1) {
7902                out.print(" ("); out.print(count); out.print(" filters)");
7903            }
7904            out.println();
7905        }
7906
7907        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7908                = new ArrayMap<ComponentName, PackageParser.Provider>();
7909        private int mFlags;
7910    };
7911
7912    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7913            new Comparator<ResolveInfo>() {
7914        public int compare(ResolveInfo r1, ResolveInfo r2) {
7915            int v1 = r1.priority;
7916            int v2 = r2.priority;
7917            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7918            if (v1 != v2) {
7919                return (v1 > v2) ? -1 : 1;
7920            }
7921            v1 = r1.preferredOrder;
7922            v2 = r2.preferredOrder;
7923            if (v1 != v2) {
7924                return (v1 > v2) ? -1 : 1;
7925            }
7926            if (r1.isDefault != r2.isDefault) {
7927                return r1.isDefault ? -1 : 1;
7928            }
7929            v1 = r1.match;
7930            v2 = r2.match;
7931            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7932            if (v1 != v2) {
7933                return (v1 > v2) ? -1 : 1;
7934            }
7935            if (r1.system != r2.system) {
7936                return r1.system ? -1 : 1;
7937            }
7938            return 0;
7939        }
7940    };
7941
7942    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7943            new Comparator<ProviderInfo>() {
7944        public int compare(ProviderInfo p1, ProviderInfo p2) {
7945            final int v1 = p1.initOrder;
7946            final int v2 = p2.initOrder;
7947            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7948        }
7949    };
7950
7951    static final void sendPackageBroadcast(String action, String pkg,
7952            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7953            int[] userIds) {
7954        IActivityManager am = ActivityManagerNative.getDefault();
7955        if (am != null) {
7956            try {
7957                if (userIds == null) {
7958                    userIds = am.getRunningUserIds();
7959                }
7960                for (int id : userIds) {
7961                    final Intent intent = new Intent(action,
7962                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7963                    if (extras != null) {
7964                        intent.putExtras(extras);
7965                    }
7966                    if (targetPkg != null) {
7967                        intent.setPackage(targetPkg);
7968                    }
7969                    // Modify the UID when posting to other users
7970                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7971                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7972                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7973                        intent.putExtra(Intent.EXTRA_UID, uid);
7974                    }
7975                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7976                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7977                    if (DEBUG_BROADCASTS) {
7978                        RuntimeException here = new RuntimeException("here");
7979                        here.fillInStackTrace();
7980                        Slog.d(TAG, "Sending to user " + id + ": "
7981                                + intent.toShortString(false, true, false, false)
7982                                + " " + intent.getExtras(), here);
7983                    }
7984                    am.broadcastIntent(null, intent, null, finishedReceiver,
7985                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7986                            finishedReceiver != null, false, id);
7987                }
7988            } catch (RemoteException ex) {
7989            }
7990        }
7991    }
7992
7993    /**
7994     * Check if the external storage media is available. This is true if there
7995     * is a mounted external storage medium or if the external storage is
7996     * emulated.
7997     */
7998    private boolean isExternalMediaAvailable() {
7999        return mMediaMounted || Environment.isExternalStorageEmulated();
8000    }
8001
8002    @Override
8003    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8004        // writer
8005        synchronized (mPackages) {
8006            if (!isExternalMediaAvailable()) {
8007                // If the external storage is no longer mounted at this point,
8008                // the caller may not have been able to delete all of this
8009                // packages files and can not delete any more.  Bail.
8010                return null;
8011            }
8012            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8013            if (lastPackage != null) {
8014                pkgs.remove(lastPackage);
8015            }
8016            if (pkgs.size() > 0) {
8017                return pkgs.get(0);
8018            }
8019        }
8020        return null;
8021    }
8022
8023    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8024        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8025                userId, andCode ? 1 : 0, packageName);
8026        if (mSystemReady) {
8027            msg.sendToTarget();
8028        } else {
8029            if (mPostSystemReadyMessages == null) {
8030                mPostSystemReadyMessages = new ArrayList<>();
8031            }
8032            mPostSystemReadyMessages.add(msg);
8033        }
8034    }
8035
8036    void startCleaningPackages() {
8037        // reader
8038        synchronized (mPackages) {
8039            if (!isExternalMediaAvailable()) {
8040                return;
8041            }
8042            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8043                return;
8044            }
8045        }
8046        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8047        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8048        IActivityManager am = ActivityManagerNative.getDefault();
8049        if (am != null) {
8050            try {
8051                am.startService(null, intent, null, UserHandle.USER_OWNER);
8052            } catch (RemoteException e) {
8053            }
8054        }
8055    }
8056
8057    @Override
8058    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8059            int installFlags, String installerPackageName, VerificationParams verificationParams,
8060            String packageAbiOverride) {
8061        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
8062                packageAbiOverride, UserHandle.getCallingUserId());
8063    }
8064
8065    @Override
8066    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8067            int installFlags, String installerPackageName, VerificationParams verificationParams,
8068            String packageAbiOverride, int userId) {
8069        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8070
8071        final int callingUid = Binder.getCallingUid();
8072        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8073
8074        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8075            try {
8076                if (observer != null) {
8077                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8078                }
8079            } catch (RemoteException re) {
8080            }
8081            return;
8082        }
8083
8084        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8085            installFlags |= PackageManager.INSTALL_FROM_ADB;
8086
8087        } else {
8088            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8089            // about installerPackageName.
8090
8091            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8092            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8093        }
8094
8095        UserHandle user;
8096        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8097            user = UserHandle.ALL;
8098        } else {
8099            user = new UserHandle(userId);
8100        }
8101
8102        verificationParams.setInstallerUid(callingUid);
8103
8104        final File originFile = new File(originPath);
8105        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8106
8107        final Message msg = mHandler.obtainMessage(INIT_COPY);
8108        msg.obj = new InstallParams(origin, observer, installFlags,
8109                installerPackageName, verificationParams, user, packageAbiOverride);
8110        mHandler.sendMessage(msg);
8111    }
8112
8113    void installStage(String packageName, File stagedDir, String stagedCid,
8114            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8115            String installerPackageName, int installerUid, UserHandle user) {
8116        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8117                params.referrerUri, installerUid, null);
8118
8119        final OriginInfo origin;
8120        if (stagedDir != null) {
8121            origin = OriginInfo.fromStagedFile(stagedDir);
8122        } else {
8123            origin = OriginInfo.fromStagedContainer(stagedCid);
8124        }
8125
8126        final Message msg = mHandler.obtainMessage(INIT_COPY);
8127        msg.obj = new InstallParams(origin, observer, params.installFlags,
8128                installerPackageName, verifParams, user, params.abiOverride);
8129        mHandler.sendMessage(msg);
8130    }
8131
8132    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8133        Bundle extras = new Bundle(1);
8134        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8135
8136        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8137                packageName, extras, null, null, new int[] {userId});
8138        try {
8139            IActivityManager am = ActivityManagerNative.getDefault();
8140            final boolean isSystem =
8141                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8142            if (isSystem && am.isUserRunning(userId, false)) {
8143                // The just-installed/enabled app is bundled on the system, so presumed
8144                // to be able to run automatically without needing an explicit launch.
8145                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8146                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8147                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8148                        .setPackage(packageName);
8149                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8150                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8151            }
8152        } catch (RemoteException e) {
8153            // shouldn't happen
8154            Slog.w(TAG, "Unable to bootstrap installed package", e);
8155        }
8156    }
8157
8158    @Override
8159    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8160            int userId) {
8161        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8162        PackageSetting pkgSetting;
8163        final int uid = Binder.getCallingUid();
8164        enforceCrossUserPermission(uid, userId, true, true,
8165                "setApplicationHiddenSetting for user " + userId);
8166
8167        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8168            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8169            return false;
8170        }
8171
8172        long callingId = Binder.clearCallingIdentity();
8173        try {
8174            boolean sendAdded = false;
8175            boolean sendRemoved = false;
8176            // writer
8177            synchronized (mPackages) {
8178                pkgSetting = mSettings.mPackages.get(packageName);
8179                if (pkgSetting == null) {
8180                    return false;
8181                }
8182                if (pkgSetting.getHidden(userId) != hidden) {
8183                    pkgSetting.setHidden(hidden, userId);
8184                    mSettings.writePackageRestrictionsLPr(userId);
8185                    if (hidden) {
8186                        sendRemoved = true;
8187                    } else {
8188                        sendAdded = true;
8189                    }
8190                }
8191            }
8192            if (sendAdded) {
8193                sendPackageAddedForUser(packageName, pkgSetting, userId);
8194                return true;
8195            }
8196            if (sendRemoved) {
8197                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8198                        "hiding pkg");
8199                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8200            }
8201        } finally {
8202            Binder.restoreCallingIdentity(callingId);
8203        }
8204        return false;
8205    }
8206
8207    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8208            int userId) {
8209        final PackageRemovedInfo info = new PackageRemovedInfo();
8210        info.removedPackage = packageName;
8211        info.removedUsers = new int[] {userId};
8212        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8213        info.sendBroadcast(false, false, false);
8214    }
8215
8216    /**
8217     * Returns true if application is not found or there was an error. Otherwise it returns
8218     * the hidden state of the package for the given user.
8219     */
8220    @Override
8221    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8222        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8223        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8224                false, "getApplicationHidden for user " + userId);
8225        PackageSetting pkgSetting;
8226        long callingId = Binder.clearCallingIdentity();
8227        try {
8228            // writer
8229            synchronized (mPackages) {
8230                pkgSetting = mSettings.mPackages.get(packageName);
8231                if (pkgSetting == null) {
8232                    return true;
8233                }
8234                return pkgSetting.getHidden(userId);
8235            }
8236        } finally {
8237            Binder.restoreCallingIdentity(callingId);
8238        }
8239    }
8240
8241    /**
8242     * @hide
8243     */
8244    @Override
8245    public int installExistingPackageAsUser(String packageName, int userId) {
8246        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8247                null);
8248        PackageSetting pkgSetting;
8249        final int uid = Binder.getCallingUid();
8250        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8251                + userId);
8252        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8253            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8254        }
8255
8256        long callingId = Binder.clearCallingIdentity();
8257        try {
8258            boolean sendAdded = false;
8259            Bundle extras = new Bundle(1);
8260
8261            // writer
8262            synchronized (mPackages) {
8263                pkgSetting = mSettings.mPackages.get(packageName);
8264                if (pkgSetting == null) {
8265                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8266                }
8267                if (!pkgSetting.getInstalled(userId)) {
8268                    pkgSetting.setInstalled(true, userId);
8269                    pkgSetting.setHidden(false, userId);
8270                    mSettings.writePackageRestrictionsLPr(userId);
8271                    sendAdded = true;
8272                }
8273            }
8274
8275            if (sendAdded) {
8276                sendPackageAddedForUser(packageName, pkgSetting, userId);
8277            }
8278        } finally {
8279            Binder.restoreCallingIdentity(callingId);
8280        }
8281
8282        return PackageManager.INSTALL_SUCCEEDED;
8283    }
8284
8285    boolean isUserRestricted(int userId, String restrictionKey) {
8286        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8287        if (restrictions.getBoolean(restrictionKey, false)) {
8288            Log.w(TAG, "User is restricted: " + restrictionKey);
8289            return true;
8290        }
8291        return false;
8292    }
8293
8294    @Override
8295    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8296        mContext.enforceCallingOrSelfPermission(
8297                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8298                "Only package verification agents can verify applications");
8299
8300        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8301        final PackageVerificationResponse response = new PackageVerificationResponse(
8302                verificationCode, Binder.getCallingUid());
8303        msg.arg1 = id;
8304        msg.obj = response;
8305        mHandler.sendMessage(msg);
8306    }
8307
8308    @Override
8309    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8310            long millisecondsToDelay) {
8311        mContext.enforceCallingOrSelfPermission(
8312                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8313                "Only package verification agents can extend verification timeouts");
8314
8315        final PackageVerificationState state = mPendingVerification.get(id);
8316        final PackageVerificationResponse response = new PackageVerificationResponse(
8317                verificationCodeAtTimeout, Binder.getCallingUid());
8318
8319        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8320            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8321        }
8322        if (millisecondsToDelay < 0) {
8323            millisecondsToDelay = 0;
8324        }
8325        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8326                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8327            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8328        }
8329
8330        if ((state != null) && !state.timeoutExtended()) {
8331            state.extendTimeout();
8332
8333            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8334            msg.arg1 = id;
8335            msg.obj = response;
8336            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8337        }
8338    }
8339
8340    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8341            int verificationCode, UserHandle user) {
8342        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8343        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8344        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8345        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8346        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8347
8348        mContext.sendBroadcastAsUser(intent, user,
8349                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8350    }
8351
8352    private ComponentName matchComponentForVerifier(String packageName,
8353            List<ResolveInfo> receivers) {
8354        ActivityInfo targetReceiver = null;
8355
8356        final int NR = receivers.size();
8357        for (int i = 0; i < NR; i++) {
8358            final ResolveInfo info = receivers.get(i);
8359            if (info.activityInfo == null) {
8360                continue;
8361            }
8362
8363            if (packageName.equals(info.activityInfo.packageName)) {
8364                targetReceiver = info.activityInfo;
8365                break;
8366            }
8367        }
8368
8369        if (targetReceiver == null) {
8370            return null;
8371        }
8372
8373        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8374    }
8375
8376    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8377            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8378        if (pkgInfo.verifiers.length == 0) {
8379            return null;
8380        }
8381
8382        final int N = pkgInfo.verifiers.length;
8383        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8384        for (int i = 0; i < N; i++) {
8385            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8386
8387            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8388                    receivers);
8389            if (comp == null) {
8390                continue;
8391            }
8392
8393            final int verifierUid = getUidForVerifier(verifierInfo);
8394            if (verifierUid == -1) {
8395                continue;
8396            }
8397
8398            if (DEBUG_VERIFY) {
8399                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8400                        + " with the correct signature");
8401            }
8402            sufficientVerifiers.add(comp);
8403            verificationState.addSufficientVerifier(verifierUid);
8404        }
8405
8406        return sufficientVerifiers;
8407    }
8408
8409    private int getUidForVerifier(VerifierInfo verifierInfo) {
8410        synchronized (mPackages) {
8411            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8412            if (pkg == null) {
8413                return -1;
8414            } else if (pkg.mSignatures.length != 1) {
8415                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8416                        + " has more than one signature; ignoring");
8417                return -1;
8418            }
8419
8420            /*
8421             * If the public key of the package's signature does not match
8422             * our expected public key, then this is a different package and
8423             * we should skip.
8424             */
8425
8426            final byte[] expectedPublicKey;
8427            try {
8428                final Signature verifierSig = pkg.mSignatures[0];
8429                final PublicKey publicKey = verifierSig.getPublicKey();
8430                expectedPublicKey = publicKey.getEncoded();
8431            } catch (CertificateException e) {
8432                return -1;
8433            }
8434
8435            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8436
8437            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8438                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8439                        + " does not have the expected public key; ignoring");
8440                return -1;
8441            }
8442
8443            return pkg.applicationInfo.uid;
8444        }
8445    }
8446
8447    @Override
8448    public void finishPackageInstall(int token) {
8449        enforceSystemOrRoot("Only the system is allowed to finish installs");
8450
8451        if (DEBUG_INSTALL) {
8452            Slog.v(TAG, "BM finishing package install for " + token);
8453        }
8454
8455        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8456        mHandler.sendMessage(msg);
8457    }
8458
8459    /**
8460     * Get the verification agent timeout.
8461     *
8462     * @return verification timeout in milliseconds
8463     */
8464    private long getVerificationTimeout() {
8465        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8466                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8467                DEFAULT_VERIFICATION_TIMEOUT);
8468    }
8469
8470    /**
8471     * Get the default verification agent response code.
8472     *
8473     * @return default verification response code
8474     */
8475    private int getDefaultVerificationResponse() {
8476        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8477                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8478                DEFAULT_VERIFICATION_RESPONSE);
8479    }
8480
8481    /**
8482     * Check whether or not package verification has been enabled.
8483     *
8484     * @return true if verification should be performed
8485     */
8486    private boolean isVerificationEnabled(int userId, int installFlags) {
8487        if (!DEFAULT_VERIFY_ENABLE) {
8488            return false;
8489        }
8490
8491        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8492
8493        // Check if installing from ADB
8494        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8495            // Do not run verification in a test harness environment
8496            if (ActivityManager.isRunningInTestHarness()) {
8497                return false;
8498            }
8499            if (ensureVerifyAppsEnabled) {
8500                return true;
8501            }
8502            // Check if the developer does not want package verification for ADB installs
8503            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8504                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8505                return false;
8506            }
8507        }
8508
8509        if (ensureVerifyAppsEnabled) {
8510            return true;
8511        }
8512
8513        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8514                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8515    }
8516
8517    /**
8518     * Get the "allow unknown sources" setting.
8519     *
8520     * @return the current "allow unknown sources" setting
8521     */
8522    private int getUnknownSourcesSettings() {
8523        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8524                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8525                -1);
8526    }
8527
8528    @Override
8529    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8530        final int uid = Binder.getCallingUid();
8531        // writer
8532        synchronized (mPackages) {
8533            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8534            if (targetPackageSetting == null) {
8535                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8536            }
8537
8538            PackageSetting installerPackageSetting;
8539            if (installerPackageName != null) {
8540                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8541                if (installerPackageSetting == null) {
8542                    throw new IllegalArgumentException("Unknown installer package: "
8543                            + installerPackageName);
8544                }
8545            } else {
8546                installerPackageSetting = null;
8547            }
8548
8549            Signature[] callerSignature;
8550            Object obj = mSettings.getUserIdLPr(uid);
8551            if (obj != null) {
8552                if (obj instanceof SharedUserSetting) {
8553                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8554                } else if (obj instanceof PackageSetting) {
8555                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8556                } else {
8557                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8558                }
8559            } else {
8560                throw new SecurityException("Unknown calling uid " + uid);
8561            }
8562
8563            // Verify: can't set installerPackageName to a package that is
8564            // not signed with the same cert as the caller.
8565            if (installerPackageSetting != null) {
8566                if (compareSignatures(callerSignature,
8567                        installerPackageSetting.signatures.mSignatures)
8568                        != PackageManager.SIGNATURE_MATCH) {
8569                    throw new SecurityException(
8570                            "Caller does not have same cert as new installer package "
8571                            + installerPackageName);
8572                }
8573            }
8574
8575            // Verify: if target already has an installer package, it must
8576            // be signed with the same cert as the caller.
8577            if (targetPackageSetting.installerPackageName != null) {
8578                PackageSetting setting = mSettings.mPackages.get(
8579                        targetPackageSetting.installerPackageName);
8580                // If the currently set package isn't valid, then it's always
8581                // okay to change it.
8582                if (setting != null) {
8583                    if (compareSignatures(callerSignature,
8584                            setting.signatures.mSignatures)
8585                            != PackageManager.SIGNATURE_MATCH) {
8586                        throw new SecurityException(
8587                                "Caller does not have same cert as old installer package "
8588                                + targetPackageSetting.installerPackageName);
8589                    }
8590                }
8591            }
8592
8593            // Okay!
8594            targetPackageSetting.installerPackageName = installerPackageName;
8595            scheduleWriteSettingsLocked();
8596        }
8597    }
8598
8599    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8600        // Queue up an async operation since the package installation may take a little while.
8601        mHandler.post(new Runnable() {
8602            public void run() {
8603                mHandler.removeCallbacks(this);
8604                 // Result object to be returned
8605                PackageInstalledInfo res = new PackageInstalledInfo();
8606                res.returnCode = currentStatus;
8607                res.uid = -1;
8608                res.pkg = null;
8609                res.removedInfo = new PackageRemovedInfo();
8610                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8611                    args.doPreInstall(res.returnCode);
8612                    synchronized (mInstallLock) {
8613                        installPackageLI(args, res);
8614                    }
8615                    args.doPostInstall(res.returnCode, res.uid);
8616                }
8617
8618                // A restore should be performed at this point if (a) the install
8619                // succeeded, (b) the operation is not an update, and (c) the new
8620                // package has not opted out of backup participation.
8621                final boolean update = res.removedInfo.removedPackage != null;
8622                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8623                boolean doRestore = !update
8624                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8625
8626                // Set up the post-install work request bookkeeping.  This will be used
8627                // and cleaned up by the post-install event handling regardless of whether
8628                // there's a restore pass performed.  Token values are >= 1.
8629                int token;
8630                if (mNextInstallToken < 0) mNextInstallToken = 1;
8631                token = mNextInstallToken++;
8632
8633                PostInstallData data = new PostInstallData(args, res);
8634                mRunningInstalls.put(token, data);
8635                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8636
8637                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8638                    // Pass responsibility to the Backup Manager.  It will perform a
8639                    // restore if appropriate, then pass responsibility back to the
8640                    // Package Manager to run the post-install observer callbacks
8641                    // and broadcasts.
8642                    IBackupManager bm = IBackupManager.Stub.asInterface(
8643                            ServiceManager.getService(Context.BACKUP_SERVICE));
8644                    if (bm != null) {
8645                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8646                                + " to BM for possible restore");
8647                        try {
8648                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
8649                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8650                            } else {
8651                                doRestore = false;
8652                            }
8653                        } catch (RemoteException e) {
8654                            // can't happen; the backup manager is local
8655                        } catch (Exception e) {
8656                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8657                            doRestore = false;
8658                        }
8659                    } else {
8660                        Slog.e(TAG, "Backup Manager not found!");
8661                        doRestore = false;
8662                    }
8663                }
8664
8665                if (!doRestore) {
8666                    // No restore possible, or the Backup Manager was mysteriously not
8667                    // available -- just fire the post-install work request directly.
8668                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8669                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8670                    mHandler.sendMessage(msg);
8671                }
8672            }
8673        });
8674    }
8675
8676    private abstract class HandlerParams {
8677        private static final int MAX_RETRIES = 4;
8678
8679        /**
8680         * Number of times startCopy() has been attempted and had a non-fatal
8681         * error.
8682         */
8683        private int mRetries = 0;
8684
8685        /** User handle for the user requesting the information or installation. */
8686        private final UserHandle mUser;
8687
8688        HandlerParams(UserHandle user) {
8689            mUser = user;
8690        }
8691
8692        UserHandle getUser() {
8693            return mUser;
8694        }
8695
8696        final boolean startCopy() {
8697            boolean res;
8698            try {
8699                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8700
8701                if (++mRetries > MAX_RETRIES) {
8702                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8703                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8704                    handleServiceError();
8705                    return false;
8706                } else {
8707                    handleStartCopy();
8708                    res = true;
8709                }
8710            } catch (RemoteException e) {
8711                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8712                mHandler.sendEmptyMessage(MCS_RECONNECT);
8713                res = false;
8714            }
8715            handleReturnCode();
8716            return res;
8717        }
8718
8719        final void serviceError() {
8720            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8721            handleServiceError();
8722            handleReturnCode();
8723        }
8724
8725        abstract void handleStartCopy() throws RemoteException;
8726        abstract void handleServiceError();
8727        abstract void handleReturnCode();
8728    }
8729
8730    class MeasureParams extends HandlerParams {
8731        private final PackageStats mStats;
8732        private boolean mSuccess;
8733
8734        private final IPackageStatsObserver mObserver;
8735
8736        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8737            super(new UserHandle(stats.userHandle));
8738            mObserver = observer;
8739            mStats = stats;
8740        }
8741
8742        @Override
8743        public String toString() {
8744            return "MeasureParams{"
8745                + Integer.toHexString(System.identityHashCode(this))
8746                + " " + mStats.packageName + "}";
8747        }
8748
8749        @Override
8750        void handleStartCopy() throws RemoteException {
8751            synchronized (mInstallLock) {
8752                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8753            }
8754
8755            if (mSuccess) {
8756                final boolean mounted;
8757                if (Environment.isExternalStorageEmulated()) {
8758                    mounted = true;
8759                } else {
8760                    final String status = Environment.getExternalStorageState();
8761                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8762                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8763                }
8764
8765                if (mounted) {
8766                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8767
8768                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8769                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8770
8771                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8772                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8773
8774                    // Always subtract cache size, since it's a subdirectory
8775                    mStats.externalDataSize -= mStats.externalCacheSize;
8776
8777                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8778                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8779
8780                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8781                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8782                }
8783            }
8784        }
8785
8786        @Override
8787        void handleReturnCode() {
8788            if (mObserver != null) {
8789                try {
8790                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8791                } catch (RemoteException e) {
8792                    Slog.i(TAG, "Observer no longer exists.");
8793                }
8794            }
8795        }
8796
8797        @Override
8798        void handleServiceError() {
8799            Slog.e(TAG, "Could not measure application " + mStats.packageName
8800                            + " external storage");
8801        }
8802    }
8803
8804    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8805            throws RemoteException {
8806        long result = 0;
8807        for (File path : paths) {
8808            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8809        }
8810        return result;
8811    }
8812
8813    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8814        for (File path : paths) {
8815            try {
8816                mcs.clearDirectory(path.getAbsolutePath());
8817            } catch (RemoteException e) {
8818            }
8819        }
8820    }
8821
8822    static class OriginInfo {
8823        /**
8824         * Location where install is coming from, before it has been
8825         * copied/renamed into place. This could be a single monolithic APK
8826         * file, or a cluster directory. This location may be untrusted.
8827         */
8828        final File file;
8829        final String cid;
8830
8831        /**
8832         * Flag indicating that {@link #file} or {@link #cid} has already been
8833         * staged, meaning downstream users don't need to defensively copy the
8834         * contents.
8835         */
8836        final boolean staged;
8837
8838        /**
8839         * Flag indicating that {@link #file} or {@link #cid} is an already
8840         * installed app that is being moved.
8841         */
8842        final boolean existing;
8843
8844        final String resolvedPath;
8845        final File resolvedFile;
8846
8847        static OriginInfo fromNothing() {
8848            return new OriginInfo(null, null, false, false);
8849        }
8850
8851        static OriginInfo fromUntrustedFile(File file) {
8852            return new OriginInfo(file, null, false, false);
8853        }
8854
8855        static OriginInfo fromExistingFile(File file) {
8856            return new OriginInfo(file, null, false, true);
8857        }
8858
8859        static OriginInfo fromStagedFile(File file) {
8860            return new OriginInfo(file, null, true, false);
8861        }
8862
8863        static OriginInfo fromStagedContainer(String cid) {
8864            return new OriginInfo(null, cid, true, false);
8865        }
8866
8867        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8868            this.file = file;
8869            this.cid = cid;
8870            this.staged = staged;
8871            this.existing = existing;
8872
8873            if (cid != null) {
8874                resolvedPath = PackageHelper.getSdDir(cid);
8875                resolvedFile = new File(resolvedPath);
8876            } else if (file != null) {
8877                resolvedPath = file.getAbsolutePath();
8878                resolvedFile = file;
8879            } else {
8880                resolvedPath = null;
8881                resolvedFile = null;
8882            }
8883        }
8884    }
8885
8886    class InstallParams extends HandlerParams {
8887        final OriginInfo origin;
8888        final IPackageInstallObserver2 observer;
8889        int installFlags;
8890        final String installerPackageName;
8891        final VerificationParams verificationParams;
8892        private InstallArgs mArgs;
8893        private int mRet;
8894        final String packageAbiOverride;
8895
8896        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8897                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8898                String packageAbiOverride) {
8899            super(user);
8900            this.origin = origin;
8901            this.observer = observer;
8902            this.installFlags = installFlags;
8903            this.installerPackageName = installerPackageName;
8904            this.verificationParams = verificationParams;
8905            this.packageAbiOverride = packageAbiOverride;
8906        }
8907
8908        @Override
8909        public String toString() {
8910            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8911                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8912        }
8913
8914        public ManifestDigest getManifestDigest() {
8915            if (verificationParams == null) {
8916                return null;
8917            }
8918            return verificationParams.getManifestDigest();
8919        }
8920
8921        private int installLocationPolicy(PackageInfoLite pkgLite) {
8922            String packageName = pkgLite.packageName;
8923            int installLocation = pkgLite.installLocation;
8924            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8925            // reader
8926            synchronized (mPackages) {
8927                PackageParser.Package pkg = mPackages.get(packageName);
8928                if (pkg != null) {
8929                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8930                        // Check for downgrading.
8931                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8932                            try {
8933                                checkDowngrade(pkg, pkgLite);
8934                            } catch (PackageManagerException e) {
8935                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8936                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8937                            }
8938                        }
8939                        // Check for updated system application.
8940                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8941                            if (onSd) {
8942                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8943                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8944                            }
8945                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8946                        } else {
8947                            if (onSd) {
8948                                // Install flag overrides everything.
8949                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8950                            }
8951                            // If current upgrade specifies particular preference
8952                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8953                                // Application explicitly specified internal.
8954                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8955                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8956                                // App explictly prefers external. Let policy decide
8957                            } else {
8958                                // Prefer previous location
8959                                if (isExternal(pkg)) {
8960                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8961                                }
8962                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8963                            }
8964                        }
8965                    } else {
8966                        // Invalid install. Return error code
8967                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8968                    }
8969                }
8970            }
8971            // All the special cases have been taken care of.
8972            // Return result based on recommended install location.
8973            if (onSd) {
8974                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8975            }
8976            return pkgLite.recommendedInstallLocation;
8977        }
8978
8979        /*
8980         * Invoke remote method to get package information and install
8981         * location values. Override install location based on default
8982         * policy if needed and then create install arguments based
8983         * on the install location.
8984         */
8985        public void handleStartCopy() throws RemoteException {
8986            int ret = PackageManager.INSTALL_SUCCEEDED;
8987
8988            // If we're already staged, we've firmly committed to an install location
8989            if (origin.staged) {
8990                if (origin.file != null) {
8991                    installFlags |= PackageManager.INSTALL_INTERNAL;
8992                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8993                } else if (origin.cid != null) {
8994                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8995                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8996                } else {
8997                    throw new IllegalStateException("Invalid stage location");
8998                }
8999            }
9000
9001            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9002            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9003
9004            PackageInfoLite pkgLite = null;
9005
9006            if (onInt && onSd) {
9007                // Check if both bits are set.
9008                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9009                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9010            } else {
9011                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9012                        packageAbiOverride);
9013
9014                /*
9015                 * If we have too little free space, try to free cache
9016                 * before giving up.
9017                 */
9018                if (!origin.staged && pkgLite.recommendedInstallLocation
9019                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9020                    // TODO: focus freeing disk space on the target device
9021                    final StorageManager storage = StorageManager.from(mContext);
9022                    final long lowThreshold = storage.getStorageLowBytes(
9023                            Environment.getDataDirectory());
9024
9025                    final long sizeBytes = mContainerService.calculateInstalledSize(
9026                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9027
9028                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9029                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9030                                installFlags, packageAbiOverride);
9031                    }
9032
9033                    /*
9034                     * The cache free must have deleted the file we
9035                     * downloaded to install.
9036                     *
9037                     * TODO: fix the "freeCache" call to not delete
9038                     *       the file we care about.
9039                     */
9040                    if (pkgLite.recommendedInstallLocation
9041                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9042                        pkgLite.recommendedInstallLocation
9043                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9044                    }
9045                }
9046            }
9047
9048            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9049                int loc = pkgLite.recommendedInstallLocation;
9050                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9051                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9052                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9053                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9054                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9055                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9056                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9057                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9058                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9059                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9060                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9061                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9062                } else {
9063                    // Override with defaults if needed.
9064                    loc = installLocationPolicy(pkgLite);
9065                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9066                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9067                    } else if (!onSd && !onInt) {
9068                        // Override install location with flags
9069                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9070                            // Set the flag to install on external media.
9071                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9072                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9073                        } else {
9074                            // Make sure the flag for installing on external
9075                            // media is unset
9076                            installFlags |= PackageManager.INSTALL_INTERNAL;
9077                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9078                        }
9079                    }
9080                }
9081            }
9082
9083            final InstallArgs args = createInstallArgs(this);
9084            mArgs = args;
9085
9086            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9087                 /*
9088                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9089                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9090                 */
9091                int userIdentifier = getUser().getIdentifier();
9092                if (userIdentifier == UserHandle.USER_ALL
9093                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9094                    userIdentifier = UserHandle.USER_OWNER;
9095                }
9096
9097                /*
9098                 * Determine if we have any installed package verifiers. If we
9099                 * do, then we'll defer to them to verify the packages.
9100                 */
9101                final int requiredUid = mRequiredVerifierPackage == null ? -1
9102                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9103                if (!origin.existing && requiredUid != -1
9104                        && isVerificationEnabled(userIdentifier, installFlags)) {
9105                    final Intent verification = new Intent(
9106                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9107                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9108                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9109                            PACKAGE_MIME_TYPE);
9110                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9111
9112                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9113                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9114                            0 /* TODO: Which userId? */);
9115
9116                    if (DEBUG_VERIFY) {
9117                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9118                                + verification.toString() + " with " + pkgLite.verifiers.length
9119                                + " optional verifiers");
9120                    }
9121
9122                    final int verificationId = mPendingVerificationToken++;
9123
9124                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9125
9126                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9127                            installerPackageName);
9128
9129                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9130                            installFlags);
9131
9132                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9133                            pkgLite.packageName);
9134
9135                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9136                            pkgLite.versionCode);
9137
9138                    if (verificationParams != null) {
9139                        if (verificationParams.getVerificationURI() != null) {
9140                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9141                                 verificationParams.getVerificationURI());
9142                        }
9143                        if (verificationParams.getOriginatingURI() != null) {
9144                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9145                                  verificationParams.getOriginatingURI());
9146                        }
9147                        if (verificationParams.getReferrer() != null) {
9148                            verification.putExtra(Intent.EXTRA_REFERRER,
9149                                  verificationParams.getReferrer());
9150                        }
9151                        if (verificationParams.getOriginatingUid() >= 0) {
9152                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9153                                  verificationParams.getOriginatingUid());
9154                        }
9155                        if (verificationParams.getInstallerUid() >= 0) {
9156                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9157                                  verificationParams.getInstallerUid());
9158                        }
9159                    }
9160
9161                    final PackageVerificationState verificationState = new PackageVerificationState(
9162                            requiredUid, args);
9163
9164                    mPendingVerification.append(verificationId, verificationState);
9165
9166                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9167                            receivers, verificationState);
9168
9169                    /*
9170                     * If any sufficient verifiers were listed in the package
9171                     * manifest, attempt to ask them.
9172                     */
9173                    if (sufficientVerifiers != null) {
9174                        final int N = sufficientVerifiers.size();
9175                        if (N == 0) {
9176                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9177                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9178                        } else {
9179                            for (int i = 0; i < N; i++) {
9180                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9181
9182                                final Intent sufficientIntent = new Intent(verification);
9183                                sufficientIntent.setComponent(verifierComponent);
9184
9185                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9186                            }
9187                        }
9188                    }
9189
9190                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9191                            mRequiredVerifierPackage, receivers);
9192                    if (ret == PackageManager.INSTALL_SUCCEEDED
9193                            && mRequiredVerifierPackage != null) {
9194                        /*
9195                         * Send the intent to the required verification agent,
9196                         * but only start the verification timeout after the
9197                         * target BroadcastReceivers have run.
9198                         */
9199                        verification.setComponent(requiredVerifierComponent);
9200                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9201                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9202                                new BroadcastReceiver() {
9203                                    @Override
9204                                    public void onReceive(Context context, Intent intent) {
9205                                        final Message msg = mHandler
9206                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9207                                        msg.arg1 = verificationId;
9208                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9209                                    }
9210                                }, null, 0, null, null);
9211
9212                        /*
9213                         * We don't want the copy to proceed until verification
9214                         * succeeds, so null out this field.
9215                         */
9216                        mArgs = null;
9217                    }
9218                } else {
9219                    /*
9220                     * No package verification is enabled, so immediately start
9221                     * the remote call to initiate copy using temporary file.
9222                     */
9223                    ret = args.copyApk(mContainerService, true);
9224                }
9225            }
9226
9227            mRet = ret;
9228        }
9229
9230        @Override
9231        void handleReturnCode() {
9232            // If mArgs is null, then MCS couldn't be reached. When it
9233            // reconnects, it will try again to install. At that point, this
9234            // will succeed.
9235            if (mArgs != null) {
9236                processPendingInstall(mArgs, mRet);
9237            }
9238        }
9239
9240        @Override
9241        void handleServiceError() {
9242            mArgs = createInstallArgs(this);
9243            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9244        }
9245
9246        public boolean isForwardLocked() {
9247            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9248        }
9249    }
9250
9251    /**
9252     * Used during creation of InstallArgs
9253     *
9254     * @param installFlags package installation flags
9255     * @return true if should be installed on external storage
9256     */
9257    private static boolean installOnSd(int installFlags) {
9258        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9259            return false;
9260        }
9261        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9262            return true;
9263        }
9264        return false;
9265    }
9266
9267    /**
9268     * Used during creation of InstallArgs
9269     *
9270     * @param installFlags package installation flags
9271     * @return true if should be installed as forward locked
9272     */
9273    private static boolean installForwardLocked(int installFlags) {
9274        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9275    }
9276
9277    private InstallArgs createInstallArgs(InstallParams params) {
9278        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9279            return new AsecInstallArgs(params);
9280        } else {
9281            return new FileInstallArgs(params);
9282        }
9283    }
9284
9285    /**
9286     * Create args that describe an existing installed package. Typically used
9287     * when cleaning up old installs, or used as a move source.
9288     */
9289    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9290            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9291        final boolean isInAsec;
9292        if (installOnSd(installFlags)) {
9293            /* Apps on SD card are always in ASEC containers. */
9294            isInAsec = true;
9295        } else if (installForwardLocked(installFlags)
9296                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9297            /*
9298             * Forward-locked apps are only in ASEC containers if they're the
9299             * new style
9300             */
9301            isInAsec = true;
9302        } else {
9303            isInAsec = false;
9304        }
9305
9306        if (isInAsec) {
9307            return new AsecInstallArgs(codePath, instructionSets,
9308                    installOnSd(installFlags), installForwardLocked(installFlags));
9309        } else {
9310            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9311                    instructionSets);
9312        }
9313    }
9314
9315    static abstract class InstallArgs {
9316        /** @see InstallParams#origin */
9317        final OriginInfo origin;
9318
9319        final IPackageInstallObserver2 observer;
9320        // Always refers to PackageManager flags only
9321        final int installFlags;
9322        final String installerPackageName;
9323        final ManifestDigest manifestDigest;
9324        final UserHandle user;
9325        final String abiOverride;
9326
9327        // The list of instruction sets supported by this app. This is currently
9328        // only used during the rmdex() phase to clean up resources. We can get rid of this
9329        // if we move dex files under the common app path.
9330        /* nullable */ String[] instructionSets;
9331
9332        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9333                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9334                String[] instructionSets, String abiOverride) {
9335            this.origin = origin;
9336            this.installFlags = installFlags;
9337            this.observer = observer;
9338            this.installerPackageName = installerPackageName;
9339            this.manifestDigest = manifestDigest;
9340            this.user = user;
9341            this.instructionSets = instructionSets;
9342            this.abiOverride = abiOverride;
9343        }
9344
9345        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9346        abstract int doPreInstall(int status);
9347
9348        /**
9349         * Rename package into final resting place. All paths on the given
9350         * scanned package should be updated to reflect the rename.
9351         */
9352        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9353        abstract int doPostInstall(int status, int uid);
9354
9355        /** @see PackageSettingBase#codePathString */
9356        abstract String getCodePath();
9357        /** @see PackageSettingBase#resourcePathString */
9358        abstract String getResourcePath();
9359        abstract String getLegacyNativeLibraryPath();
9360
9361        // Need installer lock especially for dex file removal.
9362        abstract void cleanUpResourcesLI();
9363        abstract boolean doPostDeleteLI(boolean delete);
9364        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9365
9366        /**
9367         * Called before the source arguments are copied. This is used mostly
9368         * for MoveParams when it needs to read the source file to put it in the
9369         * destination.
9370         */
9371        int doPreCopy() {
9372            return PackageManager.INSTALL_SUCCEEDED;
9373        }
9374
9375        /**
9376         * Called after the source arguments are copied. This is used mostly for
9377         * MoveParams when it needs to read the source file to put it in the
9378         * destination.
9379         *
9380         * @return
9381         */
9382        int doPostCopy(int uid) {
9383            return PackageManager.INSTALL_SUCCEEDED;
9384        }
9385
9386        protected boolean isFwdLocked() {
9387            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9388        }
9389
9390        protected boolean isExternal() {
9391            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9392        }
9393
9394        UserHandle getUser() {
9395            return user;
9396        }
9397    }
9398
9399    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9400        if (!allCodePaths.isEmpty()) {
9401            if (instructionSets == null) {
9402                throw new IllegalStateException("instructionSet == null");
9403            }
9404            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9405            for (String codePath : allCodePaths) {
9406                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9407                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9408                    if (retCode < 0) {
9409                        Slog.w(TAG, "Couldn't remove dex file for package: "
9410                                + " at location " + codePath + ", retcode=" + retCode);
9411                        // we don't consider this to be a failure of the core package deletion
9412                    }
9413                }
9414            }
9415        }
9416    }
9417
9418    /**
9419     * Logic to handle installation of non-ASEC applications, including copying
9420     * and renaming logic.
9421     */
9422    class FileInstallArgs extends InstallArgs {
9423        private File codeFile;
9424        private File resourceFile;
9425        private File legacyNativeLibraryPath;
9426
9427        // Example topology:
9428        // /data/app/com.example/base.apk
9429        // /data/app/com.example/split_foo.apk
9430        // /data/app/com.example/lib/arm/libfoo.so
9431        // /data/app/com.example/lib/arm64/libfoo.so
9432        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9433
9434        /** New install */
9435        FileInstallArgs(InstallParams params) {
9436            super(params.origin, params.observer, params.installFlags,
9437                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9438                    null /* instruction sets */, params.packageAbiOverride);
9439            if (isFwdLocked()) {
9440                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9441            }
9442        }
9443
9444        /** Existing install */
9445        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9446                String[] instructionSets) {
9447            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9448            this.codeFile = (codePath != null) ? new File(codePath) : null;
9449            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9450            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9451                    new File(legacyNativeLibraryPath) : null;
9452        }
9453
9454        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9455            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9456                    isFwdLocked(), abiOverride);
9457
9458            final StorageManager storage = StorageManager.from(mContext);
9459            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9460        }
9461
9462        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9463            if (origin.staged) {
9464                Slog.d(TAG, origin.file + " already staged; skipping copy");
9465                codeFile = origin.file;
9466                resourceFile = origin.file;
9467                return PackageManager.INSTALL_SUCCEEDED;
9468            }
9469
9470            try {
9471                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9472                codeFile = tempDir;
9473                resourceFile = tempDir;
9474            } catch (IOException e) {
9475                Slog.w(TAG, "Failed to create copy file: " + e);
9476                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9477            }
9478
9479            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9480                @Override
9481                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9482                    if (!FileUtils.isValidExtFilename(name)) {
9483                        throw new IllegalArgumentException("Invalid filename: " + name);
9484                    }
9485                    try {
9486                        final File file = new File(codeFile, name);
9487                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9488                                O_RDWR | O_CREAT, 0644);
9489                        Os.chmod(file.getAbsolutePath(), 0644);
9490                        return new ParcelFileDescriptor(fd);
9491                    } catch (ErrnoException e) {
9492                        throw new RemoteException("Failed to open: " + e.getMessage());
9493                    }
9494                }
9495            };
9496
9497            int ret = PackageManager.INSTALL_SUCCEEDED;
9498            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9499            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9500                Slog.e(TAG, "Failed to copy package");
9501                return ret;
9502            }
9503
9504            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9505            NativeLibraryHelper.Handle handle = null;
9506            try {
9507                handle = NativeLibraryHelper.Handle.create(codeFile);
9508                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9509                        abiOverride);
9510            } catch (IOException e) {
9511                Slog.e(TAG, "Copying native libraries failed", e);
9512                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9513            } finally {
9514                IoUtils.closeQuietly(handle);
9515            }
9516
9517            return ret;
9518        }
9519
9520        int doPreInstall(int status) {
9521            if (status != PackageManager.INSTALL_SUCCEEDED) {
9522                cleanUp();
9523            }
9524            return status;
9525        }
9526
9527        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9528            if (status != PackageManager.INSTALL_SUCCEEDED) {
9529                cleanUp();
9530                return false;
9531            } else {
9532                final File beforeCodeFile = codeFile;
9533                final File afterCodeFile = getNextCodePath(pkg.packageName);
9534
9535                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9536                try {
9537                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9538                } catch (ErrnoException e) {
9539                    Slog.d(TAG, "Failed to rename", e);
9540                    return false;
9541                }
9542
9543                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9544                    Slog.d(TAG, "Failed to restorecon");
9545                    return false;
9546                }
9547
9548                // Reflect the rename internally
9549                codeFile = afterCodeFile;
9550                resourceFile = afterCodeFile;
9551
9552                // Reflect the rename in scanned details
9553                pkg.codePath = afterCodeFile.getAbsolutePath();
9554                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9555                        pkg.baseCodePath);
9556                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9557                        pkg.splitCodePaths);
9558
9559                // Reflect the rename in app info
9560                pkg.applicationInfo.setCodePath(pkg.codePath);
9561                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9562                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9563                pkg.applicationInfo.setResourcePath(pkg.codePath);
9564                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9565                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9566
9567                return true;
9568            }
9569        }
9570
9571        int doPostInstall(int status, int uid) {
9572            if (status != PackageManager.INSTALL_SUCCEEDED) {
9573                cleanUp();
9574            }
9575            return status;
9576        }
9577
9578        @Override
9579        String getCodePath() {
9580            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9581        }
9582
9583        @Override
9584        String getResourcePath() {
9585            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9586        }
9587
9588        @Override
9589        String getLegacyNativeLibraryPath() {
9590            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9591        }
9592
9593        private boolean cleanUp() {
9594            if (codeFile == null || !codeFile.exists()) {
9595                return false;
9596            }
9597
9598            if (codeFile.isDirectory()) {
9599                FileUtils.deleteContents(codeFile);
9600            }
9601            codeFile.delete();
9602
9603            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9604                resourceFile.delete();
9605            }
9606
9607            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9608                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9609                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9610                }
9611                legacyNativeLibraryPath.delete();
9612            }
9613
9614            return true;
9615        }
9616
9617        void cleanUpResourcesLI() {
9618            // Try enumerating all code paths before deleting
9619            List<String> allCodePaths = Collections.EMPTY_LIST;
9620            if (codeFile != null && codeFile.exists()) {
9621                try {
9622                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9623                    allCodePaths = pkg.getAllCodePaths();
9624                } catch (PackageParserException e) {
9625                    // Ignored; we tried our best
9626                }
9627            }
9628
9629            cleanUp();
9630            removeDexFiles(allCodePaths, instructionSets);
9631        }
9632
9633        boolean doPostDeleteLI(boolean delete) {
9634            // XXX err, shouldn't we respect the delete flag?
9635            cleanUpResourcesLI();
9636            return true;
9637        }
9638    }
9639
9640    private boolean isAsecExternal(String cid) {
9641        final String asecPath = PackageHelper.getSdFilesystem(cid);
9642        return !asecPath.startsWith(mAsecInternalPath);
9643    }
9644
9645    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9646            PackageManagerException {
9647        if (copyRet < 0) {
9648            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9649                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9650                throw new PackageManagerException(copyRet, message);
9651            }
9652        }
9653    }
9654
9655    /**
9656     * Extract the MountService "container ID" from the full code path of an
9657     * .apk.
9658     */
9659    static String cidFromCodePath(String fullCodePath) {
9660        int eidx = fullCodePath.lastIndexOf("/");
9661        String subStr1 = fullCodePath.substring(0, eidx);
9662        int sidx = subStr1.lastIndexOf("/");
9663        return subStr1.substring(sidx+1, eidx);
9664    }
9665
9666    /**
9667     * Logic to handle installation of ASEC applications, including copying and
9668     * renaming logic.
9669     */
9670    class AsecInstallArgs extends InstallArgs {
9671        static final String RES_FILE_NAME = "pkg.apk";
9672        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9673
9674        String cid;
9675        String packagePath;
9676        String resourcePath;
9677        String legacyNativeLibraryDir;
9678
9679        /** New install */
9680        AsecInstallArgs(InstallParams params) {
9681            super(params.origin, params.observer, params.installFlags,
9682                    params.installerPackageName, params.getManifestDigest(),
9683                    params.getUser(), null /* instruction sets */,
9684                    params.packageAbiOverride);
9685        }
9686
9687        /** Existing install */
9688        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9689                        boolean isExternal, boolean isForwardLocked) {
9690            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9691                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9692                    instructionSets, null);
9693            // Hackily pretend we're still looking at a full code path
9694            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9695                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9696            }
9697
9698            // Extract cid from fullCodePath
9699            int eidx = fullCodePath.lastIndexOf("/");
9700            String subStr1 = fullCodePath.substring(0, eidx);
9701            int sidx = subStr1.lastIndexOf("/");
9702            cid = subStr1.substring(sidx+1, eidx);
9703            setMountPath(subStr1);
9704        }
9705
9706        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9707            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9708                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9709                    instructionSets, null);
9710            this.cid = cid;
9711            setMountPath(PackageHelper.getSdDir(cid));
9712        }
9713
9714        void createCopyFile() {
9715            cid = mInstallerService.allocateExternalStageCidLegacy();
9716        }
9717
9718        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9719            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9720                    abiOverride);
9721
9722            final File target;
9723            if (isExternal()) {
9724                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9725            } else {
9726                target = Environment.getDataDirectory();
9727            }
9728
9729            final StorageManager storage = StorageManager.from(mContext);
9730            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9731        }
9732
9733        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9734            if (origin.staged) {
9735                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9736                cid = origin.cid;
9737                setMountPath(PackageHelper.getSdDir(cid));
9738                return PackageManager.INSTALL_SUCCEEDED;
9739            }
9740
9741            if (temp) {
9742                createCopyFile();
9743            } else {
9744                /*
9745                 * Pre-emptively destroy the container since it's destroyed if
9746                 * copying fails due to it existing anyway.
9747                 */
9748                PackageHelper.destroySdDir(cid);
9749            }
9750
9751            final String newMountPath = imcs.copyPackageToContainer(
9752                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9753                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9754
9755            if (newMountPath != null) {
9756                setMountPath(newMountPath);
9757                return PackageManager.INSTALL_SUCCEEDED;
9758            } else {
9759                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9760            }
9761        }
9762
9763        @Override
9764        String getCodePath() {
9765            return packagePath;
9766        }
9767
9768        @Override
9769        String getResourcePath() {
9770            return resourcePath;
9771        }
9772
9773        @Override
9774        String getLegacyNativeLibraryPath() {
9775            return legacyNativeLibraryDir;
9776        }
9777
9778        int doPreInstall(int status) {
9779            if (status != PackageManager.INSTALL_SUCCEEDED) {
9780                // Destroy container
9781                PackageHelper.destroySdDir(cid);
9782            } else {
9783                boolean mounted = PackageHelper.isContainerMounted(cid);
9784                if (!mounted) {
9785                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9786                            Process.SYSTEM_UID);
9787                    if (newMountPath != null) {
9788                        setMountPath(newMountPath);
9789                    } else {
9790                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9791                    }
9792                }
9793            }
9794            return status;
9795        }
9796
9797        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9798            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9799            String newMountPath = null;
9800            if (PackageHelper.isContainerMounted(cid)) {
9801                // Unmount the container
9802                if (!PackageHelper.unMountSdDir(cid)) {
9803                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9804                    return false;
9805                }
9806            }
9807            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9808                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9809                        " which might be stale. Will try to clean up.");
9810                // Clean up the stale container and proceed to recreate.
9811                if (!PackageHelper.destroySdDir(newCacheId)) {
9812                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9813                    return false;
9814                }
9815                // Successfully cleaned up stale container. Try to rename again.
9816                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9817                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9818                            + " inspite of cleaning it up.");
9819                    return false;
9820                }
9821            }
9822            if (!PackageHelper.isContainerMounted(newCacheId)) {
9823                Slog.w(TAG, "Mounting container " + newCacheId);
9824                newMountPath = PackageHelper.mountSdDir(newCacheId,
9825                        getEncryptKey(), Process.SYSTEM_UID);
9826            } else {
9827                newMountPath = PackageHelper.getSdDir(newCacheId);
9828            }
9829            if (newMountPath == null) {
9830                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9831                return false;
9832            }
9833            Log.i(TAG, "Succesfully renamed " + cid +
9834                    " to " + newCacheId +
9835                    " at new path: " + newMountPath);
9836            cid = newCacheId;
9837
9838            final File beforeCodeFile = new File(packagePath);
9839            setMountPath(newMountPath);
9840            final File afterCodeFile = new File(packagePath);
9841
9842            // Reflect the rename in scanned details
9843            pkg.codePath = afterCodeFile.getAbsolutePath();
9844            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9845                    pkg.baseCodePath);
9846            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9847                    pkg.splitCodePaths);
9848
9849            // Reflect the rename in app info
9850            pkg.applicationInfo.setCodePath(pkg.codePath);
9851            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9852            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9853            pkg.applicationInfo.setResourcePath(pkg.codePath);
9854            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9855            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9856
9857            return true;
9858        }
9859
9860        private void setMountPath(String mountPath) {
9861            final File mountFile = new File(mountPath);
9862
9863            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9864            if (monolithicFile.exists()) {
9865                packagePath = monolithicFile.getAbsolutePath();
9866                if (isFwdLocked()) {
9867                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9868                } else {
9869                    resourcePath = packagePath;
9870                }
9871            } else {
9872                packagePath = mountFile.getAbsolutePath();
9873                resourcePath = packagePath;
9874            }
9875
9876            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9877        }
9878
9879        int doPostInstall(int status, int uid) {
9880            if (status != PackageManager.INSTALL_SUCCEEDED) {
9881                cleanUp();
9882            } else {
9883                final int groupOwner;
9884                final String protectedFile;
9885                if (isFwdLocked()) {
9886                    groupOwner = UserHandle.getSharedAppGid(uid);
9887                    protectedFile = RES_FILE_NAME;
9888                } else {
9889                    groupOwner = -1;
9890                    protectedFile = null;
9891                }
9892
9893                if (uid < Process.FIRST_APPLICATION_UID
9894                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9895                    Slog.e(TAG, "Failed to finalize " + cid);
9896                    PackageHelper.destroySdDir(cid);
9897                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9898                }
9899
9900                boolean mounted = PackageHelper.isContainerMounted(cid);
9901                if (!mounted) {
9902                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9903                }
9904            }
9905            return status;
9906        }
9907
9908        private void cleanUp() {
9909            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9910
9911            // Destroy secure container
9912            PackageHelper.destroySdDir(cid);
9913        }
9914
9915        private List<String> getAllCodePaths() {
9916            final File codeFile = new File(getCodePath());
9917            if (codeFile != null && codeFile.exists()) {
9918                try {
9919                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9920                    return pkg.getAllCodePaths();
9921                } catch (PackageParserException e) {
9922                    // Ignored; we tried our best
9923                }
9924            }
9925            return Collections.EMPTY_LIST;
9926        }
9927
9928        void cleanUpResourcesLI() {
9929            // Enumerate all code paths before deleting
9930            cleanUpResourcesLI(getAllCodePaths());
9931        }
9932
9933        private void cleanUpResourcesLI(List<String> allCodePaths) {
9934            cleanUp();
9935            removeDexFiles(allCodePaths, instructionSets);
9936        }
9937
9938
9939
9940        String getPackageName() {
9941            return getAsecPackageName(cid);
9942        }
9943
9944        boolean doPostDeleteLI(boolean delete) {
9945            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9946            final List<String> allCodePaths = getAllCodePaths();
9947            boolean mounted = PackageHelper.isContainerMounted(cid);
9948            if (mounted) {
9949                // Unmount first
9950                if (PackageHelper.unMountSdDir(cid)) {
9951                    mounted = false;
9952                }
9953            }
9954            if (!mounted && delete) {
9955                cleanUpResourcesLI(allCodePaths);
9956            }
9957            return !mounted;
9958        }
9959
9960        @Override
9961        int doPreCopy() {
9962            if (isFwdLocked()) {
9963                if (!PackageHelper.fixSdPermissions(cid,
9964                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9965                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9966                }
9967            }
9968
9969            return PackageManager.INSTALL_SUCCEEDED;
9970        }
9971
9972        @Override
9973        int doPostCopy(int uid) {
9974            if (isFwdLocked()) {
9975                if (uid < Process.FIRST_APPLICATION_UID
9976                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9977                                RES_FILE_NAME)) {
9978                    Slog.e(TAG, "Failed to finalize " + cid);
9979                    PackageHelper.destroySdDir(cid);
9980                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9981                }
9982            }
9983
9984            return PackageManager.INSTALL_SUCCEEDED;
9985        }
9986    }
9987
9988    static String getAsecPackageName(String packageCid) {
9989        int idx = packageCid.lastIndexOf("-");
9990        if (idx == -1) {
9991            return packageCid;
9992        }
9993        return packageCid.substring(0, idx);
9994    }
9995
9996    // Utility method used to create code paths based on package name and available index.
9997    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9998        String idxStr = "";
9999        int idx = 1;
10000        // Fall back to default value of idx=1 if prefix is not
10001        // part of oldCodePath
10002        if (oldCodePath != null) {
10003            String subStr = oldCodePath;
10004            // Drop the suffix right away
10005            if (suffix != null && subStr.endsWith(suffix)) {
10006                subStr = subStr.substring(0, subStr.length() - suffix.length());
10007            }
10008            // If oldCodePath already contains prefix find out the
10009            // ending index to either increment or decrement.
10010            int sidx = subStr.lastIndexOf(prefix);
10011            if (sidx != -1) {
10012                subStr = subStr.substring(sidx + prefix.length());
10013                if (subStr != null) {
10014                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10015                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10016                    }
10017                    try {
10018                        idx = Integer.parseInt(subStr);
10019                        if (idx <= 1) {
10020                            idx++;
10021                        } else {
10022                            idx--;
10023                        }
10024                    } catch(NumberFormatException e) {
10025                    }
10026                }
10027            }
10028        }
10029        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10030        return prefix + idxStr;
10031    }
10032
10033    private File getNextCodePath(String packageName) {
10034        int suffix = 1;
10035        File result;
10036        do {
10037            result = new File(mAppInstallDir, packageName + "-" + suffix);
10038            suffix++;
10039        } while (result.exists());
10040        return result;
10041    }
10042
10043    // Utility method used to ignore ADD/REMOVE events
10044    // by directory observer.
10045    private static boolean ignoreCodePath(String fullPathStr) {
10046        String apkName = deriveCodePathName(fullPathStr);
10047        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
10048        if (idx != -1 && ((idx+1) < apkName.length())) {
10049            // Make sure the package ends with a numeral
10050            String version = apkName.substring(idx+1);
10051            try {
10052                Integer.parseInt(version);
10053                return true;
10054            } catch (NumberFormatException e) {}
10055        }
10056        return false;
10057    }
10058
10059    // Utility method that returns the relative package path with respect
10060    // to the installation directory. Like say for /data/data/com.test-1.apk
10061    // string com.test-1 is returned.
10062    static String deriveCodePathName(String codePath) {
10063        if (codePath == null) {
10064            return null;
10065        }
10066        final File codeFile = new File(codePath);
10067        final String name = codeFile.getName();
10068        if (codeFile.isDirectory()) {
10069            return name;
10070        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10071            final int lastDot = name.lastIndexOf('.');
10072            return name.substring(0, lastDot);
10073        } else {
10074            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10075            return null;
10076        }
10077    }
10078
10079    class PackageInstalledInfo {
10080        String name;
10081        int uid;
10082        // The set of users that originally had this package installed.
10083        int[] origUsers;
10084        // The set of users that now have this package installed.
10085        int[] newUsers;
10086        PackageParser.Package pkg;
10087        int returnCode;
10088        String returnMsg;
10089        PackageRemovedInfo removedInfo;
10090
10091        public void setError(int code, String msg) {
10092            returnCode = code;
10093            returnMsg = msg;
10094            Slog.w(TAG, msg);
10095        }
10096
10097        public void setError(String msg, PackageParserException e) {
10098            returnCode = e.error;
10099            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10100            Slog.w(TAG, msg, e);
10101        }
10102
10103        public void setError(String msg, PackageManagerException e) {
10104            returnCode = e.error;
10105            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10106            Slog.w(TAG, msg, e);
10107        }
10108
10109        // In some error cases we want to convey more info back to the observer
10110        String origPackage;
10111        String origPermission;
10112    }
10113
10114    /*
10115     * Install a non-existing package.
10116     */
10117    private void installNewPackageLI(PackageParser.Package pkg,
10118            int parseFlags, int scanFlags, UserHandle user,
10119            String installerPackageName, PackageInstalledInfo res) {
10120        // Remember this for later, in case we need to rollback this install
10121        String pkgName = pkg.packageName;
10122
10123        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10124        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10125        synchronized(mPackages) {
10126            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10127                // A package with the same name is already installed, though
10128                // it has been renamed to an older name.  The package we
10129                // are trying to install should be installed as an update to
10130                // the existing one, but that has not been requested, so bail.
10131                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10132                        + " without first uninstalling package running as "
10133                        + mSettings.mRenamedPackages.get(pkgName));
10134                return;
10135            }
10136            if (mPackages.containsKey(pkgName)) {
10137                // Don't allow installation over an existing package with the same name.
10138                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10139                        + " without first uninstalling.");
10140                return;
10141            }
10142        }
10143
10144        try {
10145            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10146                    System.currentTimeMillis(), user);
10147
10148            updateSettingsLI(newPackage, installerPackageName, null, null, res, user);
10149            // delete the partially installed application. the data directory will have to be
10150            // restored if it was already existing
10151            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10152                // remove package from internal structures.  Note that we want deletePackageX to
10153                // delete the package data and cache directories that it created in
10154                // scanPackageLocked, unless those directories existed before we even tried to
10155                // install.
10156                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10157                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10158                                res.removedInfo, true);
10159            }
10160
10161        } catch (PackageManagerException e) {
10162            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10163        }
10164    }
10165
10166    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10167        // Upgrade keysets are being used.  Determine if new package has a superset of the
10168        // required keys.
10169        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10170        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10171        for (int i = 0; i < upgradeKeySets.length; i++) {
10172            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10173            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10174                return true;
10175            }
10176        }
10177        return false;
10178    }
10179
10180    private void replacePackageLI(PackageParser.Package pkg,
10181            int parseFlags, int scanFlags, UserHandle user,
10182            String installerPackageName, PackageInstalledInfo res) {
10183        PackageParser.Package oldPackage;
10184        String pkgName = pkg.packageName;
10185        int[] allUsers;
10186        boolean[] perUserInstalled;
10187
10188        // First find the old package info and check signatures
10189        synchronized(mPackages) {
10190            oldPackage = mPackages.get(pkgName);
10191            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10192            PackageSetting ps = mSettings.mPackages.get(pkgName);
10193            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10194                // default to original signature matching
10195                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10196                    != PackageManager.SIGNATURE_MATCH) {
10197                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10198                            "New package has a different signature: " + pkgName);
10199                    return;
10200                }
10201            } else {
10202                if(!checkUpgradeKeySetLP(ps, pkg)) {
10203                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10204                            "New package not signed by keys specified by upgrade-keysets: "
10205                            + pkgName);
10206                    return;
10207                }
10208            }
10209
10210            // In case of rollback, remember per-user/profile install state
10211            allUsers = sUserManager.getUserIds();
10212            perUserInstalled = new boolean[allUsers.length];
10213            for (int i = 0; i < allUsers.length; i++) {
10214                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10215            }
10216        }
10217
10218        boolean sysPkg = (isSystemApp(oldPackage));
10219        if (sysPkg) {
10220            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10221                    user, allUsers, perUserInstalled, installerPackageName, res);
10222        } else {
10223            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10224                    user, allUsers, perUserInstalled, installerPackageName, res);
10225        }
10226    }
10227
10228    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10229            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10230            int[] allUsers, boolean[] perUserInstalled,
10231            String installerPackageName, PackageInstalledInfo res) {
10232        String pkgName = deletedPackage.packageName;
10233        boolean deletedPkg = true;
10234        boolean updatedSettings = false;
10235
10236        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10237                + deletedPackage);
10238        long origUpdateTime;
10239        if (pkg.mExtras != null) {
10240            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10241        } else {
10242            origUpdateTime = 0;
10243        }
10244
10245        // First delete the existing package while retaining the data directory
10246        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10247                res.removedInfo, true)) {
10248            // If the existing package wasn't successfully deleted
10249            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10250            deletedPkg = false;
10251        } else {
10252            // Successfully deleted the old package; proceed with replace.
10253
10254            // If deleted package lived in a container, give users a chance to
10255            // relinquish resources before killing.
10256            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10257                if (DEBUG_INSTALL) {
10258                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10259                }
10260                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10261                final ArrayList<String> pkgList = new ArrayList<String>(1);
10262                pkgList.add(deletedPackage.applicationInfo.packageName);
10263                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10264            }
10265
10266            deleteCodeCacheDirsLI(pkgName);
10267            try {
10268                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10269                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10270                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res,
10271                        user);
10272                updatedSettings = true;
10273            } catch (PackageManagerException e) {
10274                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10275            }
10276        }
10277
10278        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10279            // remove package from internal structures.  Note that we want deletePackageX to
10280            // delete the package data and cache directories that it created in
10281            // scanPackageLocked, unless those directories existed before we even tried to
10282            // install.
10283            if(updatedSettings) {
10284                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10285                deletePackageLI(
10286                        pkgName, null, true, allUsers, perUserInstalled,
10287                        PackageManager.DELETE_KEEP_DATA,
10288                                res.removedInfo, true);
10289            }
10290            // Since we failed to install the new package we need to restore the old
10291            // package that we deleted.
10292            if (deletedPkg) {
10293                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10294                File restoreFile = new File(deletedPackage.codePath);
10295                // Parse old package
10296                boolean oldOnSd = isExternal(deletedPackage);
10297                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10298                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10299                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10300                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10301                try {
10302                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10303                } catch (PackageManagerException e) {
10304                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10305                            + e.getMessage());
10306                    return;
10307                }
10308                // Restore of old package succeeded. Update permissions.
10309                // writer
10310                synchronized (mPackages) {
10311                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10312                            UPDATE_PERMISSIONS_ALL);
10313                    // can downgrade to reader
10314                    mSettings.writeLPr();
10315                }
10316                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10317            }
10318        }
10319    }
10320
10321    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10322            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10323            int[] allUsers, boolean[] perUserInstalled,
10324            String installerPackageName, PackageInstalledInfo res) {
10325        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10326                + ", old=" + deletedPackage);
10327        boolean disabledSystem = false;
10328        boolean updatedSettings = false;
10329        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10330        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10331                != 0) {
10332            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10333        }
10334        String packageName = deletedPackage.packageName;
10335        if (packageName == null) {
10336            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10337                    "Attempt to delete null packageName.");
10338            return;
10339        }
10340        PackageParser.Package oldPkg;
10341        PackageSetting oldPkgSetting;
10342        // reader
10343        synchronized (mPackages) {
10344            oldPkg = mPackages.get(packageName);
10345            oldPkgSetting = mSettings.mPackages.get(packageName);
10346            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10347                    (oldPkgSetting == null)) {
10348                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10349                        "Couldn't find package:" + packageName + " information");
10350                return;
10351            }
10352        }
10353
10354        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10355
10356        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10357        res.removedInfo.removedPackage = packageName;
10358        // Remove existing system package
10359        removePackageLI(oldPkgSetting, true);
10360        // writer
10361        synchronized (mPackages) {
10362            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10363            if (!disabledSystem && deletedPackage != null) {
10364                // We didn't need to disable the .apk as a current system package,
10365                // which means we are replacing another update that is already
10366                // installed.  We need to make sure to delete the older one's .apk.
10367                res.removedInfo.args = createInstallArgsForExisting(0,
10368                        deletedPackage.applicationInfo.getCodePath(),
10369                        deletedPackage.applicationInfo.getResourcePath(),
10370                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10371                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10372            } else {
10373                res.removedInfo.args = null;
10374            }
10375        }
10376
10377        // Successfully disabled the old package. Now proceed with re-installation
10378        deleteCodeCacheDirsLI(packageName);
10379
10380        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10381        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10382
10383        PackageParser.Package newPackage = null;
10384        try {
10385            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10386            if (newPackage.mExtras != null) {
10387                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10388                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10389                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10390
10391                // is the update attempting to change shared user? that isn't going to work...
10392                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10393                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10394                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10395                            + " to " + newPkgSetting.sharedUser);
10396                    updatedSettings = true;
10397                }
10398            }
10399
10400            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10401                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res,
10402                        user);
10403                updatedSettings = true;
10404            }
10405
10406        } catch (PackageManagerException e) {
10407            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10408        }
10409
10410        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10411            // Re installation failed. Restore old information
10412            // Remove new pkg information
10413            if (newPackage != null) {
10414                removeInstalledPackageLI(newPackage, true);
10415            }
10416            // Add back the old system package
10417            try {
10418                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10419            } catch (PackageManagerException e) {
10420                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10421            }
10422            // Restore the old system information in Settings
10423            synchronized (mPackages) {
10424                if (disabledSystem) {
10425                    mSettings.enableSystemPackageLPw(packageName);
10426                }
10427                if (updatedSettings) {
10428                    mSettings.setInstallerPackageName(packageName,
10429                            oldPkgSetting.installerPackageName);
10430                }
10431                mSettings.writeLPr();
10432            }
10433        }
10434    }
10435
10436    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10437            int[] allUsers, boolean[] perUserInstalled,
10438            PackageInstalledInfo res, UserHandle user) {
10439        String pkgName = newPackage.packageName;
10440        synchronized (mPackages) {
10441            //write settings. the installStatus will be incomplete at this stage.
10442            //note that the new package setting would have already been
10443            //added to mPackages. It hasn't been persisted yet.
10444            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10445            mSettings.writeLPr();
10446        }
10447
10448        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10449
10450        synchronized (mPackages) {
10451            updatePermissionsLPw(newPackage.packageName, newPackage,
10452                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10453                            ? UPDATE_PERMISSIONS_ALL : 0));
10454            // For system-bundled packages, we assume that installing an upgraded version
10455            // of the package implies that the user actually wants to run that new code,
10456            // so we enable the package.
10457            PackageSetting ps = mSettings.mPackages.get(pkgName);
10458            if (ps != null) {
10459                if (isSystemApp(newPackage)) {
10460                    // NB: implicit assumption that system package upgrades apply to all users
10461                    if (DEBUG_INSTALL) {
10462                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10463                    }
10464                    if (res.origUsers != null) {
10465                        for (int userHandle : res.origUsers) {
10466                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10467                                    userHandle, installerPackageName);
10468                        }
10469                    }
10470                    // Also convey the prior install/uninstall state
10471                    if (allUsers != null && perUserInstalled != null) {
10472                        for (int i = 0; i < allUsers.length; i++) {
10473                            if (DEBUG_INSTALL) {
10474                                Slog.d(TAG, "    user " + allUsers[i]
10475                                        + " => " + perUserInstalled[i]);
10476                            }
10477                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10478                        }
10479                        // these install state changes will be persisted in the
10480                        // upcoming call to mSettings.writeLPr().
10481                    }
10482                }
10483                // It's implied that when a user requests installation, they want the app to be
10484                // installed and enabled.
10485                int userId = user.getIdentifier();
10486                if (userId != UserHandle.USER_ALL) {
10487                    ps.setInstalled(true, userId);
10488                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
10489                }
10490            }
10491            res.name = pkgName;
10492            res.uid = newPackage.applicationInfo.uid;
10493            res.pkg = newPackage;
10494            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10495            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10496            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10497            //to update install status
10498            mSettings.writeLPr();
10499        }
10500    }
10501
10502    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10503        final int installFlags = args.installFlags;
10504        String installerPackageName = args.installerPackageName;
10505        File tmpPackageFile = new File(args.getCodePath());
10506        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10507        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10508        boolean replace = false;
10509        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10510        // Result object to be returned
10511        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10512
10513        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10514        // Retrieve PackageSettings and parse package
10515        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10516                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10517                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10518        PackageParser pp = new PackageParser();
10519        pp.setSeparateProcesses(mSeparateProcesses);
10520        pp.setDisplayMetrics(mMetrics);
10521
10522        final PackageParser.Package pkg;
10523        try {
10524            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10525        } catch (PackageParserException e) {
10526            res.setError("Failed parse during installPackageLI", e);
10527            return;
10528        }
10529
10530        // Mark that we have an install time CPU ABI override.
10531        pkg.cpuAbiOverride = args.abiOverride;
10532
10533        String pkgName = res.name = pkg.packageName;
10534        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10535            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10536                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10537                return;
10538            }
10539        }
10540
10541        try {
10542            pp.collectCertificates(pkg, parseFlags);
10543            pp.collectManifestDigest(pkg);
10544        } catch (PackageParserException e) {
10545            res.setError("Failed collect during installPackageLI", e);
10546            return;
10547        }
10548
10549        /* If the installer passed in a manifest digest, compare it now. */
10550        if (args.manifestDigest != null) {
10551            if (DEBUG_INSTALL) {
10552                final String parsedManifest = pkg.manifestDigest == null ? "null"
10553                        : pkg.manifestDigest.toString();
10554                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10555                        + parsedManifest);
10556            }
10557
10558            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10559                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10560                return;
10561            }
10562        } else if (DEBUG_INSTALL) {
10563            final String parsedManifest = pkg.manifestDigest == null
10564                    ? "null" : pkg.manifestDigest.toString();
10565            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10566        }
10567
10568        // Get rid of all references to package scan path via parser.
10569        pp = null;
10570        String oldCodePath = null;
10571        boolean systemApp = false;
10572        synchronized (mPackages) {
10573            // Check if installing already existing package
10574            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10575                String oldName = mSettings.mRenamedPackages.get(pkgName);
10576                if (pkg.mOriginalPackages != null
10577                        && pkg.mOriginalPackages.contains(oldName)
10578                        && mPackages.containsKey(oldName)) {
10579                    // This package is derived from an original package,
10580                    // and this device has been updating from that original
10581                    // name.  We must continue using the original name, so
10582                    // rename the new package here.
10583                    pkg.setPackageName(oldName);
10584                    pkgName = pkg.packageName;
10585                    replace = true;
10586                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10587                            + oldName + " pkgName=" + pkgName);
10588                } else if (mPackages.containsKey(pkgName)) {
10589                    // This package, under its official name, already exists
10590                    // on the device; we should replace it.
10591                    replace = true;
10592                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10593                }
10594            }
10595
10596            PackageSetting ps = mSettings.mPackages.get(pkgName);
10597            if (ps != null) {
10598                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10599
10600                // Quick sanity check that we're signed correctly if updating;
10601                // we'll check this again later when scanning, but we want to
10602                // bail early here before tripping over redefined permissions.
10603                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10604                    try {
10605                        verifySignaturesLP(ps, pkg);
10606                    } catch (PackageManagerException e) {
10607                        res.setError(e.error, e.getMessage());
10608                        return;
10609                    }
10610                } else {
10611                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10612                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10613                                + pkg.packageName + " upgrade keys do not match the "
10614                                + "previously installed version");
10615                        return;
10616                    }
10617                }
10618
10619                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10620                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10621                    systemApp = (ps.pkg.applicationInfo.flags &
10622                            ApplicationInfo.FLAG_SYSTEM) != 0;
10623                }
10624                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10625            }
10626
10627            // Check whether the newly-scanned package wants to define an already-defined perm
10628            int N = pkg.permissions.size();
10629            for (int i = N-1; i >= 0; i--) {
10630                PackageParser.Permission perm = pkg.permissions.get(i);
10631                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10632                if (bp != null) {
10633                    // If the defining package is signed with our cert, it's okay.  This
10634                    // also includes the "updating the same package" case, of course.
10635                    // "updating same package" could also involve key-rotation.
10636                    final boolean sigsOk;
10637                    if (!bp.sourcePackage.equals(pkg.packageName)
10638                            || !(bp.packageSetting instanceof PackageSetting)
10639                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10640                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10641                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10642                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10643                    } else {
10644                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10645                    }
10646                    if (!sigsOk) {
10647                        // If the owning package is the system itself, we log but allow
10648                        // install to proceed; we fail the install on all other permission
10649                        // redefinitions.
10650                        if (!bp.sourcePackage.equals("android")) {
10651                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10652                                    + pkg.packageName + " attempting to redeclare permission "
10653                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10654                            res.origPermission = perm.info.name;
10655                            res.origPackage = bp.sourcePackage;
10656                            return;
10657                        } else {
10658                            Slog.w(TAG, "Package " + pkg.packageName
10659                                    + " attempting to redeclare system permission "
10660                                    + perm.info.name + "; ignoring new declaration");
10661                            pkg.permissions.remove(i);
10662                        }
10663                    }
10664                }
10665            }
10666
10667        }
10668
10669        if (systemApp && onSd) {
10670            // Disable updates to system apps on sdcard
10671            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10672                    "Cannot install updates to system apps on sdcard");
10673            return;
10674        }
10675
10676        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10677            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10678            return;
10679        }
10680
10681        if (replace) {
10682            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10683                    installerPackageName, res);
10684        } else {
10685            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10686                    args.user, installerPackageName, res);
10687        }
10688        synchronized (mPackages) {
10689            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10690            if (ps != null) {
10691                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10692            }
10693        }
10694    }
10695
10696    private static boolean isMultiArch(PackageSetting ps) {
10697        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10698    }
10699
10700    private static boolean isMultiArch(ApplicationInfo info) {
10701        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10702    }
10703
10704    private static boolean isExternal(PackageParser.Package pkg) {
10705        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10706    }
10707
10708    private static boolean isExternal(PackageSetting ps) {
10709        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10710    }
10711
10712    private static boolean isExternal(ApplicationInfo info) {
10713        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10714    }
10715
10716    private static boolean isSystemApp(PackageParser.Package pkg) {
10717        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10718    }
10719
10720    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10721        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
10722    }
10723
10724    private static boolean isSystemApp(ApplicationInfo info) {
10725        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10726    }
10727
10728    private static boolean isSystemApp(PackageSetting ps) {
10729        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10730    }
10731
10732    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10733        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10734    }
10735
10736    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10737        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10738    }
10739
10740    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10741        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10742    }
10743
10744    private int packageFlagsToInstallFlags(PackageSetting ps) {
10745        int installFlags = 0;
10746        if (isExternal(ps)) {
10747            installFlags |= PackageManager.INSTALL_EXTERNAL;
10748        }
10749        if (ps.isForwardLocked()) {
10750            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10751        }
10752        return installFlags;
10753    }
10754
10755    private void deleteTempPackageFiles() {
10756        final FilenameFilter filter = new FilenameFilter() {
10757            public boolean accept(File dir, String name) {
10758                return name.startsWith("vmdl") && name.endsWith(".tmp");
10759            }
10760        };
10761        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10762            file.delete();
10763        }
10764    }
10765
10766    @Override
10767    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10768            int flags) {
10769        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10770                flags);
10771    }
10772
10773    @Override
10774    public void deletePackage(final String packageName,
10775            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10776        mContext.enforceCallingOrSelfPermission(
10777                android.Manifest.permission.DELETE_PACKAGES, null);
10778        final int uid = Binder.getCallingUid();
10779        if (UserHandle.getUserId(uid) != userId) {
10780            mContext.enforceCallingPermission(
10781                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10782                    "deletePackage for user " + userId);
10783        }
10784        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10785            try {
10786                observer.onPackageDeleted(packageName,
10787                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10788            } catch (RemoteException re) {
10789            }
10790            return;
10791        }
10792
10793        boolean uninstallBlocked = false;
10794        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10795            int[] users = sUserManager.getUserIds();
10796            for (int i = 0; i < users.length; ++i) {
10797                if (getBlockUninstallForUser(packageName, users[i])) {
10798                    uninstallBlocked = true;
10799                    break;
10800                }
10801            }
10802        } else {
10803            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10804        }
10805        if (uninstallBlocked) {
10806            try {
10807                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10808                        null);
10809            } catch (RemoteException re) {
10810            }
10811            return;
10812        }
10813
10814        if (DEBUG_REMOVE) {
10815            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10816        }
10817        // Queue up an async operation since the package deletion may take a little while.
10818        mHandler.post(new Runnable() {
10819            public void run() {
10820                mHandler.removeCallbacks(this);
10821                final int returnCode = deletePackageX(packageName, userId, flags);
10822                if (observer != null) {
10823                    try {
10824                        observer.onPackageDeleted(packageName, returnCode, null);
10825                    } catch (RemoteException e) {
10826                        Log.i(TAG, "Observer no longer exists.");
10827                    } //end catch
10828                } //end if
10829            } //end run
10830        });
10831    }
10832
10833    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10834        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10835                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10836        try {
10837            if (dpm != null) {
10838                if (dpm.isDeviceOwner(packageName)) {
10839                    return true;
10840                }
10841                int[] users;
10842                if (userId == UserHandle.USER_ALL) {
10843                    users = sUserManager.getUserIds();
10844                } else {
10845                    users = new int[]{userId};
10846                }
10847                for (int i = 0; i < users.length; ++i) {
10848                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10849                        return true;
10850                    }
10851                }
10852            }
10853        } catch (RemoteException e) {
10854        }
10855        return false;
10856    }
10857
10858    /**
10859     *  This method is an internal method that could be get invoked either
10860     *  to delete an installed package or to clean up a failed installation.
10861     *  After deleting an installed package, a broadcast is sent to notify any
10862     *  listeners that the package has been installed. For cleaning up a failed
10863     *  installation, the broadcast is not necessary since the package's
10864     *  installation wouldn't have sent the initial broadcast either
10865     *  The key steps in deleting a package are
10866     *  deleting the package information in internal structures like mPackages,
10867     *  deleting the packages base directories through installd
10868     *  updating mSettings to reflect current status
10869     *  persisting settings for later use
10870     *  sending a broadcast if necessary
10871     */
10872    private int deletePackageX(String packageName, int userId, int flags) {
10873        final PackageRemovedInfo info = new PackageRemovedInfo();
10874        final boolean res;
10875
10876        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10877                ? UserHandle.ALL : new UserHandle(userId);
10878
10879        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10880            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10881            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10882        }
10883
10884        boolean removedForAllUsers = false;
10885        boolean systemUpdate = false;
10886
10887        // for the uninstall-updates case and restricted profiles, remember the per-
10888        // userhandle installed state
10889        int[] allUsers;
10890        boolean[] perUserInstalled;
10891        synchronized (mPackages) {
10892            PackageSetting ps = mSettings.mPackages.get(packageName);
10893            allUsers = sUserManager.getUserIds();
10894            perUserInstalled = new boolean[allUsers.length];
10895            for (int i = 0; i < allUsers.length; i++) {
10896                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10897            }
10898        }
10899
10900        synchronized (mInstallLock) {
10901            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10902            res = deletePackageLI(packageName, removeForUser,
10903                    true, allUsers, perUserInstalled,
10904                    flags | REMOVE_CHATTY, info, true);
10905            systemUpdate = info.isRemovedPackageSystemUpdate;
10906            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10907                removedForAllUsers = true;
10908            }
10909            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10910                    + " removedForAllUsers=" + removedForAllUsers);
10911        }
10912
10913        if (res) {
10914            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10915
10916            // If the removed package was a system update, the old system package
10917            // was re-enabled; we need to broadcast this information
10918            if (systemUpdate) {
10919                Bundle extras = new Bundle(1);
10920                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10921                        ? info.removedAppId : info.uid);
10922                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10923
10924                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10925                        extras, null, null, null);
10926                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10927                        extras, null, null, null);
10928                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10929                        null, packageName, null, null);
10930            }
10931        }
10932        // Force a gc here.
10933        Runtime.getRuntime().gc();
10934        // Delete the resources here after sending the broadcast to let
10935        // other processes clean up before deleting resources.
10936        if (info.args != null) {
10937            synchronized (mInstallLock) {
10938                info.args.doPostDeleteLI(true);
10939            }
10940        }
10941
10942        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10943    }
10944
10945    static class PackageRemovedInfo {
10946        String removedPackage;
10947        int uid = -1;
10948        int removedAppId = -1;
10949        int[] removedUsers = null;
10950        boolean isRemovedPackageSystemUpdate = false;
10951        // Clean up resources deleted packages.
10952        InstallArgs args = null;
10953
10954        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10955            Bundle extras = new Bundle(1);
10956            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10957            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10958            if (replacing) {
10959                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10960            }
10961            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10962            if (removedPackage != null) {
10963                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10964                        extras, null, null, removedUsers);
10965                if (fullRemove && !replacing) {
10966                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10967                            extras, null, null, removedUsers);
10968                }
10969            }
10970            if (removedAppId >= 0) {
10971                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10972                        removedUsers);
10973            }
10974        }
10975    }
10976
10977    /*
10978     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10979     * flag is not set, the data directory is removed as well.
10980     * make sure this flag is set for partially installed apps. If not its meaningless to
10981     * delete a partially installed application.
10982     */
10983    private void removePackageDataLI(PackageSetting ps,
10984            int[] allUserHandles, boolean[] perUserInstalled,
10985            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10986        String packageName = ps.name;
10987        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10988        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10989        // Retrieve object to delete permissions for shared user later on
10990        final PackageSetting deletedPs;
10991        // reader
10992        synchronized (mPackages) {
10993            deletedPs = mSettings.mPackages.get(packageName);
10994            if (outInfo != null) {
10995                outInfo.removedPackage = packageName;
10996                outInfo.removedUsers = deletedPs != null
10997                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10998                        : null;
10999            }
11000        }
11001        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11002            removeDataDirsLI(packageName);
11003            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11004        }
11005        // writer
11006        synchronized (mPackages) {
11007            if (deletedPs != null) {
11008                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11009                    if (outInfo != null) {
11010                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11011                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11012                    }
11013                    updatePermissionsLPw(deletedPs.name, null, 0);
11014                    if (deletedPs.sharedUser != null) {
11015                        // Remove permissions associated with package. Since runtime
11016                        // permissions are per user we have to kill the removed package
11017                        // or packages running under the shared user of the removed
11018                        // package if revoking the permissions requested only by the removed
11019                        // package is successful and this causes a change in gids.
11020                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11021                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11022                                    userId);
11023                            if (userIdToKill == userId) {
11024                                // If gids changed for this user, kill all affected packages.
11025                                killSettingPackagesForUser(deletedPs, userIdToKill,
11026                                        KILL_APP_REASON_GIDS_CHANGED);
11027                            } else if (userIdToKill == UserHandle.USER_ALL) {
11028                                // If gids changed for all users, kill them all - done.
11029                                killSettingPackagesForUser(deletedPs, userIdToKill,
11030                                        KILL_APP_REASON_GIDS_CHANGED);
11031                                break;
11032                            }
11033                        }
11034                    }
11035                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11036                }
11037                // make sure to preserve per-user disabled state if this removal was just
11038                // a downgrade of a system app to the factory package
11039                if (allUserHandles != null && perUserInstalled != null) {
11040                    if (DEBUG_REMOVE) {
11041                        Slog.d(TAG, "Propagating install state across downgrade");
11042                    }
11043                    for (int i = 0; i < allUserHandles.length; i++) {
11044                        if (DEBUG_REMOVE) {
11045                            Slog.d(TAG, "    user " + allUserHandles[i]
11046                                    + " => " + perUserInstalled[i]);
11047                        }
11048                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11049                    }
11050                }
11051            }
11052            // can downgrade to reader
11053            if (writeSettings) {
11054                // Save settings now
11055                mSettings.writeLPr();
11056            }
11057        }
11058        if (outInfo != null) {
11059            // A user ID was deleted here. Go through all users and remove it
11060            // from KeyStore.
11061            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11062        }
11063    }
11064
11065    static boolean locationIsPrivileged(File path) {
11066        try {
11067            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11068                    .getCanonicalPath();
11069            return path.getCanonicalPath().startsWith(privilegedAppDir);
11070        } catch (IOException e) {
11071            Slog.e(TAG, "Unable to access code path " + path);
11072        }
11073        return false;
11074    }
11075
11076    /*
11077     * Tries to delete system package.
11078     */
11079    private boolean deleteSystemPackageLI(PackageSetting newPs,
11080            int[] allUserHandles, boolean[] perUserInstalled,
11081            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11082        final boolean applyUserRestrictions
11083                = (allUserHandles != null) && (perUserInstalled != null);
11084        PackageSetting disabledPs = null;
11085        // Confirm if the system package has been updated
11086        // An updated system app can be deleted. This will also have to restore
11087        // the system pkg from system partition
11088        // reader
11089        synchronized (mPackages) {
11090            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11091        }
11092        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11093                + " disabledPs=" + disabledPs);
11094        if (disabledPs == null) {
11095            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11096            return false;
11097        } else if (DEBUG_REMOVE) {
11098            Slog.d(TAG, "Deleting system pkg from data partition");
11099        }
11100        if (DEBUG_REMOVE) {
11101            if (applyUserRestrictions) {
11102                Slog.d(TAG, "Remembering install states:");
11103                for (int i = 0; i < allUserHandles.length; i++) {
11104                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11105                }
11106            }
11107        }
11108        // Delete the updated package
11109        outInfo.isRemovedPackageSystemUpdate = true;
11110        if (disabledPs.versionCode < newPs.versionCode) {
11111            // Delete data for downgrades
11112            flags &= ~PackageManager.DELETE_KEEP_DATA;
11113        } else {
11114            // Preserve data by setting flag
11115            flags |= PackageManager.DELETE_KEEP_DATA;
11116        }
11117        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11118                allUserHandles, perUserInstalled, outInfo, writeSettings);
11119        if (!ret) {
11120            return false;
11121        }
11122        // writer
11123        synchronized (mPackages) {
11124            // Reinstate the old system package
11125            mSettings.enableSystemPackageLPw(newPs.name);
11126            // Remove any native libraries from the upgraded package.
11127            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11128        }
11129        // Install the system package
11130        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11131        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11132        if (locationIsPrivileged(disabledPs.codePath)) {
11133            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11134        }
11135
11136        final PackageParser.Package newPkg;
11137        try {
11138            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11139        } catch (PackageManagerException e) {
11140            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11141            return false;
11142        }
11143
11144        // writer
11145        synchronized (mPackages) {
11146            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11147            updatePermissionsLPw(newPkg.packageName, newPkg,
11148                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11149            if (applyUserRestrictions) {
11150                if (DEBUG_REMOVE) {
11151                    Slog.d(TAG, "Propagating install state across reinstall");
11152                }
11153                for (int i = 0; i < allUserHandles.length; i++) {
11154                    if (DEBUG_REMOVE) {
11155                        Slog.d(TAG, "    user " + allUserHandles[i]
11156                                + " => " + perUserInstalled[i]);
11157                    }
11158                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11159                }
11160                // Regardless of writeSettings we need to ensure that this restriction
11161                // state propagation is persisted
11162                mSettings.writeAllUsersPackageRestrictionsLPr();
11163            }
11164            // can downgrade to reader here
11165            if (writeSettings) {
11166                mSettings.writeLPr();
11167            }
11168        }
11169        return true;
11170    }
11171
11172    private boolean deleteInstalledPackageLI(PackageSetting ps,
11173            boolean deleteCodeAndResources, int flags,
11174            int[] allUserHandles, boolean[] perUserInstalled,
11175            PackageRemovedInfo outInfo, boolean writeSettings) {
11176        if (outInfo != null) {
11177            outInfo.uid = ps.appId;
11178        }
11179
11180        // Delete package data from internal structures and also remove data if flag is set
11181        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11182
11183        // Delete application code and resources
11184        if (deleteCodeAndResources && (outInfo != null)) {
11185            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11186                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11187                    getAppDexInstructionSets(ps));
11188            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11189        }
11190        return true;
11191    }
11192
11193    @Override
11194    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11195            int userId) {
11196        mContext.enforceCallingOrSelfPermission(
11197                android.Manifest.permission.DELETE_PACKAGES, null);
11198        synchronized (mPackages) {
11199            PackageSetting ps = mSettings.mPackages.get(packageName);
11200            if (ps == null) {
11201                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11202                return false;
11203            }
11204            if (!ps.getInstalled(userId)) {
11205                // Can't block uninstall for an app that is not installed or enabled.
11206                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11207                return false;
11208            }
11209            ps.setBlockUninstall(blockUninstall, userId);
11210            mSettings.writePackageRestrictionsLPr(userId);
11211        }
11212        return true;
11213    }
11214
11215    @Override
11216    public boolean getBlockUninstallForUser(String packageName, int userId) {
11217        synchronized (mPackages) {
11218            PackageSetting ps = mSettings.mPackages.get(packageName);
11219            if (ps == null) {
11220                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11221                return false;
11222            }
11223            return ps.getBlockUninstall(userId);
11224        }
11225    }
11226
11227    /*
11228     * This method handles package deletion in general
11229     */
11230    private boolean deletePackageLI(String packageName, UserHandle user,
11231            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11232            int flags, PackageRemovedInfo outInfo,
11233            boolean writeSettings) {
11234        if (packageName == null) {
11235            Slog.w(TAG, "Attempt to delete null packageName.");
11236            return false;
11237        }
11238        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11239        PackageSetting ps;
11240        boolean dataOnly = false;
11241        int removeUser = -1;
11242        int appId = -1;
11243        synchronized (mPackages) {
11244            ps = mSettings.mPackages.get(packageName);
11245            if (ps == null) {
11246                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11247                return false;
11248            }
11249            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11250                    && user.getIdentifier() != UserHandle.USER_ALL) {
11251                // The caller is asking that the package only be deleted for a single
11252                // user.  To do this, we just mark its uninstalled state and delete
11253                // its data.  If this is a system app, we only allow this to happen if
11254                // they have set the special DELETE_SYSTEM_APP which requests different
11255                // semantics than normal for uninstalling system apps.
11256                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11257                ps.setUserState(user.getIdentifier(),
11258                        COMPONENT_ENABLED_STATE_DEFAULT,
11259                        false, //installed
11260                        true,  //stopped
11261                        true,  //notLaunched
11262                        false, //hidden
11263                        null, null, null,
11264                        false // blockUninstall
11265                        );
11266                if (!isSystemApp(ps)) {
11267                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11268                        // Other user still have this package installed, so all
11269                        // we need to do is clear this user's data and save that
11270                        // it is uninstalled.
11271                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11272                        removeUser = user.getIdentifier();
11273                        appId = ps.appId;
11274                        mSettings.writePackageRestrictionsLPr(removeUser);
11275                    } else {
11276                        // We need to set it back to 'installed' so the uninstall
11277                        // broadcasts will be sent correctly.
11278                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11279                        ps.setInstalled(true, user.getIdentifier());
11280                    }
11281                } else {
11282                    // This is a system app, so we assume that the
11283                    // other users still have this package installed, so all
11284                    // we need to do is clear this user's data and save that
11285                    // it is uninstalled.
11286                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11287                    removeUser = user.getIdentifier();
11288                    appId = ps.appId;
11289                    mSettings.writePackageRestrictionsLPr(removeUser);
11290                }
11291            }
11292        }
11293
11294        if (removeUser >= 0) {
11295            // From above, we determined that we are deleting this only
11296            // for a single user.  Continue the work here.
11297            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11298            if (outInfo != null) {
11299                outInfo.removedPackage = packageName;
11300                outInfo.removedAppId = appId;
11301                outInfo.removedUsers = new int[] {removeUser};
11302            }
11303            mInstaller.clearUserData(packageName, removeUser);
11304            removeKeystoreDataIfNeeded(removeUser, appId);
11305            schedulePackageCleaning(packageName, removeUser, false);
11306            return true;
11307        }
11308
11309        if (dataOnly) {
11310            // Delete application data first
11311            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11312            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11313            return true;
11314        }
11315
11316        boolean ret = false;
11317        if (isSystemApp(ps)) {
11318            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11319            // When an updated system application is deleted we delete the existing resources as well and
11320            // fall back to existing code in system partition
11321            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11322                    flags, outInfo, writeSettings);
11323        } else {
11324            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11325            // Kill application pre-emptively especially for apps on sd.
11326            killApplication(packageName, ps.appId, "uninstall pkg");
11327            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11328                    allUserHandles, perUserInstalled,
11329                    outInfo, writeSettings);
11330        }
11331
11332        return ret;
11333    }
11334
11335    private final class ClearStorageConnection implements ServiceConnection {
11336        IMediaContainerService mContainerService;
11337
11338        @Override
11339        public void onServiceConnected(ComponentName name, IBinder service) {
11340            synchronized (this) {
11341                mContainerService = IMediaContainerService.Stub.asInterface(service);
11342                notifyAll();
11343            }
11344        }
11345
11346        @Override
11347        public void onServiceDisconnected(ComponentName name) {
11348        }
11349    }
11350
11351    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11352        final boolean mounted;
11353        if (Environment.isExternalStorageEmulated()) {
11354            mounted = true;
11355        } else {
11356            final String status = Environment.getExternalStorageState();
11357
11358            mounted = status.equals(Environment.MEDIA_MOUNTED)
11359                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11360        }
11361
11362        if (!mounted) {
11363            return;
11364        }
11365
11366        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11367        int[] users;
11368        if (userId == UserHandle.USER_ALL) {
11369            users = sUserManager.getUserIds();
11370        } else {
11371            users = new int[] { userId };
11372        }
11373        final ClearStorageConnection conn = new ClearStorageConnection();
11374        if (mContext.bindServiceAsUser(
11375                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11376            try {
11377                for (int curUser : users) {
11378                    long timeout = SystemClock.uptimeMillis() + 5000;
11379                    synchronized (conn) {
11380                        long now = SystemClock.uptimeMillis();
11381                        while (conn.mContainerService == null && now < timeout) {
11382                            try {
11383                                conn.wait(timeout - now);
11384                            } catch (InterruptedException e) {
11385                            }
11386                        }
11387                    }
11388                    if (conn.mContainerService == null) {
11389                        return;
11390                    }
11391
11392                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11393                    clearDirectory(conn.mContainerService,
11394                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11395                    if (allData) {
11396                        clearDirectory(conn.mContainerService,
11397                                userEnv.buildExternalStorageAppDataDirs(packageName));
11398                        clearDirectory(conn.mContainerService,
11399                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11400                    }
11401                }
11402            } finally {
11403                mContext.unbindService(conn);
11404            }
11405        }
11406    }
11407
11408    @Override
11409    public void clearApplicationUserData(final String packageName,
11410            final IPackageDataObserver observer, final int userId) {
11411        mContext.enforceCallingOrSelfPermission(
11412                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11413        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11414        // Queue up an async operation since the package deletion may take a little while.
11415        mHandler.post(new Runnable() {
11416            public void run() {
11417                mHandler.removeCallbacks(this);
11418                final boolean succeeded;
11419                synchronized (mInstallLock) {
11420                    succeeded = clearApplicationUserDataLI(packageName, userId);
11421                }
11422                clearExternalStorageDataSync(packageName, userId, true);
11423                if (succeeded) {
11424                    // invoke DeviceStorageMonitor's update method to clear any notifications
11425                    DeviceStorageMonitorInternal
11426                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11427                    if (dsm != null) {
11428                        dsm.checkMemory();
11429                    }
11430                }
11431                if(observer != null) {
11432                    try {
11433                        observer.onRemoveCompleted(packageName, succeeded);
11434                    } catch (RemoteException e) {
11435                        Log.i(TAG, "Observer no longer exists.");
11436                    }
11437                } //end if observer
11438            } //end run
11439        });
11440    }
11441
11442    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11443        if (packageName == null) {
11444            Slog.w(TAG, "Attempt to delete null packageName.");
11445            return false;
11446        }
11447
11448        // Try finding details about the requested package
11449        PackageParser.Package pkg;
11450        synchronized (mPackages) {
11451            pkg = mPackages.get(packageName);
11452            if (pkg == null) {
11453                final PackageSetting ps = mSettings.mPackages.get(packageName);
11454                if (ps != null) {
11455                    pkg = ps.pkg;
11456                }
11457            }
11458        }
11459
11460        if (pkg == null) {
11461            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11462        }
11463
11464        // Always delete data directories for package, even if we found no other
11465        // record of app. This helps users recover from UID mismatches without
11466        // resorting to a full data wipe.
11467        int retCode = mInstaller.clearUserData(packageName, userId);
11468        if (retCode < 0) {
11469            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11470            return false;
11471        }
11472
11473        if (pkg == null) {
11474            return false;
11475        }
11476
11477        if (pkg != null && pkg.applicationInfo != null) {
11478            final int appId = pkg.applicationInfo.uid;
11479            removeKeystoreDataIfNeeded(userId, appId);
11480        }
11481
11482        // Create a native library symlink only if we have native libraries
11483        // and if the native libraries are 32 bit libraries. We do not provide
11484        // this symlink for 64 bit libraries.
11485        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11486                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11487            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11488            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11489                Slog.w(TAG, "Failed linking native library dir");
11490                return false;
11491            }
11492        }
11493
11494        return true;
11495    }
11496
11497    /**
11498     * Remove entries from the keystore daemon. Will only remove it if the
11499     * {@code appId} is valid.
11500     */
11501    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11502        if (appId < 0) {
11503            return;
11504        }
11505
11506        final KeyStore keyStore = KeyStore.getInstance();
11507        if (keyStore != null) {
11508            if (userId == UserHandle.USER_ALL) {
11509                for (final int individual : sUserManager.getUserIds()) {
11510                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11511                }
11512            } else {
11513                keyStore.clearUid(UserHandle.getUid(userId, appId));
11514            }
11515        } else {
11516            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11517        }
11518    }
11519
11520    @Override
11521    public void deleteApplicationCacheFiles(final String packageName,
11522            final IPackageDataObserver observer) {
11523        mContext.enforceCallingOrSelfPermission(
11524                android.Manifest.permission.DELETE_CACHE_FILES, null);
11525        // Queue up an async operation since the package deletion may take a little while.
11526        final int userId = UserHandle.getCallingUserId();
11527        mHandler.post(new Runnable() {
11528            public void run() {
11529                mHandler.removeCallbacks(this);
11530                final boolean succeded;
11531                synchronized (mInstallLock) {
11532                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11533                }
11534                clearExternalStorageDataSync(packageName, userId, false);
11535                if(observer != null) {
11536                    try {
11537                        observer.onRemoveCompleted(packageName, succeded);
11538                    } catch (RemoteException e) {
11539                        Log.i(TAG, "Observer no longer exists.");
11540                    }
11541                } //end if observer
11542            } //end run
11543        });
11544    }
11545
11546    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11547        if (packageName == null) {
11548            Slog.w(TAG, "Attempt to delete null packageName.");
11549            return false;
11550        }
11551        PackageParser.Package p;
11552        synchronized (mPackages) {
11553            p = mPackages.get(packageName);
11554        }
11555        if (p == null) {
11556            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11557            return false;
11558        }
11559        final ApplicationInfo applicationInfo = p.applicationInfo;
11560        if (applicationInfo == null) {
11561            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11562            return false;
11563        }
11564        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11565        if (retCode < 0) {
11566            Slog.w(TAG, "Couldn't remove cache files for package: "
11567                       + packageName + " u" + userId);
11568            return false;
11569        }
11570        return true;
11571    }
11572
11573    @Override
11574    public void getPackageSizeInfo(final String packageName, int userHandle,
11575            final IPackageStatsObserver observer) {
11576        mContext.enforceCallingOrSelfPermission(
11577                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11578        if (packageName == null) {
11579            throw new IllegalArgumentException("Attempt to get size of null packageName");
11580        }
11581
11582        PackageStats stats = new PackageStats(packageName, userHandle);
11583
11584        /*
11585         * Queue up an async operation since the package measurement may take a
11586         * little while.
11587         */
11588        Message msg = mHandler.obtainMessage(INIT_COPY);
11589        msg.obj = new MeasureParams(stats, observer);
11590        mHandler.sendMessage(msg);
11591    }
11592
11593    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11594            PackageStats pStats) {
11595        if (packageName == null) {
11596            Slog.w(TAG, "Attempt to get size of null packageName.");
11597            return false;
11598        }
11599        PackageParser.Package p;
11600        boolean dataOnly = false;
11601        String libDirRoot = null;
11602        String asecPath = null;
11603        PackageSetting ps = null;
11604        synchronized (mPackages) {
11605            p = mPackages.get(packageName);
11606            ps = mSettings.mPackages.get(packageName);
11607            if(p == null) {
11608                dataOnly = true;
11609                if((ps == null) || (ps.pkg == null)) {
11610                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11611                    return false;
11612                }
11613                p = ps.pkg;
11614            }
11615            if (ps != null) {
11616                libDirRoot = ps.legacyNativeLibraryPathString;
11617            }
11618            if (p != null && (isExternal(p) || p.isForwardLocked())) {
11619                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11620                if (secureContainerId != null) {
11621                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11622                }
11623            }
11624        }
11625        String publicSrcDir = null;
11626        if(!dataOnly) {
11627            final ApplicationInfo applicationInfo = p.applicationInfo;
11628            if (applicationInfo == null) {
11629                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11630                return false;
11631            }
11632            if (p.isForwardLocked()) {
11633                publicSrcDir = applicationInfo.getBaseResourcePath();
11634            }
11635        }
11636        // TODO: extend to measure size of split APKs
11637        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11638        // not just the first level.
11639        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11640        // just the primary.
11641        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11642        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11643                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11644        if (res < 0) {
11645            return false;
11646        }
11647
11648        // Fix-up for forward-locked applications in ASEC containers.
11649        if (!isExternal(p)) {
11650            pStats.codeSize += pStats.externalCodeSize;
11651            pStats.externalCodeSize = 0L;
11652        }
11653
11654        return true;
11655    }
11656
11657
11658    @Override
11659    public void addPackageToPreferred(String packageName) {
11660        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11661    }
11662
11663    @Override
11664    public void removePackageFromPreferred(String packageName) {
11665        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11666    }
11667
11668    @Override
11669    public List<PackageInfo> getPreferredPackages(int flags) {
11670        return new ArrayList<PackageInfo>();
11671    }
11672
11673    private int getUidTargetSdkVersionLockedLPr(int uid) {
11674        Object obj = mSettings.getUserIdLPr(uid);
11675        if (obj instanceof SharedUserSetting) {
11676            final SharedUserSetting sus = (SharedUserSetting) obj;
11677            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11678            final Iterator<PackageSetting> it = sus.packages.iterator();
11679            while (it.hasNext()) {
11680                final PackageSetting ps = it.next();
11681                if (ps.pkg != null) {
11682                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11683                    if (v < vers) vers = v;
11684                }
11685            }
11686            return vers;
11687        } else if (obj instanceof PackageSetting) {
11688            final PackageSetting ps = (PackageSetting) obj;
11689            if (ps.pkg != null) {
11690                return ps.pkg.applicationInfo.targetSdkVersion;
11691            }
11692        }
11693        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11694    }
11695
11696    @Override
11697    public void addPreferredActivity(IntentFilter filter, int match,
11698            ComponentName[] set, ComponentName activity, int userId) {
11699        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11700                "Adding preferred");
11701    }
11702
11703    private void addPreferredActivityInternal(IntentFilter filter, int match,
11704            ComponentName[] set, ComponentName activity, boolean always, int userId,
11705            String opname) {
11706        // writer
11707        int callingUid = Binder.getCallingUid();
11708        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11709        if (filter.countActions() == 0) {
11710            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11711            return;
11712        }
11713        synchronized (mPackages) {
11714            if (mContext.checkCallingOrSelfPermission(
11715                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11716                    != PackageManager.PERMISSION_GRANTED) {
11717                if (getUidTargetSdkVersionLockedLPr(callingUid)
11718                        < Build.VERSION_CODES.FROYO) {
11719                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11720                            + callingUid);
11721                    return;
11722                }
11723                mContext.enforceCallingOrSelfPermission(
11724                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11725            }
11726
11727            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11728            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11729                    + userId + ":");
11730            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11731            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11732            scheduleWritePackageRestrictionsLocked(userId);
11733        }
11734    }
11735
11736    @Override
11737    public void replacePreferredActivity(IntentFilter filter, int match,
11738            ComponentName[] set, ComponentName activity, int userId) {
11739        if (filter.countActions() != 1) {
11740            throw new IllegalArgumentException(
11741                    "replacePreferredActivity expects filter to have only 1 action.");
11742        }
11743        if (filter.countDataAuthorities() != 0
11744                || filter.countDataPaths() != 0
11745                || filter.countDataSchemes() > 1
11746                || filter.countDataTypes() != 0) {
11747            throw new IllegalArgumentException(
11748                    "replacePreferredActivity expects filter to have no data authorities, " +
11749                    "paths, or types; and at most one scheme.");
11750        }
11751
11752        final int callingUid = Binder.getCallingUid();
11753        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11754        synchronized (mPackages) {
11755            if (mContext.checkCallingOrSelfPermission(
11756                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11757                    != PackageManager.PERMISSION_GRANTED) {
11758                if (getUidTargetSdkVersionLockedLPr(callingUid)
11759                        < Build.VERSION_CODES.FROYO) {
11760                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11761                            + Binder.getCallingUid());
11762                    return;
11763                }
11764                mContext.enforceCallingOrSelfPermission(
11765                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11766            }
11767
11768            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11769            if (pir != null) {
11770                // Get all of the existing entries that exactly match this filter.
11771                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11772                if (existing != null && existing.size() == 1) {
11773                    PreferredActivity cur = existing.get(0);
11774                    if (DEBUG_PREFERRED) {
11775                        Slog.i(TAG, "Checking replace of preferred:");
11776                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11777                        if (!cur.mPref.mAlways) {
11778                            Slog.i(TAG, "  -- CUR; not mAlways!");
11779                        } else {
11780                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11781                            Slog.i(TAG, "  -- CUR: mSet="
11782                                    + Arrays.toString(cur.mPref.mSetComponents));
11783                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11784                            Slog.i(TAG, "  -- NEW: mMatch="
11785                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11786                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11787                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11788                        }
11789                    }
11790                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11791                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11792                            && cur.mPref.sameSet(set)) {
11793                        // Setting the preferred activity to what it happens to be already
11794                        if (DEBUG_PREFERRED) {
11795                            Slog.i(TAG, "Replacing with same preferred activity "
11796                                    + cur.mPref.mShortComponent + " for user "
11797                                    + userId + ":");
11798                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11799                        }
11800                        return;
11801                    }
11802                }
11803
11804                if (existing != null) {
11805                    if (DEBUG_PREFERRED) {
11806                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11807                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11808                    }
11809                    for (int i = 0; i < existing.size(); i++) {
11810                        PreferredActivity pa = existing.get(i);
11811                        if (DEBUG_PREFERRED) {
11812                            Slog.i(TAG, "Removing existing preferred activity "
11813                                    + pa.mPref.mComponent + ":");
11814                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11815                        }
11816                        pir.removeFilter(pa);
11817                    }
11818                }
11819            }
11820            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11821                    "Replacing preferred");
11822        }
11823    }
11824
11825    @Override
11826    public void clearPackagePreferredActivities(String packageName) {
11827        final int uid = Binder.getCallingUid();
11828        // writer
11829        synchronized (mPackages) {
11830            PackageParser.Package pkg = mPackages.get(packageName);
11831            if (pkg == null || pkg.applicationInfo.uid != uid) {
11832                if (mContext.checkCallingOrSelfPermission(
11833                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11834                        != PackageManager.PERMISSION_GRANTED) {
11835                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11836                            < Build.VERSION_CODES.FROYO) {
11837                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11838                                + Binder.getCallingUid());
11839                        return;
11840                    }
11841                    mContext.enforceCallingOrSelfPermission(
11842                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11843                }
11844            }
11845
11846            int user = UserHandle.getCallingUserId();
11847            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11848                scheduleWritePackageRestrictionsLocked(user);
11849            }
11850        }
11851    }
11852
11853    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11854    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11855        ArrayList<PreferredActivity> removed = null;
11856        boolean changed = false;
11857        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11858            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11859            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11860            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11861                continue;
11862            }
11863            Iterator<PreferredActivity> it = pir.filterIterator();
11864            while (it.hasNext()) {
11865                PreferredActivity pa = it.next();
11866                // Mark entry for removal only if it matches the package name
11867                // and the entry is of type "always".
11868                if (packageName == null ||
11869                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11870                                && pa.mPref.mAlways)) {
11871                    if (removed == null) {
11872                        removed = new ArrayList<PreferredActivity>();
11873                    }
11874                    removed.add(pa);
11875                }
11876            }
11877            if (removed != null) {
11878                for (int j=0; j<removed.size(); j++) {
11879                    PreferredActivity pa = removed.get(j);
11880                    pir.removeFilter(pa);
11881                }
11882                changed = true;
11883            }
11884        }
11885        return changed;
11886    }
11887
11888    @Override
11889    public void resetPreferredActivities(int userId) {
11890        /* TODO: Actually use userId. Why is it being passed in? */
11891        mContext.enforceCallingOrSelfPermission(
11892                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11893        // writer
11894        synchronized (mPackages) {
11895            int user = UserHandle.getCallingUserId();
11896            clearPackagePreferredActivitiesLPw(null, user);
11897            mSettings.readDefaultPreferredAppsLPw(this, user);
11898            scheduleWritePackageRestrictionsLocked(user);
11899        }
11900    }
11901
11902    @Override
11903    public int getPreferredActivities(List<IntentFilter> outFilters,
11904            List<ComponentName> outActivities, String packageName) {
11905
11906        int num = 0;
11907        final int userId = UserHandle.getCallingUserId();
11908        // reader
11909        synchronized (mPackages) {
11910            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11911            if (pir != null) {
11912                final Iterator<PreferredActivity> it = pir.filterIterator();
11913                while (it.hasNext()) {
11914                    final PreferredActivity pa = it.next();
11915                    if (packageName == null
11916                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11917                                    && pa.mPref.mAlways)) {
11918                        if (outFilters != null) {
11919                            outFilters.add(new IntentFilter(pa));
11920                        }
11921                        if (outActivities != null) {
11922                            outActivities.add(pa.mPref.mComponent);
11923                        }
11924                    }
11925                }
11926            }
11927        }
11928
11929        return num;
11930    }
11931
11932    @Override
11933    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11934            int userId) {
11935        int callingUid = Binder.getCallingUid();
11936        if (callingUid != Process.SYSTEM_UID) {
11937            throw new SecurityException(
11938                    "addPersistentPreferredActivity can only be run by the system");
11939        }
11940        if (filter.countActions() == 0) {
11941            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11942            return;
11943        }
11944        synchronized (mPackages) {
11945            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11946                    " :");
11947            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11948            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11949                    new PersistentPreferredActivity(filter, activity));
11950            scheduleWritePackageRestrictionsLocked(userId);
11951        }
11952    }
11953
11954    @Override
11955    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11956        int callingUid = Binder.getCallingUid();
11957        if (callingUid != Process.SYSTEM_UID) {
11958            throw new SecurityException(
11959                    "clearPackagePersistentPreferredActivities can only be run by the system");
11960        }
11961        ArrayList<PersistentPreferredActivity> removed = null;
11962        boolean changed = false;
11963        synchronized (mPackages) {
11964            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11965                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11966                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11967                        .valueAt(i);
11968                if (userId != thisUserId) {
11969                    continue;
11970                }
11971                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11972                while (it.hasNext()) {
11973                    PersistentPreferredActivity ppa = it.next();
11974                    // Mark entry for removal only if it matches the package name.
11975                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11976                        if (removed == null) {
11977                            removed = new ArrayList<PersistentPreferredActivity>();
11978                        }
11979                        removed.add(ppa);
11980                    }
11981                }
11982                if (removed != null) {
11983                    for (int j=0; j<removed.size(); j++) {
11984                        PersistentPreferredActivity ppa = removed.get(j);
11985                        ppir.removeFilter(ppa);
11986                    }
11987                    changed = true;
11988                }
11989            }
11990
11991            if (changed) {
11992                scheduleWritePackageRestrictionsLocked(userId);
11993            }
11994        }
11995    }
11996
11997    @Override
11998    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11999            int sourceUserId, int targetUserId, int flags) {
12000        mContext.enforceCallingOrSelfPermission(
12001                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12002        int callingUid = Binder.getCallingUid();
12003        enforceOwnerRights(ownerPackage, callingUid);
12004        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12005        if (intentFilter.countActions() == 0) {
12006            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12007            return;
12008        }
12009        synchronized (mPackages) {
12010            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12011                    ownerPackage, targetUserId, flags);
12012            CrossProfileIntentResolver resolver =
12013                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12014            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12015            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12016            if (existing != null) {
12017                int size = existing.size();
12018                for (int i = 0; i < size; i++) {
12019                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12020                        return;
12021                    }
12022                }
12023            }
12024            resolver.addFilter(newFilter);
12025            scheduleWritePackageRestrictionsLocked(sourceUserId);
12026        }
12027    }
12028
12029    @Override
12030    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12031        mContext.enforceCallingOrSelfPermission(
12032                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12033        int callingUid = Binder.getCallingUid();
12034        enforceOwnerRights(ownerPackage, callingUid);
12035        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12036        synchronized (mPackages) {
12037            CrossProfileIntentResolver resolver =
12038                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12039            ArraySet<CrossProfileIntentFilter> set =
12040                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12041            for (CrossProfileIntentFilter filter : set) {
12042                if (filter.getOwnerPackage().equals(ownerPackage)) {
12043                    resolver.removeFilter(filter);
12044                }
12045            }
12046            scheduleWritePackageRestrictionsLocked(sourceUserId);
12047        }
12048    }
12049
12050    // Enforcing that callingUid is owning pkg on userId
12051    private void enforceOwnerRights(String pkg, int callingUid) {
12052        // The system owns everything.
12053        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12054            return;
12055        }
12056        int callingUserId = UserHandle.getUserId(callingUid);
12057        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12058        if (pi == null) {
12059            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12060                    + callingUserId);
12061        }
12062        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12063            throw new SecurityException("Calling uid " + callingUid
12064                    + " does not own package " + pkg);
12065        }
12066    }
12067
12068    @Override
12069    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12070        Intent intent = new Intent(Intent.ACTION_MAIN);
12071        intent.addCategory(Intent.CATEGORY_HOME);
12072
12073        final int callingUserId = UserHandle.getCallingUserId();
12074        List<ResolveInfo> list = queryIntentActivities(intent, null,
12075                PackageManager.GET_META_DATA, callingUserId);
12076        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12077                true, false, false, callingUserId);
12078
12079        allHomeCandidates.clear();
12080        if (list != null) {
12081            for (ResolveInfo ri : list) {
12082                allHomeCandidates.add(ri);
12083            }
12084        }
12085        return (preferred == null || preferred.activityInfo == null)
12086                ? null
12087                : new ComponentName(preferred.activityInfo.packageName,
12088                        preferred.activityInfo.name);
12089    }
12090
12091    @Override
12092    public void setApplicationEnabledSetting(String appPackageName,
12093            int newState, int flags, int userId, String callingPackage) {
12094        if (!sUserManager.exists(userId)) return;
12095        if (callingPackage == null) {
12096            callingPackage = Integer.toString(Binder.getCallingUid());
12097        }
12098        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12099    }
12100
12101    @Override
12102    public void setComponentEnabledSetting(ComponentName componentName,
12103            int newState, int flags, int userId) {
12104        if (!sUserManager.exists(userId)) return;
12105        setEnabledSetting(componentName.getPackageName(),
12106                componentName.getClassName(), newState, flags, userId, null);
12107    }
12108
12109    private void setEnabledSetting(final String packageName, String className, int newState,
12110            final int flags, int userId, String callingPackage) {
12111        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12112              || newState == COMPONENT_ENABLED_STATE_ENABLED
12113              || newState == COMPONENT_ENABLED_STATE_DISABLED
12114              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12115              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12116            throw new IllegalArgumentException("Invalid new component state: "
12117                    + newState);
12118        }
12119        PackageSetting pkgSetting;
12120        final int uid = Binder.getCallingUid();
12121        final int permission = mContext.checkCallingOrSelfPermission(
12122                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12123        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12124        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12125        boolean sendNow = false;
12126        boolean isApp = (className == null);
12127        String componentName = isApp ? packageName : className;
12128        int packageUid = -1;
12129        ArrayList<String> components;
12130
12131        // writer
12132        synchronized (mPackages) {
12133            pkgSetting = mSettings.mPackages.get(packageName);
12134            if (pkgSetting == null) {
12135                if (className == null) {
12136                    throw new IllegalArgumentException(
12137                            "Unknown package: " + packageName);
12138                }
12139                throw new IllegalArgumentException(
12140                        "Unknown component: " + packageName
12141                        + "/" + className);
12142            }
12143            // Allow root and verify that userId is not being specified by a different user
12144            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12145                throw new SecurityException(
12146                        "Permission Denial: attempt to change component state from pid="
12147                        + Binder.getCallingPid()
12148                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12149            }
12150            if (className == null) {
12151                // We're dealing with an application/package level state change
12152                if (pkgSetting.getEnabled(userId) == newState) {
12153                    // Nothing to do
12154                    return;
12155                }
12156                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12157                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12158                    // Don't care about who enables an app.
12159                    callingPackage = null;
12160                }
12161                pkgSetting.setEnabled(newState, userId, callingPackage);
12162                // pkgSetting.pkg.mSetEnabled = newState;
12163            } else {
12164                // We're dealing with a component level state change
12165                // First, verify that this is a valid class name.
12166                PackageParser.Package pkg = pkgSetting.pkg;
12167                if (pkg == null || !pkg.hasComponentClassName(className)) {
12168                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12169                        throw new IllegalArgumentException("Component class " + className
12170                                + " does not exist in " + packageName);
12171                    } else {
12172                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12173                                + className + " does not exist in " + packageName);
12174                    }
12175                }
12176                switch (newState) {
12177                case COMPONENT_ENABLED_STATE_ENABLED:
12178                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12179                        return;
12180                    }
12181                    break;
12182                case COMPONENT_ENABLED_STATE_DISABLED:
12183                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12184                        return;
12185                    }
12186                    break;
12187                case COMPONENT_ENABLED_STATE_DEFAULT:
12188                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12189                        return;
12190                    }
12191                    break;
12192                default:
12193                    Slog.e(TAG, "Invalid new component state: " + newState);
12194                    return;
12195                }
12196            }
12197            scheduleWritePackageRestrictionsLocked(userId);
12198            components = mPendingBroadcasts.get(userId, packageName);
12199            final boolean newPackage = components == null;
12200            if (newPackage) {
12201                components = new ArrayList<String>();
12202            }
12203            if (!components.contains(componentName)) {
12204                components.add(componentName);
12205            }
12206            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12207                sendNow = true;
12208                // Purge entry from pending broadcast list if another one exists already
12209                // since we are sending one right away.
12210                mPendingBroadcasts.remove(userId, packageName);
12211            } else {
12212                if (newPackage) {
12213                    mPendingBroadcasts.put(userId, packageName, components);
12214                }
12215                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12216                    // Schedule a message
12217                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12218                }
12219            }
12220        }
12221
12222        long callingId = Binder.clearCallingIdentity();
12223        try {
12224            if (sendNow) {
12225                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12226                sendPackageChangedBroadcast(packageName,
12227                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12228            }
12229        } finally {
12230            Binder.restoreCallingIdentity(callingId);
12231        }
12232    }
12233
12234    private void sendPackageChangedBroadcast(String packageName,
12235            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12236        if (DEBUG_INSTALL)
12237            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12238                    + componentNames);
12239        Bundle extras = new Bundle(4);
12240        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12241        String nameList[] = new String[componentNames.size()];
12242        componentNames.toArray(nameList);
12243        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12244        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12245        extras.putInt(Intent.EXTRA_UID, packageUid);
12246        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12247                new int[] {UserHandle.getUserId(packageUid)});
12248    }
12249
12250    @Override
12251    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12252        if (!sUserManager.exists(userId)) return;
12253        final int uid = Binder.getCallingUid();
12254        final int permission = mContext.checkCallingOrSelfPermission(
12255                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12256        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12257        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12258        // writer
12259        synchronized (mPackages) {
12260            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12261                    uid, userId)) {
12262                scheduleWritePackageRestrictionsLocked(userId);
12263            }
12264        }
12265    }
12266
12267    @Override
12268    public String getInstallerPackageName(String packageName) {
12269        // reader
12270        synchronized (mPackages) {
12271            return mSettings.getInstallerPackageNameLPr(packageName);
12272        }
12273    }
12274
12275    @Override
12276    public int getApplicationEnabledSetting(String packageName, int userId) {
12277        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12278        int uid = Binder.getCallingUid();
12279        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12280        // reader
12281        synchronized (mPackages) {
12282            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12283        }
12284    }
12285
12286    @Override
12287    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12288        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12289        int uid = Binder.getCallingUid();
12290        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12291        // reader
12292        synchronized (mPackages) {
12293            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12294        }
12295    }
12296
12297    @Override
12298    public void enterSafeMode() {
12299        enforceSystemOrRoot("Only the system can request entering safe mode");
12300
12301        if (!mSystemReady) {
12302            mSafeMode = true;
12303        }
12304    }
12305
12306    @Override
12307    public void systemReady() {
12308        mSystemReady = true;
12309
12310        // Read the compatibilty setting when the system is ready.
12311        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12312                mContext.getContentResolver(),
12313                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12314        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12315        if (DEBUG_SETTINGS) {
12316            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12317        }
12318
12319        synchronized (mPackages) {
12320            // Verify that all of the preferred activity components actually
12321            // exist.  It is possible for applications to be updated and at
12322            // that point remove a previously declared activity component that
12323            // had been set as a preferred activity.  We try to clean this up
12324            // the next time we encounter that preferred activity, but it is
12325            // possible for the user flow to never be able to return to that
12326            // situation so here we do a sanity check to make sure we haven't
12327            // left any junk around.
12328            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12329            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12330                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12331                removed.clear();
12332                for (PreferredActivity pa : pir.filterSet()) {
12333                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12334                        removed.add(pa);
12335                    }
12336                }
12337                if (removed.size() > 0) {
12338                    for (int r=0; r<removed.size(); r++) {
12339                        PreferredActivity pa = removed.get(r);
12340                        Slog.w(TAG, "Removing dangling preferred activity: "
12341                                + pa.mPref.mComponent);
12342                        pir.removeFilter(pa);
12343                    }
12344                    mSettings.writePackageRestrictionsLPr(
12345                            mSettings.mPreferredActivities.keyAt(i));
12346                }
12347            }
12348        }
12349        sUserManager.systemReady();
12350
12351        // Kick off any messages waiting for system ready
12352        if (mPostSystemReadyMessages != null) {
12353            for (Message msg : mPostSystemReadyMessages) {
12354                msg.sendToTarget();
12355            }
12356            mPostSystemReadyMessages = null;
12357        }
12358    }
12359
12360    @Override
12361    public boolean isSafeMode() {
12362        return mSafeMode;
12363    }
12364
12365    @Override
12366    public boolean hasSystemUidErrors() {
12367        return mHasSystemUidErrors;
12368    }
12369
12370    static String arrayToString(int[] array) {
12371        StringBuffer buf = new StringBuffer(128);
12372        buf.append('[');
12373        if (array != null) {
12374            for (int i=0; i<array.length; i++) {
12375                if (i > 0) buf.append(", ");
12376                buf.append(array[i]);
12377            }
12378        }
12379        buf.append(']');
12380        return buf.toString();
12381    }
12382
12383    static class DumpState {
12384        public static final int DUMP_LIBS = 1 << 0;
12385        public static final int DUMP_FEATURES = 1 << 1;
12386        public static final int DUMP_RESOLVERS = 1 << 2;
12387        public static final int DUMP_PERMISSIONS = 1 << 3;
12388        public static final int DUMP_PACKAGES = 1 << 4;
12389        public static final int DUMP_SHARED_USERS = 1 << 5;
12390        public static final int DUMP_MESSAGES = 1 << 6;
12391        public static final int DUMP_PROVIDERS = 1 << 7;
12392        public static final int DUMP_VERIFIERS = 1 << 8;
12393        public static final int DUMP_PREFERRED = 1 << 9;
12394        public static final int DUMP_PREFERRED_XML = 1 << 10;
12395        public static final int DUMP_KEYSETS = 1 << 11;
12396        public static final int DUMP_VERSION = 1 << 12;
12397        public static final int DUMP_INSTALLS = 1 << 13;
12398
12399        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12400
12401        private int mTypes;
12402
12403        private int mOptions;
12404
12405        private boolean mTitlePrinted;
12406
12407        private SharedUserSetting mSharedUser;
12408
12409        public boolean isDumping(int type) {
12410            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12411                return true;
12412            }
12413
12414            return (mTypes & type) != 0;
12415        }
12416
12417        public void setDump(int type) {
12418            mTypes |= type;
12419        }
12420
12421        public boolean isOptionEnabled(int option) {
12422            return (mOptions & option) != 0;
12423        }
12424
12425        public void setOptionEnabled(int option) {
12426            mOptions |= option;
12427        }
12428
12429        public boolean onTitlePrinted() {
12430            final boolean printed = mTitlePrinted;
12431            mTitlePrinted = true;
12432            return printed;
12433        }
12434
12435        public boolean getTitlePrinted() {
12436            return mTitlePrinted;
12437        }
12438
12439        public void setTitlePrinted(boolean enabled) {
12440            mTitlePrinted = enabled;
12441        }
12442
12443        public SharedUserSetting getSharedUser() {
12444            return mSharedUser;
12445        }
12446
12447        public void setSharedUser(SharedUserSetting user) {
12448            mSharedUser = user;
12449        }
12450    }
12451
12452    @Override
12453    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12454        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12455                != PackageManager.PERMISSION_GRANTED) {
12456            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12457                    + Binder.getCallingPid()
12458                    + ", uid=" + Binder.getCallingUid()
12459                    + " without permission "
12460                    + android.Manifest.permission.DUMP);
12461            return;
12462        }
12463
12464        DumpState dumpState = new DumpState();
12465        boolean fullPreferred = false;
12466        boolean checkin = false;
12467
12468        String packageName = null;
12469
12470        int opti = 0;
12471        while (opti < args.length) {
12472            String opt = args[opti];
12473            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12474                break;
12475            }
12476            opti++;
12477
12478            if ("-a".equals(opt)) {
12479                // Right now we only know how to print all.
12480            } else if ("-h".equals(opt)) {
12481                pw.println("Package manager dump options:");
12482                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12483                pw.println("    --checkin: dump for a checkin");
12484                pw.println("    -f: print details of intent filters");
12485                pw.println("    -h: print this help");
12486                pw.println("  cmd may be one of:");
12487                pw.println("    l[ibraries]: list known shared libraries");
12488                pw.println("    f[ibraries]: list device features");
12489                pw.println("    k[eysets]: print known keysets");
12490                pw.println("    r[esolvers]: dump intent resolvers");
12491                pw.println("    perm[issions]: dump permissions");
12492                pw.println("    pref[erred]: print preferred package settings");
12493                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12494                pw.println("    prov[iders]: dump content providers");
12495                pw.println("    p[ackages]: dump installed packages");
12496                pw.println("    s[hared-users]: dump shared user IDs");
12497                pw.println("    m[essages]: print collected runtime messages");
12498                pw.println("    v[erifiers]: print package verifier info");
12499                pw.println("    version: print database version info");
12500                pw.println("    write: write current settings now");
12501                pw.println("    <package.name>: info about given package");
12502                pw.println("    installs: details about install sessions");
12503                return;
12504            } else if ("--checkin".equals(opt)) {
12505                checkin = true;
12506            } else if ("-f".equals(opt)) {
12507                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12508            } else {
12509                pw.println("Unknown argument: " + opt + "; use -h for help");
12510            }
12511        }
12512
12513        // Is the caller requesting to dump a particular piece of data?
12514        if (opti < args.length) {
12515            String cmd = args[opti];
12516            opti++;
12517            // Is this a package name?
12518            if ("android".equals(cmd) || cmd.contains(".")) {
12519                packageName = cmd;
12520                // When dumping a single package, we always dump all of its
12521                // filter information since the amount of data will be reasonable.
12522                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12523            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12524                dumpState.setDump(DumpState.DUMP_LIBS);
12525            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12526                dumpState.setDump(DumpState.DUMP_FEATURES);
12527            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12528                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12529            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12530                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12531            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12532                dumpState.setDump(DumpState.DUMP_PREFERRED);
12533            } else if ("preferred-xml".equals(cmd)) {
12534                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12535                if (opti < args.length && "--full".equals(args[opti])) {
12536                    fullPreferred = true;
12537                    opti++;
12538                }
12539            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12540                dumpState.setDump(DumpState.DUMP_PACKAGES);
12541            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12542                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12543            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12544                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12545            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12546                dumpState.setDump(DumpState.DUMP_MESSAGES);
12547            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12548                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12549            } else if ("version".equals(cmd)) {
12550                dumpState.setDump(DumpState.DUMP_VERSION);
12551            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12552                dumpState.setDump(DumpState.DUMP_KEYSETS);
12553            } else if ("installs".equals(cmd)) {
12554                dumpState.setDump(DumpState.DUMP_INSTALLS);
12555            } else if ("write".equals(cmd)) {
12556                synchronized (mPackages) {
12557                    mSettings.writeLPr();
12558                    pw.println("Settings written.");
12559                    return;
12560                }
12561            }
12562        }
12563
12564        if (checkin) {
12565            pw.println("vers,1");
12566        }
12567
12568        // reader
12569        synchronized (mPackages) {
12570            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12571                if (!checkin) {
12572                    if (dumpState.onTitlePrinted())
12573                        pw.println();
12574                    pw.println("Database versions:");
12575                    pw.print("  SDK Version:");
12576                    pw.print(" internal=");
12577                    pw.print(mSettings.mInternalSdkPlatform);
12578                    pw.print(" external=");
12579                    pw.println(mSettings.mExternalSdkPlatform);
12580                    pw.print("  DB Version:");
12581                    pw.print(" internal=");
12582                    pw.print(mSettings.mInternalDatabaseVersion);
12583                    pw.print(" external=");
12584                    pw.println(mSettings.mExternalDatabaseVersion);
12585                }
12586            }
12587
12588            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12589                if (!checkin) {
12590                    if (dumpState.onTitlePrinted())
12591                        pw.println();
12592                    pw.println("Verifiers:");
12593                    pw.print("  Required: ");
12594                    pw.print(mRequiredVerifierPackage);
12595                    pw.print(" (uid=");
12596                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12597                    pw.println(")");
12598                } else if (mRequiredVerifierPackage != null) {
12599                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12600                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12601                }
12602            }
12603
12604            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12605                boolean printedHeader = false;
12606                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12607                while (it.hasNext()) {
12608                    String name = it.next();
12609                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12610                    if (!checkin) {
12611                        if (!printedHeader) {
12612                            if (dumpState.onTitlePrinted())
12613                                pw.println();
12614                            pw.println("Libraries:");
12615                            printedHeader = true;
12616                        }
12617                        pw.print("  ");
12618                    } else {
12619                        pw.print("lib,");
12620                    }
12621                    pw.print(name);
12622                    if (!checkin) {
12623                        pw.print(" -> ");
12624                    }
12625                    if (ent.path != null) {
12626                        if (!checkin) {
12627                            pw.print("(jar) ");
12628                            pw.print(ent.path);
12629                        } else {
12630                            pw.print(",jar,");
12631                            pw.print(ent.path);
12632                        }
12633                    } else {
12634                        if (!checkin) {
12635                            pw.print("(apk) ");
12636                            pw.print(ent.apk);
12637                        } else {
12638                            pw.print(",apk,");
12639                            pw.print(ent.apk);
12640                        }
12641                    }
12642                    pw.println();
12643                }
12644            }
12645
12646            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12647                if (dumpState.onTitlePrinted())
12648                    pw.println();
12649                if (!checkin) {
12650                    pw.println("Features:");
12651                }
12652                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12653                while (it.hasNext()) {
12654                    String name = it.next();
12655                    if (!checkin) {
12656                        pw.print("  ");
12657                    } else {
12658                        pw.print("feat,");
12659                    }
12660                    pw.println(name);
12661                }
12662            }
12663
12664            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12665                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12666                        : "Activity Resolver Table:", "  ", packageName,
12667                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12668                    dumpState.setTitlePrinted(true);
12669                }
12670                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12671                        : "Receiver Resolver Table:", "  ", packageName,
12672                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12673                    dumpState.setTitlePrinted(true);
12674                }
12675                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12676                        : "Service Resolver Table:", "  ", packageName,
12677                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12678                    dumpState.setTitlePrinted(true);
12679                }
12680                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12681                        : "Provider Resolver Table:", "  ", packageName,
12682                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12683                    dumpState.setTitlePrinted(true);
12684                }
12685            }
12686
12687            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12688                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12689                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12690                    int user = mSettings.mPreferredActivities.keyAt(i);
12691                    if (pir.dump(pw,
12692                            dumpState.getTitlePrinted()
12693                                ? "\nPreferred Activities User " + user + ":"
12694                                : "Preferred Activities User " + user + ":", "  ",
12695                            packageName, true, false)) {
12696                        dumpState.setTitlePrinted(true);
12697                    }
12698                }
12699            }
12700
12701            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12702                pw.flush();
12703                FileOutputStream fout = new FileOutputStream(fd);
12704                BufferedOutputStream str = new BufferedOutputStream(fout);
12705                XmlSerializer serializer = new FastXmlSerializer();
12706                try {
12707                    serializer.setOutput(str, "utf-8");
12708                    serializer.startDocument(null, true);
12709                    serializer.setFeature(
12710                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12711                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12712                    serializer.endDocument();
12713                    serializer.flush();
12714                } catch (IllegalArgumentException e) {
12715                    pw.println("Failed writing: " + e);
12716                } catch (IllegalStateException e) {
12717                    pw.println("Failed writing: " + e);
12718                } catch (IOException e) {
12719                    pw.println("Failed writing: " + e);
12720                }
12721            }
12722
12723            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12724                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12725                if (packageName == null) {
12726                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12727                        if (iperm == 0) {
12728                            if (dumpState.onTitlePrinted())
12729                                pw.println();
12730                            pw.println("AppOp Permissions:");
12731                        }
12732                        pw.print("  AppOp Permission ");
12733                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12734                        pw.println(":");
12735                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12736                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12737                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12738                        }
12739                    }
12740                }
12741            }
12742
12743            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12744                boolean printedSomething = false;
12745                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12746                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12747                        continue;
12748                    }
12749                    if (!printedSomething) {
12750                        if (dumpState.onTitlePrinted())
12751                            pw.println();
12752                        pw.println("Registered ContentProviders:");
12753                        printedSomething = true;
12754                    }
12755                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12756                    pw.print("    "); pw.println(p.toString());
12757                }
12758                printedSomething = false;
12759                for (Map.Entry<String, PackageParser.Provider> entry :
12760                        mProvidersByAuthority.entrySet()) {
12761                    PackageParser.Provider p = entry.getValue();
12762                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12763                        continue;
12764                    }
12765                    if (!printedSomething) {
12766                        if (dumpState.onTitlePrinted())
12767                            pw.println();
12768                        pw.println("ContentProvider Authorities:");
12769                        printedSomething = true;
12770                    }
12771                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12772                    pw.print("    "); pw.println(p.toString());
12773                    if (p.info != null && p.info.applicationInfo != null) {
12774                        final String appInfo = p.info.applicationInfo.toString();
12775                        pw.print("      applicationInfo="); pw.println(appInfo);
12776                    }
12777                }
12778            }
12779
12780            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12781                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12782            }
12783
12784            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12785                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12786            }
12787
12788            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12789                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12790            }
12791
12792            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12793                // XXX should handle packageName != null by dumping only install data that
12794                // the given package is involved with.
12795                if (dumpState.onTitlePrinted()) pw.println();
12796                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12797            }
12798
12799            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12800                if (dumpState.onTitlePrinted()) pw.println();
12801                mSettings.dumpReadMessagesLPr(pw, dumpState);
12802
12803                pw.println();
12804                pw.println("Package warning messages:");
12805                BufferedReader in = null;
12806                String line = null;
12807                try {
12808                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12809                    while ((line = in.readLine()) != null) {
12810                        if (line.contains("ignored: updated version")) continue;
12811                        pw.println(line);
12812                    }
12813                } catch (IOException ignored) {
12814                } finally {
12815                    IoUtils.closeQuietly(in);
12816                }
12817            }
12818
12819            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12820                BufferedReader in = null;
12821                String line = null;
12822                try {
12823                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12824                    while ((line = in.readLine()) != null) {
12825                        if (line.contains("ignored: updated version")) continue;
12826                        pw.print("msg,");
12827                        pw.println(line);
12828                    }
12829                } catch (IOException ignored) {
12830                } finally {
12831                    IoUtils.closeQuietly(in);
12832                }
12833            }
12834        }
12835    }
12836
12837    // ------- apps on sdcard specific code -------
12838    static final boolean DEBUG_SD_INSTALL = false;
12839
12840    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12841
12842    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12843
12844    private boolean mMediaMounted = false;
12845
12846    static String getEncryptKey() {
12847        try {
12848            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12849                    SD_ENCRYPTION_KEYSTORE_NAME);
12850            if (sdEncKey == null) {
12851                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12852                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12853                if (sdEncKey == null) {
12854                    Slog.e(TAG, "Failed to create encryption keys");
12855                    return null;
12856                }
12857            }
12858            return sdEncKey;
12859        } catch (NoSuchAlgorithmException nsae) {
12860            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12861            return null;
12862        } catch (IOException ioe) {
12863            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12864            return null;
12865        }
12866    }
12867
12868    /*
12869     * Update media status on PackageManager.
12870     */
12871    @Override
12872    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12873        int callingUid = Binder.getCallingUid();
12874        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12875            throw new SecurityException("Media status can only be updated by the system");
12876        }
12877        // reader; this apparently protects mMediaMounted, but should probably
12878        // be a different lock in that case.
12879        synchronized (mPackages) {
12880            Log.i(TAG, "Updating external media status from "
12881                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12882                    + (mediaStatus ? "mounted" : "unmounted"));
12883            if (DEBUG_SD_INSTALL)
12884                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12885                        + ", mMediaMounted=" + mMediaMounted);
12886            if (mediaStatus == mMediaMounted) {
12887                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12888                        : 0, -1);
12889                mHandler.sendMessage(msg);
12890                return;
12891            }
12892            mMediaMounted = mediaStatus;
12893        }
12894        // Queue up an async operation since the package installation may take a
12895        // little while.
12896        mHandler.post(new Runnable() {
12897            public void run() {
12898                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12899            }
12900        });
12901    }
12902
12903    /**
12904     * Called by MountService when the initial ASECs to scan are available.
12905     * Should block until all the ASEC containers are finished being scanned.
12906     */
12907    public void scanAvailableAsecs() {
12908        updateExternalMediaStatusInner(true, false, false);
12909        if (mShouldRestoreconData) {
12910            SELinuxMMAC.setRestoreconDone();
12911            mShouldRestoreconData = false;
12912        }
12913    }
12914
12915    /*
12916     * Collect information of applications on external media, map them against
12917     * existing containers and update information based on current mount status.
12918     * Please note that we always have to report status if reportStatus has been
12919     * set to true especially when unloading packages.
12920     */
12921    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12922            boolean externalStorage) {
12923        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12924        int[] uidArr = EmptyArray.INT;
12925
12926        final String[] list = PackageHelper.getSecureContainerList();
12927        if (ArrayUtils.isEmpty(list)) {
12928            Log.i(TAG, "No secure containers found");
12929        } else {
12930            // Process list of secure containers and categorize them
12931            // as active or stale based on their package internal state.
12932
12933            // reader
12934            synchronized (mPackages) {
12935                for (String cid : list) {
12936                    // Leave stages untouched for now; installer service owns them
12937                    if (PackageInstallerService.isStageName(cid)) continue;
12938
12939                    if (DEBUG_SD_INSTALL)
12940                        Log.i(TAG, "Processing container " + cid);
12941                    String pkgName = getAsecPackageName(cid);
12942                    if (pkgName == null) {
12943                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12944                        continue;
12945                    }
12946                    if (DEBUG_SD_INSTALL)
12947                        Log.i(TAG, "Looking for pkg : " + pkgName);
12948
12949                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12950                    if (ps == null) {
12951                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12952                        continue;
12953                    }
12954
12955                    /*
12956                     * Skip packages that are not external if we're unmounting
12957                     * external storage.
12958                     */
12959                    if (externalStorage && !isMounted && !isExternal(ps)) {
12960                        continue;
12961                    }
12962
12963                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12964                            getAppDexInstructionSets(ps), ps.isForwardLocked());
12965                    // The package status is changed only if the code path
12966                    // matches between settings and the container id.
12967                    if (ps.codePathString != null
12968                            && ps.codePathString.startsWith(args.getCodePath())) {
12969                        if (DEBUG_SD_INSTALL) {
12970                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12971                                    + " at code path: " + ps.codePathString);
12972                        }
12973
12974                        // We do have a valid package installed on sdcard
12975                        processCids.put(args, ps.codePathString);
12976                        final int uid = ps.appId;
12977                        if (uid != -1) {
12978                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12979                        }
12980                    } else {
12981                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12982                                + ps.codePathString);
12983                    }
12984                }
12985            }
12986
12987            Arrays.sort(uidArr);
12988        }
12989
12990        // Process packages with valid entries.
12991        if (isMounted) {
12992            if (DEBUG_SD_INSTALL)
12993                Log.i(TAG, "Loading packages");
12994            loadMediaPackages(processCids, uidArr);
12995            startCleaningPackages();
12996            mInstallerService.onSecureContainersAvailable();
12997        } else {
12998            if (DEBUG_SD_INSTALL)
12999                Log.i(TAG, "Unloading packages");
13000            unloadMediaPackages(processCids, uidArr, reportStatus);
13001        }
13002    }
13003
13004    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13005            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13006        int size = pkgList.size();
13007        if (size > 0) {
13008            // Send broadcasts here
13009            Bundle extras = new Bundle();
13010            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
13011                    .toArray(new String[size]));
13012            if (uidArr != null) {
13013                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13014            }
13015            if (replacing) {
13016                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13017            }
13018            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13019                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13020            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13021        }
13022    }
13023
13024   /*
13025     * Look at potentially valid container ids from processCids If package
13026     * information doesn't match the one on record or package scanning fails,
13027     * the cid is added to list of removeCids. We currently don't delete stale
13028     * containers.
13029     */
13030    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13031        ArrayList<String> pkgList = new ArrayList<String>();
13032        Set<AsecInstallArgs> keys = processCids.keySet();
13033
13034        for (AsecInstallArgs args : keys) {
13035            String codePath = processCids.get(args);
13036            if (DEBUG_SD_INSTALL)
13037                Log.i(TAG, "Loading container : " + args.cid);
13038            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13039            try {
13040                // Make sure there are no container errors first.
13041                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13042                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13043                            + " when installing from sdcard");
13044                    continue;
13045                }
13046                // Check code path here.
13047                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13048                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13049                            + " does not match one in settings " + codePath);
13050                    continue;
13051                }
13052                // Parse package
13053                int parseFlags = mDefParseFlags;
13054                if (args.isExternal()) {
13055                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
13056                }
13057                if (args.isFwdLocked()) {
13058                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13059                }
13060
13061                synchronized (mInstallLock) {
13062                    PackageParser.Package pkg = null;
13063                    try {
13064                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13065                    } catch (PackageManagerException e) {
13066                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13067                    }
13068                    // Scan the package
13069                    if (pkg != null) {
13070                        /*
13071                         * TODO why is the lock being held? doPostInstall is
13072                         * called in other places without the lock. This needs
13073                         * to be straightened out.
13074                         */
13075                        // writer
13076                        synchronized (mPackages) {
13077                            retCode = PackageManager.INSTALL_SUCCEEDED;
13078                            pkgList.add(pkg.packageName);
13079                            // Post process args
13080                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13081                                    pkg.applicationInfo.uid);
13082                        }
13083                    } else {
13084                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13085                    }
13086                }
13087
13088            } finally {
13089                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13090                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13091                }
13092            }
13093        }
13094        // writer
13095        synchronized (mPackages) {
13096            // If the platform SDK has changed since the last time we booted,
13097            // we need to re-grant app permission to catch any new ones that
13098            // appear. This is really a hack, and means that apps can in some
13099            // cases get permissions that the user didn't initially explicitly
13100            // allow... it would be nice to have some better way to handle
13101            // this situation.
13102            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13103            if (regrantPermissions)
13104                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13105                        + mSdkVersion + "; regranting permissions for external storage");
13106            mSettings.mExternalSdkPlatform = mSdkVersion;
13107
13108            // Make sure group IDs have been assigned, and any permission
13109            // changes in other apps are accounted for
13110            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13111                    | (regrantPermissions
13112                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13113                            : 0));
13114
13115            mSettings.updateExternalDatabaseVersion();
13116
13117            // can downgrade to reader
13118            // Persist settings
13119            mSettings.writeLPr();
13120        }
13121        // Send a broadcast to let everyone know we are done processing
13122        if (pkgList.size() > 0) {
13123            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13124        }
13125    }
13126
13127   /*
13128     * Utility method to unload a list of specified containers
13129     */
13130    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13131        // Just unmount all valid containers.
13132        for (AsecInstallArgs arg : cidArgs) {
13133            synchronized (mInstallLock) {
13134                arg.doPostDeleteLI(false);
13135           }
13136       }
13137   }
13138
13139    /*
13140     * Unload packages mounted on external media. This involves deleting package
13141     * data from internal structures, sending broadcasts about diabled packages,
13142     * gc'ing to free up references, unmounting all secure containers
13143     * corresponding to packages on external media, and posting a
13144     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13145     * that we always have to post this message if status has been requested no
13146     * matter what.
13147     */
13148    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13149            final boolean reportStatus) {
13150        if (DEBUG_SD_INSTALL)
13151            Log.i(TAG, "unloading media packages");
13152        ArrayList<String> pkgList = new ArrayList<String>();
13153        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13154        final Set<AsecInstallArgs> keys = processCids.keySet();
13155        for (AsecInstallArgs args : keys) {
13156            String pkgName = args.getPackageName();
13157            if (DEBUG_SD_INSTALL)
13158                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13159            // Delete package internally
13160            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13161            synchronized (mInstallLock) {
13162                boolean res = deletePackageLI(pkgName, null, false, null, null,
13163                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13164                if (res) {
13165                    pkgList.add(pkgName);
13166                } else {
13167                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13168                    failedList.add(args);
13169                }
13170            }
13171        }
13172
13173        // reader
13174        synchronized (mPackages) {
13175            // We didn't update the settings after removing each package;
13176            // write them now for all packages.
13177            mSettings.writeLPr();
13178        }
13179
13180        // We have to absolutely send UPDATED_MEDIA_STATUS only
13181        // after confirming that all the receivers processed the ordered
13182        // broadcast when packages get disabled, force a gc to clean things up.
13183        // and unload all the containers.
13184        if (pkgList.size() > 0) {
13185            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13186                    new IIntentReceiver.Stub() {
13187                public void performReceive(Intent intent, int resultCode, String data,
13188                        Bundle extras, boolean ordered, boolean sticky,
13189                        int sendingUser) throws RemoteException {
13190                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13191                            reportStatus ? 1 : 0, 1, keys);
13192                    mHandler.sendMessage(msg);
13193                }
13194            });
13195        } else {
13196            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13197                    keys);
13198            mHandler.sendMessage(msg);
13199        }
13200    }
13201
13202    /** Binder call */
13203    @Override
13204    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13205            final int flags) {
13206        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13207        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13208        int returnCode = PackageManager.MOVE_SUCCEEDED;
13209        int currInstallFlags = 0;
13210        int newInstallFlags = 0;
13211
13212        File codeFile = null;
13213        String installerPackageName = null;
13214        String packageAbiOverride = null;
13215
13216        // reader
13217        synchronized (mPackages) {
13218            final PackageParser.Package pkg = mPackages.get(packageName);
13219            final PackageSetting ps = mSettings.mPackages.get(packageName);
13220            if (pkg == null || ps == null) {
13221                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13222            } else {
13223                // Disable moving fwd locked apps and system packages
13224                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13225                    Slog.w(TAG, "Cannot move system application");
13226                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13227                } else if (pkg.mOperationPending) {
13228                    Slog.w(TAG, "Attempt to move package which has pending operations");
13229                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13230                } else {
13231                    // Find install location first
13232                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13233                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13234                        Slog.w(TAG, "Ambigous flags specified for move location.");
13235                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13236                    } else {
13237                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13238                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13239                        currInstallFlags = isExternal(pkg)
13240                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13241
13242                        if (newInstallFlags == currInstallFlags) {
13243                            Slog.w(TAG, "No move required. Trying to move to same location");
13244                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13245                        } else {
13246                            if (pkg.isForwardLocked()) {
13247                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13248                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13249                            }
13250                        }
13251                    }
13252                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13253                        pkg.mOperationPending = true;
13254                    }
13255                }
13256
13257                codeFile = new File(pkg.codePath);
13258                installerPackageName = ps.installerPackageName;
13259                packageAbiOverride = ps.cpuAbiOverrideString;
13260            }
13261        }
13262
13263        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13264            try {
13265                observer.packageMoved(packageName, returnCode);
13266            } catch (RemoteException ignored) {
13267            }
13268            return;
13269        }
13270
13271        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13272            @Override
13273            public void onUserActionRequired(Intent intent) throws RemoteException {
13274                throw new IllegalStateException();
13275            }
13276
13277            @Override
13278            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13279                    Bundle extras) throws RemoteException {
13280                Slog.d(TAG, "Install result for move: "
13281                        + PackageManager.installStatusToString(returnCode, msg));
13282
13283                // We usually have a new package now after the install, but if
13284                // we failed we need to clear the pending flag on the original
13285                // package object.
13286                synchronized (mPackages) {
13287                    final PackageParser.Package pkg = mPackages.get(packageName);
13288                    if (pkg != null) {
13289                        pkg.mOperationPending = false;
13290                    }
13291                }
13292
13293                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13294                switch (status) {
13295                    case PackageInstaller.STATUS_SUCCESS:
13296                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13297                        break;
13298                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13299                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13300                        break;
13301                    default:
13302                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13303                        break;
13304                }
13305            }
13306        };
13307
13308        // Treat a move like reinstalling an existing app, which ensures that we
13309        // process everythign uniformly, like unpacking native libraries.
13310        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13311
13312        final Message msg = mHandler.obtainMessage(INIT_COPY);
13313        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13314        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13315                installerPackageName, null, user, packageAbiOverride);
13316        mHandler.sendMessage(msg);
13317    }
13318
13319    @Override
13320    public boolean setInstallLocation(int loc) {
13321        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13322                null);
13323        if (getInstallLocation() == loc) {
13324            return true;
13325        }
13326        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13327                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13328            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13329                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13330            return true;
13331        }
13332        return false;
13333   }
13334
13335    @Override
13336    public int getInstallLocation() {
13337        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13338                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13339                PackageHelper.APP_INSTALL_AUTO);
13340    }
13341
13342    /** Called by UserManagerService */
13343    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13344        mDirtyUsers.remove(userHandle);
13345        mSettings.removeUserLPw(userHandle);
13346        mPendingBroadcasts.remove(userHandle);
13347        if (mInstaller != null) {
13348            // Technically, we shouldn't be doing this with the package lock
13349            // held.  However, this is very rare, and there is already so much
13350            // other disk I/O going on, that we'll let it slide for now.
13351            mInstaller.removeUserDataDirs(userHandle);
13352        }
13353        mUserNeedsBadging.delete(userHandle);
13354        removeUnusedPackagesLILPw(userManager, userHandle);
13355    }
13356
13357    /**
13358     * We're removing userHandle and would like to remove any downloaded packages
13359     * that are no longer in use by any other user.
13360     * @param userHandle the user being removed
13361     */
13362    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13363        final boolean DEBUG_CLEAN_APKS = false;
13364        int [] users = userManager.getUserIdsLPr();
13365        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13366        while (psit.hasNext()) {
13367            PackageSetting ps = psit.next();
13368            if (ps.pkg == null) {
13369                continue;
13370            }
13371            final String packageName = ps.pkg.packageName;
13372            // Skip over if system app
13373            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13374                continue;
13375            }
13376            if (DEBUG_CLEAN_APKS) {
13377                Slog.i(TAG, "Checking package " + packageName);
13378            }
13379            boolean keep = false;
13380            for (int i = 0; i < users.length; i++) {
13381                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13382                    keep = true;
13383                    if (DEBUG_CLEAN_APKS) {
13384                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13385                                + users[i]);
13386                    }
13387                    break;
13388                }
13389            }
13390            if (!keep) {
13391                if (DEBUG_CLEAN_APKS) {
13392                    Slog.i(TAG, "  Removing package " + packageName);
13393                }
13394                mHandler.post(new Runnable() {
13395                    public void run() {
13396                        deletePackageX(packageName, userHandle, 0);
13397                    } //end run
13398                });
13399            }
13400        }
13401    }
13402
13403    /** Called by UserManagerService */
13404    void createNewUserLILPw(int userHandle, File path) {
13405        if (mInstaller != null) {
13406            mInstaller.createUserConfig(userHandle);
13407            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13408        }
13409    }
13410
13411    void newUserCreatedLILPw(int userHandle) {
13412        // Adding a user requires updating runtime permissions for system apps.
13413        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
13414    }
13415
13416    @Override
13417    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13418        mContext.enforceCallingOrSelfPermission(
13419                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13420                "Only package verification agents can read the verifier device identity");
13421
13422        synchronized (mPackages) {
13423            return mSettings.getVerifierDeviceIdentityLPw();
13424        }
13425    }
13426
13427    @Override
13428    public void setPermissionEnforced(String permission, boolean enforced) {
13429        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13430        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13431            synchronized (mPackages) {
13432                if (mSettings.mReadExternalStorageEnforced == null
13433                        || mSettings.mReadExternalStorageEnforced != enforced) {
13434                    mSettings.mReadExternalStorageEnforced = enforced;
13435                    mSettings.writeLPr();
13436                }
13437            }
13438            // kill any non-foreground processes so we restart them and
13439            // grant/revoke the GID.
13440            final IActivityManager am = ActivityManagerNative.getDefault();
13441            if (am != null) {
13442                final long token = Binder.clearCallingIdentity();
13443                try {
13444                    am.killProcessesBelowForeground("setPermissionEnforcement");
13445                } catch (RemoteException e) {
13446                } finally {
13447                    Binder.restoreCallingIdentity(token);
13448                }
13449            }
13450        } else {
13451            throw new IllegalArgumentException("No selective enforcement for " + permission);
13452        }
13453    }
13454
13455    @Override
13456    @Deprecated
13457    public boolean isPermissionEnforced(String permission) {
13458        return true;
13459    }
13460
13461    @Override
13462    public boolean isStorageLow() {
13463        final long token = Binder.clearCallingIdentity();
13464        try {
13465            final DeviceStorageMonitorInternal
13466                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13467            if (dsm != null) {
13468                return dsm.isMemoryLow();
13469            } else {
13470                return false;
13471            }
13472        } finally {
13473            Binder.restoreCallingIdentity(token);
13474        }
13475    }
13476
13477    @Override
13478    public IPackageInstaller getPackageInstaller() {
13479        return mInstallerService;
13480    }
13481
13482    private boolean userNeedsBadging(int userId) {
13483        int index = mUserNeedsBadging.indexOfKey(userId);
13484        if (index < 0) {
13485            final UserInfo userInfo;
13486            final long token = Binder.clearCallingIdentity();
13487            try {
13488                userInfo = sUserManager.getUserInfo(userId);
13489            } finally {
13490                Binder.restoreCallingIdentity(token);
13491            }
13492            final boolean b;
13493            if (userInfo != null && userInfo.isManagedProfile()) {
13494                b = true;
13495            } else {
13496                b = false;
13497            }
13498            mUserNeedsBadging.put(userId, b);
13499            return b;
13500        }
13501        return mUserNeedsBadging.valueAt(index);
13502    }
13503
13504    @Override
13505    public KeySet getKeySetByAlias(String packageName, String alias) {
13506        if (packageName == null || alias == null) {
13507            return null;
13508        }
13509        synchronized(mPackages) {
13510            final PackageParser.Package pkg = mPackages.get(packageName);
13511            if (pkg == null) {
13512                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13513                throw new IllegalArgumentException("Unknown package: " + packageName);
13514            }
13515            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13516            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13517        }
13518    }
13519
13520    @Override
13521    public KeySet getSigningKeySet(String packageName) {
13522        if (packageName == null) {
13523            return null;
13524        }
13525        synchronized(mPackages) {
13526            final PackageParser.Package pkg = mPackages.get(packageName);
13527            if (pkg == null) {
13528                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13529                throw new IllegalArgumentException("Unknown package: " + packageName);
13530            }
13531            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13532                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13533                throw new SecurityException("May not access signing KeySet of other apps.");
13534            }
13535            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13536            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13537        }
13538    }
13539
13540    @Override
13541    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13542        if (packageName == null || ks == null) {
13543            return false;
13544        }
13545        synchronized(mPackages) {
13546            final PackageParser.Package pkg = mPackages.get(packageName);
13547            if (pkg == null) {
13548                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13549                throw new IllegalArgumentException("Unknown package: " + packageName);
13550            }
13551            IBinder ksh = ks.getToken();
13552            if (ksh instanceof KeySetHandle) {
13553                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13554                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13555            }
13556            return false;
13557        }
13558    }
13559
13560    @Override
13561    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13562        if (packageName == null || ks == null) {
13563            return false;
13564        }
13565        synchronized(mPackages) {
13566            final PackageParser.Package pkg = mPackages.get(packageName);
13567            if (pkg == null) {
13568                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13569                throw new IllegalArgumentException("Unknown package: " + packageName);
13570            }
13571            IBinder ksh = ks.getToken();
13572            if (ksh instanceof KeySetHandle) {
13573                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13574                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13575            }
13576            return false;
13577        }
13578    }
13579
13580    public void getUsageStatsIfNoPackageUsageInfo() {
13581        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13582            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13583            if (usm == null) {
13584                throw new IllegalStateException("UsageStatsManager must be initialized");
13585            }
13586            long now = System.currentTimeMillis();
13587            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13588            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13589                String packageName = entry.getKey();
13590                PackageParser.Package pkg = mPackages.get(packageName);
13591                if (pkg == null) {
13592                    continue;
13593                }
13594                UsageStats usage = entry.getValue();
13595                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13596                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13597            }
13598        }
13599    }
13600
13601    /**
13602     * Check and throw if the given before/after packages would be considered a
13603     * downgrade.
13604     */
13605    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13606            throws PackageManagerException {
13607        if (after.versionCode < before.mVersionCode) {
13608            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13609                    "Update version code " + after.versionCode + " is older than current "
13610                    + before.mVersionCode);
13611        } else if (after.versionCode == before.mVersionCode) {
13612            if (after.baseRevisionCode < before.baseRevisionCode) {
13613                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13614                        "Update base revision code " + after.baseRevisionCode
13615                        + " is older than current " + before.baseRevisionCode);
13616            }
13617
13618            if (!ArrayUtils.isEmpty(after.splitNames)) {
13619                for (int i = 0; i < after.splitNames.length; i++) {
13620                    final String splitName = after.splitNames[i];
13621                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13622                    if (j != -1) {
13623                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13624                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13625                                    "Update split " + splitName + " revision code "
13626                                    + after.splitRevisionCodes[i] + " is older than current "
13627                                    + before.splitRevisionCodes[j]);
13628                        }
13629                    }
13630                }
13631            }
13632        }
13633    }
13634}
13635