PackageManagerService.java revision 9041df7f6948f5314b576c437f08247967ac2c2f
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    private static final boolean RUNTIME_PERMISSIONS_ENABLED =
252            SystemProperties.getInt("ro.runtime.premissions.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 permission. */
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            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1815                    | (regrantPermissions
1816                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1817                            : 0));
1818
1819            // If this is the first boot, and it is a normal boot, then
1820            // we need to initialize the default preferred apps.
1821            if (!mRestoredSettings && !onlyCore) {
1822                mSettings.readDefaultPreferredAppsLPw(this, 0);
1823            }
1824
1825            // If this is first boot after an OTA, and a normal boot, then
1826            // we need to clear code cache directories.
1827            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1828            if (mIsUpgrade && !onlyCore) {
1829                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1830                for (String pkgName : mSettings.mPackages.keySet()) {
1831                    deleteCodeCacheDirsLI(pkgName);
1832                }
1833                mSettings.mFingerprint = Build.FINGERPRINT;
1834            }
1835
1836            // All the changes are done during package scanning.
1837            mSettings.updateInternalDatabaseVersion();
1838
1839            // can downgrade to reader
1840            mSettings.writeLPr();
1841
1842            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1843                    SystemClock.uptimeMillis());
1844
1845
1846            mRequiredVerifierPackage = getRequiredVerifierLPr();
1847        } // synchronized (mPackages)
1848        } // synchronized (mInstallLock)
1849
1850        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1851
1852        // Now after opening every single application zip, make sure they
1853        // are all flushed.  Not really needed, but keeps things nice and
1854        // tidy.
1855        Runtime.getRuntime().gc();
1856    }
1857
1858    @Override
1859    public boolean isFirstBoot() {
1860        return !mRestoredSettings;
1861    }
1862
1863    @Override
1864    public boolean isOnlyCoreApps() {
1865        return mOnlyCore;
1866    }
1867
1868    @Override
1869    public boolean isUpgrade() {
1870        return mIsUpgrade;
1871    }
1872
1873    private String getRequiredVerifierLPr() {
1874        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1875        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1876                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1877
1878        String requiredVerifier = null;
1879
1880        final int N = receivers.size();
1881        for (int i = 0; i < N; i++) {
1882            final ResolveInfo info = receivers.get(i);
1883
1884            if (info.activityInfo == null) {
1885                continue;
1886            }
1887
1888            final String packageName = info.activityInfo.packageName;
1889
1890            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
1891                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
1892                continue;
1893            }
1894
1895            if (requiredVerifier != null) {
1896                throw new RuntimeException("There can be only one required verifier");
1897            }
1898
1899            requiredVerifier = packageName;
1900        }
1901
1902        return requiredVerifier;
1903    }
1904
1905    @Override
1906    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1907            throws RemoteException {
1908        try {
1909            return super.onTransact(code, data, reply, flags);
1910        } catch (RuntimeException e) {
1911            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1912                Slog.wtf(TAG, "Package Manager Crash", e);
1913            }
1914            throw e;
1915        }
1916    }
1917
1918    void cleanupInstallFailedPackage(PackageSetting ps) {
1919        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1920
1921        removeDataDirsLI(ps.name);
1922        if (ps.codePath != null) {
1923            if (ps.codePath.isDirectory()) {
1924                FileUtils.deleteContents(ps.codePath);
1925            }
1926            ps.codePath.delete();
1927        }
1928        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1929            if (ps.resourcePath.isDirectory()) {
1930                FileUtils.deleteContents(ps.resourcePath);
1931            }
1932            ps.resourcePath.delete();
1933        }
1934        mSettings.removePackageLPw(ps.name);
1935    }
1936
1937    static int[] appendInts(int[] cur, int[] add) {
1938        if (add == null) return cur;
1939        if (cur == null) return add;
1940        final int N = add.length;
1941        for (int i=0; i<N; i++) {
1942            cur = appendInt(cur, add[i]);
1943        }
1944        return cur;
1945    }
1946
1947    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1948        if (!sUserManager.exists(userId)) return null;
1949        final PackageSetting ps = (PackageSetting) p.mExtras;
1950        if (ps == null) {
1951            return null;
1952        }
1953
1954        PermissionsState permissionsState = ps.getPermissionsState();
1955
1956        final int[] gids = permissionsState.computeGids(userId);
1957        Set<String> permissions = permissionsState.getPermissions(userId);
1958
1959        final PackageUserState state = ps.readUserState(userId);
1960        return PackageParser.generatePackageInfo(p, gids, flags,
1961                ps.firstInstallTime, ps.lastUpdateTime, permissions,
1962                state, userId);
1963    }
1964
1965    @Override
1966    public boolean isPackageAvailable(String packageName, int userId) {
1967        if (!sUserManager.exists(userId)) return false;
1968        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1969        synchronized (mPackages) {
1970            PackageParser.Package p = mPackages.get(packageName);
1971            if (p != null) {
1972                final PackageSetting ps = (PackageSetting) p.mExtras;
1973                if (ps != null) {
1974                    final PackageUserState state = ps.readUserState(userId);
1975                    if (state != null) {
1976                        return PackageParser.isAvailable(state);
1977                    }
1978                }
1979            }
1980        }
1981        return false;
1982    }
1983
1984    @Override
1985    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1986        if (!sUserManager.exists(userId)) return null;
1987        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1988        // reader
1989        synchronized (mPackages) {
1990            PackageParser.Package p = mPackages.get(packageName);
1991            if (DEBUG_PACKAGE_INFO)
1992                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1993            if (p != null) {
1994                return generatePackageInfo(p, flags, userId);
1995            }
1996            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1997                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1998            }
1999        }
2000        return null;
2001    }
2002
2003    @Override
2004    public String[] currentToCanonicalPackageNames(String[] names) {
2005        String[] out = new String[names.length];
2006        // reader
2007        synchronized (mPackages) {
2008            for (int i=names.length-1; i>=0; i--) {
2009                PackageSetting ps = mSettings.mPackages.get(names[i]);
2010                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2011            }
2012        }
2013        return out;
2014    }
2015
2016    @Override
2017    public String[] canonicalToCurrentPackageNames(String[] names) {
2018        String[] out = new String[names.length];
2019        // reader
2020        synchronized (mPackages) {
2021            for (int i=names.length-1; i>=0; i--) {
2022                String cur = mSettings.mRenamedPackages.get(names[i]);
2023                out[i] = cur != null ? cur : names[i];
2024            }
2025        }
2026        return out;
2027    }
2028
2029    @Override
2030    public int getPackageUid(String packageName, int userId) {
2031        if (!sUserManager.exists(userId)) return -1;
2032        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2033
2034        // reader
2035        synchronized (mPackages) {
2036            PackageParser.Package p = mPackages.get(packageName);
2037            if(p != null) {
2038                return UserHandle.getUid(userId, p.applicationInfo.uid);
2039            }
2040            PackageSetting ps = mSettings.mPackages.get(packageName);
2041            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2042                return -1;
2043            }
2044            p = ps.pkg;
2045            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2046        }
2047    }
2048
2049    @Override
2050    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2051        if (!sUserManager.exists(userId)) {
2052            return null;
2053        }
2054
2055        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2056                "getPackageGids");
2057
2058        // reader
2059        synchronized (mPackages) {
2060            PackageParser.Package p = mPackages.get(packageName);
2061            if (DEBUG_PACKAGE_INFO) {
2062                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2063            }
2064            if (p != null) {
2065                PackageSetting ps = (PackageSetting) p.mExtras;
2066                return ps.getPermissionsState().computeGids(userId);
2067            }
2068        }
2069
2070        return null;
2071    }
2072
2073    static PermissionInfo generatePermissionInfo(
2074            BasePermission bp, int flags) {
2075        if (bp.perm != null) {
2076            return PackageParser.generatePermissionInfo(bp.perm, flags);
2077        }
2078        PermissionInfo pi = new PermissionInfo();
2079        pi.name = bp.name;
2080        pi.packageName = bp.sourcePackage;
2081        pi.nonLocalizedLabel = bp.name;
2082        pi.protectionLevel = bp.protectionLevel;
2083        return pi;
2084    }
2085
2086    @Override
2087    public PermissionInfo getPermissionInfo(String name, int flags) {
2088        // reader
2089        synchronized (mPackages) {
2090            final BasePermission p = mSettings.mPermissions.get(name);
2091            if (p != null) {
2092                return generatePermissionInfo(p, flags);
2093            }
2094            return null;
2095        }
2096    }
2097
2098    @Override
2099    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2100        // reader
2101        synchronized (mPackages) {
2102            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2103            for (BasePermission p : mSettings.mPermissions.values()) {
2104                if (group == null) {
2105                    if (p.perm == null || p.perm.info.group == null) {
2106                        out.add(generatePermissionInfo(p, flags));
2107                    }
2108                } else {
2109                    if (p.perm != null && group.equals(p.perm.info.group)) {
2110                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2111                    }
2112                }
2113            }
2114
2115            if (out.size() > 0) {
2116                return out;
2117            }
2118            return mPermissionGroups.containsKey(group) ? out : null;
2119        }
2120    }
2121
2122    @Override
2123    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2124        // reader
2125        synchronized (mPackages) {
2126            return PackageParser.generatePermissionGroupInfo(
2127                    mPermissionGroups.get(name), flags);
2128        }
2129    }
2130
2131    @Override
2132    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2133        // reader
2134        synchronized (mPackages) {
2135            final int N = mPermissionGroups.size();
2136            ArrayList<PermissionGroupInfo> out
2137                    = new ArrayList<PermissionGroupInfo>(N);
2138            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2139                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2140            }
2141            return out;
2142        }
2143    }
2144
2145    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2146            int userId) {
2147        if (!sUserManager.exists(userId)) return null;
2148        PackageSetting ps = mSettings.mPackages.get(packageName);
2149        if (ps != null) {
2150            if (ps.pkg == null) {
2151                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2152                        flags, userId);
2153                if (pInfo != null) {
2154                    return pInfo.applicationInfo;
2155                }
2156                return null;
2157            }
2158            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2159                    ps.readUserState(userId), userId);
2160        }
2161        return null;
2162    }
2163
2164    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2165            int userId) {
2166        if (!sUserManager.exists(userId)) return null;
2167        PackageSetting ps = mSettings.mPackages.get(packageName);
2168        if (ps != null) {
2169            PackageParser.Package pkg = ps.pkg;
2170            if (pkg == null) {
2171                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2172                    return null;
2173                }
2174                // Only data remains, so we aren't worried about code paths
2175                pkg = new PackageParser.Package(packageName);
2176                pkg.applicationInfo.packageName = packageName;
2177                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2178                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2179                pkg.applicationInfo.dataDir =
2180                        getDataPathForPackage(packageName, 0).getPath();
2181                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2182                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2183            }
2184            return generatePackageInfo(pkg, flags, userId);
2185        }
2186        return null;
2187    }
2188
2189    @Override
2190    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2191        if (!sUserManager.exists(userId)) return null;
2192        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2193        // writer
2194        synchronized (mPackages) {
2195            PackageParser.Package p = mPackages.get(packageName);
2196            if (DEBUG_PACKAGE_INFO) Log.v(
2197                    TAG, "getApplicationInfo " + packageName
2198                    + ": " + p);
2199            if (p != null) {
2200                PackageSetting ps = mSettings.mPackages.get(packageName);
2201                if (ps == null) return null;
2202                // Note: isEnabledLP() does not apply here - always return info
2203                return PackageParser.generateApplicationInfo(
2204                        p, flags, ps.readUserState(userId), userId);
2205            }
2206            if ("android".equals(packageName)||"system".equals(packageName)) {
2207                return mAndroidApplication;
2208            }
2209            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2210                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2211            }
2212        }
2213        return null;
2214    }
2215
2216
2217    @Override
2218    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2219        mContext.enforceCallingOrSelfPermission(
2220                android.Manifest.permission.CLEAR_APP_CACHE, null);
2221        // Queue up an async operation since clearing cache may take a little while.
2222        mHandler.post(new Runnable() {
2223            public void run() {
2224                mHandler.removeCallbacks(this);
2225                int retCode = -1;
2226                synchronized (mInstallLock) {
2227                    retCode = mInstaller.freeCache(freeStorageSize);
2228                    if (retCode < 0) {
2229                        Slog.w(TAG, "Couldn't clear application caches");
2230                    }
2231                }
2232                if (observer != null) {
2233                    try {
2234                        observer.onRemoveCompleted(null, (retCode >= 0));
2235                    } catch (RemoteException e) {
2236                        Slog.w(TAG, "RemoveException when invoking call back");
2237                    }
2238                }
2239            }
2240        });
2241    }
2242
2243    @Override
2244    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2245        mContext.enforceCallingOrSelfPermission(
2246                android.Manifest.permission.CLEAR_APP_CACHE, null);
2247        // Queue up an async operation since clearing cache may take a little while.
2248        mHandler.post(new Runnable() {
2249            public void run() {
2250                mHandler.removeCallbacks(this);
2251                int retCode = -1;
2252                synchronized (mInstallLock) {
2253                    retCode = mInstaller.freeCache(freeStorageSize);
2254                    if (retCode < 0) {
2255                        Slog.w(TAG, "Couldn't clear application caches");
2256                    }
2257                }
2258                if(pi != null) {
2259                    try {
2260                        // Callback via pending intent
2261                        int code = (retCode >= 0) ? 1 : 0;
2262                        pi.sendIntent(null, code, null,
2263                                null, null);
2264                    } catch (SendIntentException e1) {
2265                        Slog.i(TAG, "Failed to send pending intent");
2266                    }
2267                }
2268            }
2269        });
2270    }
2271
2272    void freeStorage(long freeStorageSize) throws IOException {
2273        synchronized (mInstallLock) {
2274            if (mInstaller.freeCache(freeStorageSize) < 0) {
2275                throw new IOException("Failed to free enough space");
2276            }
2277        }
2278    }
2279
2280    @Override
2281    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2282        if (!sUserManager.exists(userId)) return null;
2283        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2284        synchronized (mPackages) {
2285            PackageParser.Activity a = mActivities.mActivities.get(component);
2286
2287            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2288            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2289                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2290                if (ps == null) return null;
2291                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2292                        userId);
2293            }
2294            if (mResolveComponentName.equals(component)) {
2295                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2296                        new PackageUserState(), userId);
2297            }
2298        }
2299        return null;
2300    }
2301
2302    @Override
2303    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2304            String resolvedType) {
2305        synchronized (mPackages) {
2306            PackageParser.Activity a = mActivities.mActivities.get(component);
2307            if (a == null) {
2308                return false;
2309            }
2310            for (int i=0; i<a.intents.size(); i++) {
2311                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2312                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2313                    return true;
2314                }
2315            }
2316            return false;
2317        }
2318    }
2319
2320    @Override
2321    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2322        if (!sUserManager.exists(userId)) return null;
2323        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2324        synchronized (mPackages) {
2325            PackageParser.Activity a = mReceivers.mActivities.get(component);
2326            if (DEBUG_PACKAGE_INFO) Log.v(
2327                TAG, "getReceiverInfo " + component + ": " + a);
2328            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2329                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2330                if (ps == null) return null;
2331                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2332                        userId);
2333            }
2334        }
2335        return null;
2336    }
2337
2338    @Override
2339    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2340        if (!sUserManager.exists(userId)) return null;
2341        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2342        synchronized (mPackages) {
2343            PackageParser.Service s = mServices.mServices.get(component);
2344            if (DEBUG_PACKAGE_INFO) Log.v(
2345                TAG, "getServiceInfo " + component + ": " + s);
2346            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2347                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2348                if (ps == null) return null;
2349                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2350                        userId);
2351            }
2352        }
2353        return null;
2354    }
2355
2356    @Override
2357    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2358        if (!sUserManager.exists(userId)) return null;
2359        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2360        synchronized (mPackages) {
2361            PackageParser.Provider p = mProviders.mProviders.get(component);
2362            if (DEBUG_PACKAGE_INFO) Log.v(
2363                TAG, "getProviderInfo " + component + ": " + p);
2364            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2365                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2366                if (ps == null) return null;
2367                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2368                        userId);
2369            }
2370        }
2371        return null;
2372    }
2373
2374    @Override
2375    public String[] getSystemSharedLibraryNames() {
2376        Set<String> libSet;
2377        synchronized (mPackages) {
2378            libSet = mSharedLibraries.keySet();
2379            int size = libSet.size();
2380            if (size > 0) {
2381                String[] libs = new String[size];
2382                libSet.toArray(libs);
2383                return libs;
2384            }
2385        }
2386        return null;
2387    }
2388
2389    /**
2390     * @hide
2391     */
2392    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2393        synchronized (mPackages) {
2394            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2395            if (lib != null && lib.apk != null) {
2396                return mPackages.get(lib.apk);
2397            }
2398        }
2399        return null;
2400    }
2401
2402    @Override
2403    public FeatureInfo[] getSystemAvailableFeatures() {
2404        Collection<FeatureInfo> featSet;
2405        synchronized (mPackages) {
2406            featSet = mAvailableFeatures.values();
2407            int size = featSet.size();
2408            if (size > 0) {
2409                FeatureInfo[] features = new FeatureInfo[size+1];
2410                featSet.toArray(features);
2411                FeatureInfo fi = new FeatureInfo();
2412                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2413                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2414                features[size] = fi;
2415                return features;
2416            }
2417        }
2418        return null;
2419    }
2420
2421    @Override
2422    public boolean hasSystemFeature(String name) {
2423        synchronized (mPackages) {
2424            return mAvailableFeatures.containsKey(name);
2425        }
2426    }
2427
2428    private void checkValidCaller(int uid, int userId) {
2429        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2430            return;
2431
2432        throw new SecurityException("Caller uid=" + uid
2433                + " is not privileged to communicate with user=" + userId);
2434    }
2435
2436    @Override
2437    public int checkPermission(String permName, String pkgName, int userId) {
2438        if (!sUserManager.exists(userId)) {
2439            return PackageManager.PERMISSION_DENIED;
2440        }
2441
2442        synchronized (mPackages) {
2443            final PackageParser.Package p = mPackages.get(pkgName);
2444            if (p != null && p.mExtras != null) {
2445                final PackageSetting ps = (PackageSetting) p.mExtras;
2446                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2447                    return PackageManager.PERMISSION_GRANTED;
2448                }
2449            }
2450        }
2451
2452        return PackageManager.PERMISSION_DENIED;
2453    }
2454
2455    @Override
2456    public int checkUidPermission(String permName, int uid) {
2457        final int userId = UserHandle.getUserId(uid);
2458
2459        if (!sUserManager.exists(userId)) {
2460            return PackageManager.PERMISSION_DENIED;
2461        }
2462
2463        synchronized (mPackages) {
2464            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2465            if (obj != null) {
2466                final SettingBase ps = (SettingBase) obj;
2467                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2468                    return PackageManager.PERMISSION_GRANTED;
2469                }
2470            } else {
2471                ArraySet<String> perms = mSystemPermissions.get(uid);
2472                if (perms != null && perms.contains(permName)) {
2473                    return PackageManager.PERMISSION_GRANTED;
2474                }
2475            }
2476        }
2477
2478        return PackageManager.PERMISSION_DENIED;
2479    }
2480
2481    /**
2482     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2483     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2484     * @param checkShell TODO(yamasani):
2485     * @param message the message to log on security exception
2486     */
2487    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2488            boolean checkShell, String message) {
2489        if (userId < 0) {
2490            throw new IllegalArgumentException("Invalid userId " + userId);
2491        }
2492        if (checkShell) {
2493            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2494        }
2495        if (userId == UserHandle.getUserId(callingUid)) return;
2496        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2497            if (requireFullPermission) {
2498                mContext.enforceCallingOrSelfPermission(
2499                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2500            } else {
2501                try {
2502                    mContext.enforceCallingOrSelfPermission(
2503                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2504                } catch (SecurityException se) {
2505                    mContext.enforceCallingOrSelfPermission(
2506                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2507                }
2508            }
2509        }
2510    }
2511
2512    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2513        if (callingUid == Process.SHELL_UID) {
2514            if (userHandle >= 0
2515                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2516                throw new SecurityException("Shell does not have permission to access user "
2517                        + userHandle);
2518            } else if (userHandle < 0) {
2519                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2520                        + Debug.getCallers(3));
2521            }
2522        }
2523    }
2524
2525    private BasePermission findPermissionTreeLP(String permName) {
2526        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2527            if (permName.startsWith(bp.name) &&
2528                    permName.length() > bp.name.length() &&
2529                    permName.charAt(bp.name.length()) == '.') {
2530                return bp;
2531            }
2532        }
2533        return null;
2534    }
2535
2536    private BasePermission checkPermissionTreeLP(String permName) {
2537        if (permName != null) {
2538            BasePermission bp = findPermissionTreeLP(permName);
2539            if (bp != null) {
2540                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2541                    return bp;
2542                }
2543                throw new SecurityException("Calling uid "
2544                        + Binder.getCallingUid()
2545                        + " is not allowed to add to permission tree "
2546                        + bp.name + " owned by uid " + bp.uid);
2547            }
2548        }
2549        throw new SecurityException("No permission tree found for " + permName);
2550    }
2551
2552    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2553        if (s1 == null) {
2554            return s2 == null;
2555        }
2556        if (s2 == null) {
2557            return false;
2558        }
2559        if (s1.getClass() != s2.getClass()) {
2560            return false;
2561        }
2562        return s1.equals(s2);
2563    }
2564
2565    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2566        if (pi1.icon != pi2.icon) return false;
2567        if (pi1.logo != pi2.logo) return false;
2568        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2569        if (!compareStrings(pi1.name, pi2.name)) return false;
2570        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2571        // We'll take care of setting this one.
2572        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2573        // These are not currently stored in settings.
2574        //if (!compareStrings(pi1.group, pi2.group)) return false;
2575        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2576        //if (pi1.labelRes != pi2.labelRes) return false;
2577        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2578        return true;
2579    }
2580
2581    int permissionInfoFootprint(PermissionInfo info) {
2582        int size = info.name.length();
2583        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2584        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2585        return size;
2586    }
2587
2588    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2589        int size = 0;
2590        for (BasePermission perm : mSettings.mPermissions.values()) {
2591            if (perm.uid == tree.uid) {
2592                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2593            }
2594        }
2595        return size;
2596    }
2597
2598    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2599        // We calculate the max size of permissions defined by this uid and throw
2600        // if that plus the size of 'info' would exceed our stated maximum.
2601        if (tree.uid != Process.SYSTEM_UID) {
2602            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2603            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2604                throw new SecurityException("Permission tree size cap exceeded");
2605            }
2606        }
2607    }
2608
2609    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2610        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2611            throw new SecurityException("Label must be specified in permission");
2612        }
2613        BasePermission tree = checkPermissionTreeLP(info.name);
2614        BasePermission bp = mSettings.mPermissions.get(info.name);
2615        boolean added = bp == null;
2616        boolean changed = true;
2617        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2618        if (added) {
2619            enforcePermissionCapLocked(info, tree);
2620            bp = new BasePermission(info.name, tree.sourcePackage,
2621                    BasePermission.TYPE_DYNAMIC);
2622        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2623            throw new SecurityException(
2624                    "Not allowed to modify non-dynamic permission "
2625                    + info.name);
2626        } else {
2627            if (bp.protectionLevel == fixedLevel
2628                    && bp.perm.owner.equals(tree.perm.owner)
2629                    && bp.uid == tree.uid
2630                    && comparePermissionInfos(bp.perm.info, info)) {
2631                changed = false;
2632            }
2633        }
2634        bp.protectionLevel = fixedLevel;
2635        info = new PermissionInfo(info);
2636        info.protectionLevel = fixedLevel;
2637        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2638        bp.perm.info.packageName = tree.perm.info.packageName;
2639        bp.uid = tree.uid;
2640        if (added) {
2641            mSettings.mPermissions.put(info.name, bp);
2642        }
2643        if (changed) {
2644            if (!async) {
2645                mSettings.writeLPr();
2646            } else {
2647                scheduleWriteSettingsLocked();
2648            }
2649        }
2650        return added;
2651    }
2652
2653    @Override
2654    public boolean addPermission(PermissionInfo info) {
2655        synchronized (mPackages) {
2656            return addPermissionLocked(info, false);
2657        }
2658    }
2659
2660    @Override
2661    public boolean addPermissionAsync(PermissionInfo info) {
2662        synchronized (mPackages) {
2663            return addPermissionLocked(info, true);
2664        }
2665    }
2666
2667    @Override
2668    public void removePermission(String name) {
2669        synchronized (mPackages) {
2670            checkPermissionTreeLP(name);
2671            BasePermission bp = mSettings.mPermissions.get(name);
2672            if (bp != null) {
2673                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2674                    throw new SecurityException(
2675                            "Not allowed to modify non-dynamic permission "
2676                            + name);
2677                }
2678                mSettings.mPermissions.remove(name);
2679                mSettings.writeLPr();
2680            }
2681        }
2682    }
2683
2684    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
2685            BasePermission bp) {
2686        int index = pkg.requestedPermissions.indexOf(bp.name);
2687        if (index == -1) {
2688            throw new SecurityException("Package " + pkg.packageName
2689                    + " has not requested permission " + bp.name);
2690        }
2691        if (!bp.isRuntime()) {
2692            throw new SecurityException("Permission " + bp.name
2693                    + " is not a changeable permission type");
2694        }
2695    }
2696
2697    @Override
2698    public boolean grantPermission(String packageName, String name, int userId) {
2699        if (!sUserManager.exists(userId)) {
2700            return false;
2701        }
2702
2703        mContext.enforceCallingOrSelfPermission(
2704                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
2705                "grantPermission");
2706
2707        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
2708                "grantPermission");
2709
2710        synchronized (mPackages) {
2711            final PackageParser.Package pkg = mPackages.get(packageName);
2712            if (pkg == null) {
2713                throw new IllegalArgumentException("Unknown package: " + packageName);
2714            }
2715
2716            final BasePermission bp = mSettings.mPermissions.get(name);
2717            if (bp == null) {
2718                throw new IllegalArgumentException("Unknown permission: " + name);
2719            }
2720
2721            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
2722
2723            final SettingBase sb = (SettingBase) pkg.mExtras;
2724            if (sb == null) {
2725                throw new IllegalArgumentException("Unknown package: " + packageName);
2726            }
2727
2728            final PermissionsState permissionsState = sb.getPermissionsState();
2729
2730            final int result = permissionsState.grantRuntimePermission(bp, userId);
2731            switch (result) {
2732                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
2733                    return false;
2734                }
2735
2736                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
2737                    killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
2738                } break;
2739            }
2740
2741            // Not critical if that is lost - app has to request again.
2742            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
2743
2744            return true;
2745        }
2746    }
2747
2748    @Override
2749    public boolean revokePermission(String packageName, String name, int userId) {
2750        if (!sUserManager.exists(userId)) {
2751            return false;
2752        }
2753
2754        mContext.enforceCallingOrSelfPermission(
2755                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
2756                "revokePermission");
2757
2758        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
2759                "revokePermission");
2760
2761        synchronized (mPackages) {
2762            final PackageParser.Package pkg = mPackages.get(packageName);
2763            if (pkg == null) {
2764                throw new IllegalArgumentException("Unknown package: " + packageName);
2765            }
2766
2767            final BasePermission bp = mSettings.mPermissions.get(name);
2768            if (bp == null) {
2769                throw new IllegalArgumentException("Unknown permission: " + name);
2770            }
2771
2772            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
2773
2774            final SettingBase sb = (SettingBase) pkg.mExtras;
2775            if (sb == null) {
2776                throw new IllegalArgumentException("Unknown package: " + packageName);
2777            }
2778
2779            final PermissionsState permissionsState = sb.getPermissionsState();
2780
2781            if (permissionsState.revokeRuntimePermission(bp, userId) ==
2782                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
2783                return false;
2784            }
2785
2786            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
2787
2788            // Critical, after this call all should never have the permission.
2789            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
2790
2791            return true;
2792        }
2793    }
2794
2795    @Override
2796    public boolean isProtectedBroadcast(String actionName) {
2797        synchronized (mPackages) {
2798            return mProtectedBroadcasts.contains(actionName);
2799        }
2800    }
2801
2802    @Override
2803    public int checkSignatures(String pkg1, String pkg2) {
2804        synchronized (mPackages) {
2805            final PackageParser.Package p1 = mPackages.get(pkg1);
2806            final PackageParser.Package p2 = mPackages.get(pkg2);
2807            if (p1 == null || p1.mExtras == null
2808                    || p2 == null || p2.mExtras == null) {
2809                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2810            }
2811            return compareSignatures(p1.mSignatures, p2.mSignatures);
2812        }
2813    }
2814
2815    @Override
2816    public int checkUidSignatures(int uid1, int uid2) {
2817        // Map to base uids.
2818        uid1 = UserHandle.getAppId(uid1);
2819        uid2 = UserHandle.getAppId(uid2);
2820        // reader
2821        synchronized (mPackages) {
2822            Signature[] s1;
2823            Signature[] s2;
2824            Object obj = mSettings.getUserIdLPr(uid1);
2825            if (obj != null) {
2826                if (obj instanceof SharedUserSetting) {
2827                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2828                } else if (obj instanceof PackageSetting) {
2829                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2830                } else {
2831                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2832                }
2833            } else {
2834                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2835            }
2836            obj = mSettings.getUserIdLPr(uid2);
2837            if (obj != null) {
2838                if (obj instanceof SharedUserSetting) {
2839                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2840                } else if (obj instanceof PackageSetting) {
2841                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2842                } else {
2843                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2844                }
2845            } else {
2846                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2847            }
2848            return compareSignatures(s1, s2);
2849        }
2850    }
2851
2852    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
2853        final long identity = Binder.clearCallingIdentity();
2854        try {
2855            if (sb instanceof SharedUserSetting) {
2856                SharedUserSetting sus = (SharedUserSetting) sb;
2857                final int packageCount = sus.packages.size();
2858                for (int i = 0; i < packageCount; i++) {
2859                    PackageSetting susPs = sus.packages.valueAt(i);
2860                    if (userId == UserHandle.USER_ALL) {
2861                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
2862                    } else {
2863                        final int uid = UserHandle.getUid(userId, susPs.appId);
2864                        killUid(uid, reason);
2865                    }
2866                }
2867            } else if (sb instanceof PackageSetting) {
2868                PackageSetting ps = (PackageSetting) sb;
2869                if (userId == UserHandle.USER_ALL) {
2870                    killApplication(ps.pkg.packageName, ps.appId, reason);
2871                } else {
2872                    final int uid = UserHandle.getUid(userId, ps.appId);
2873                    killUid(uid, reason);
2874                }
2875            }
2876        } finally {
2877            Binder.restoreCallingIdentity(identity);
2878        }
2879    }
2880
2881    private static void killUid(int uid, String reason) {
2882        IActivityManager am = ActivityManagerNative.getDefault();
2883        if (am != null) {
2884            try {
2885                am.killUid(uid, reason);
2886            } catch (RemoteException e) {
2887                /* ignore - same process */
2888            }
2889        }
2890    }
2891
2892    /**
2893     * Compares two sets of signatures. Returns:
2894     * <br />
2895     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2896     * <br />
2897     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2898     * <br />
2899     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2900     * <br />
2901     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2902     * <br />
2903     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2904     */
2905    static int compareSignatures(Signature[] s1, Signature[] s2) {
2906        if (s1 == null) {
2907            return s2 == null
2908                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2909                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2910        }
2911
2912        if (s2 == null) {
2913            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2914        }
2915
2916        if (s1.length != s2.length) {
2917            return PackageManager.SIGNATURE_NO_MATCH;
2918        }
2919
2920        // Since both signature sets are of size 1, we can compare without HashSets.
2921        if (s1.length == 1) {
2922            return s1[0].equals(s2[0]) ?
2923                    PackageManager.SIGNATURE_MATCH :
2924                    PackageManager.SIGNATURE_NO_MATCH;
2925        }
2926
2927        ArraySet<Signature> set1 = new ArraySet<Signature>();
2928        for (Signature sig : s1) {
2929            set1.add(sig);
2930        }
2931        ArraySet<Signature> set2 = new ArraySet<Signature>();
2932        for (Signature sig : s2) {
2933            set2.add(sig);
2934        }
2935        // Make sure s2 contains all signatures in s1.
2936        if (set1.equals(set2)) {
2937            return PackageManager.SIGNATURE_MATCH;
2938        }
2939        return PackageManager.SIGNATURE_NO_MATCH;
2940    }
2941
2942    /**
2943     * If the database version for this type of package (internal storage or
2944     * external storage) is less than the version where package signatures
2945     * were updated, return true.
2946     */
2947    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2948        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2949                DatabaseVersion.SIGNATURE_END_ENTITY))
2950                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2951                        DatabaseVersion.SIGNATURE_END_ENTITY));
2952    }
2953
2954    /**
2955     * Used for backward compatibility to make sure any packages with
2956     * certificate chains get upgraded to the new style. {@code existingSigs}
2957     * will be in the old format (since they were stored on disk from before the
2958     * system upgrade) and {@code scannedSigs} will be in the newer format.
2959     */
2960    private int compareSignaturesCompat(PackageSignatures existingSigs,
2961            PackageParser.Package scannedPkg) {
2962        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2963            return PackageManager.SIGNATURE_NO_MATCH;
2964        }
2965
2966        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2967        for (Signature sig : existingSigs.mSignatures) {
2968            existingSet.add(sig);
2969        }
2970        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2971        for (Signature sig : scannedPkg.mSignatures) {
2972            try {
2973                Signature[] chainSignatures = sig.getChainSignatures();
2974                for (Signature chainSig : chainSignatures) {
2975                    scannedCompatSet.add(chainSig);
2976                }
2977            } catch (CertificateEncodingException e) {
2978                scannedCompatSet.add(sig);
2979            }
2980        }
2981        /*
2982         * Make sure the expanded scanned set contains all signatures in the
2983         * existing one.
2984         */
2985        if (scannedCompatSet.equals(existingSet)) {
2986            // Migrate the old signatures to the new scheme.
2987            existingSigs.assignSignatures(scannedPkg.mSignatures);
2988            // The new KeySets will be re-added later in the scanning process.
2989            synchronized (mPackages) {
2990                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2991            }
2992            return PackageManager.SIGNATURE_MATCH;
2993        }
2994        return PackageManager.SIGNATURE_NO_MATCH;
2995    }
2996
2997    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2998        if (isExternal(scannedPkg)) {
2999            return mSettings.isExternalDatabaseVersionOlderThan(
3000                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3001        } else {
3002            return mSettings.isInternalDatabaseVersionOlderThan(
3003                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3004        }
3005    }
3006
3007    private int compareSignaturesRecover(PackageSignatures existingSigs,
3008            PackageParser.Package scannedPkg) {
3009        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3010            return PackageManager.SIGNATURE_NO_MATCH;
3011        }
3012
3013        String msg = null;
3014        try {
3015            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3016                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3017                        + scannedPkg.packageName);
3018                return PackageManager.SIGNATURE_MATCH;
3019            }
3020        } catch (CertificateException e) {
3021            msg = e.getMessage();
3022        }
3023
3024        logCriticalInfo(Log.INFO,
3025                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3026        return PackageManager.SIGNATURE_NO_MATCH;
3027    }
3028
3029    @Override
3030    public String[] getPackagesForUid(int uid) {
3031        uid = UserHandle.getAppId(uid);
3032        // reader
3033        synchronized (mPackages) {
3034            Object obj = mSettings.getUserIdLPr(uid);
3035            if (obj instanceof SharedUserSetting) {
3036                final SharedUserSetting sus = (SharedUserSetting) obj;
3037                final int N = sus.packages.size();
3038                final String[] res = new String[N];
3039                final Iterator<PackageSetting> it = sus.packages.iterator();
3040                int i = 0;
3041                while (it.hasNext()) {
3042                    res[i++] = it.next().name;
3043                }
3044                return res;
3045            } else if (obj instanceof PackageSetting) {
3046                final PackageSetting ps = (PackageSetting) obj;
3047                return new String[] { ps.name };
3048            }
3049        }
3050        return null;
3051    }
3052
3053    @Override
3054    public String getNameForUid(int uid) {
3055        // reader
3056        synchronized (mPackages) {
3057            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3058            if (obj instanceof SharedUserSetting) {
3059                final SharedUserSetting sus = (SharedUserSetting) obj;
3060                return sus.name + ":" + sus.userId;
3061            } else if (obj instanceof PackageSetting) {
3062                final PackageSetting ps = (PackageSetting) obj;
3063                return ps.name;
3064            }
3065        }
3066        return null;
3067    }
3068
3069    @Override
3070    public int getUidForSharedUser(String sharedUserName) {
3071        if(sharedUserName == null) {
3072            return -1;
3073        }
3074        // reader
3075        synchronized (mPackages) {
3076            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3077            if (suid == null) {
3078                return -1;
3079            }
3080            return suid.userId;
3081        }
3082    }
3083
3084    @Override
3085    public int getFlagsForUid(int uid) {
3086        synchronized (mPackages) {
3087            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3088            if (obj instanceof SharedUserSetting) {
3089                final SharedUserSetting sus = (SharedUserSetting) obj;
3090                return sus.pkgFlags;
3091            } else if (obj instanceof PackageSetting) {
3092                final PackageSetting ps = (PackageSetting) obj;
3093                return ps.pkgFlags;
3094            }
3095        }
3096        return 0;
3097    }
3098
3099    @Override
3100    public int getPrivateFlagsForUid(int uid) {
3101        synchronized (mPackages) {
3102            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3103            if (obj instanceof SharedUserSetting) {
3104                final SharedUserSetting sus = (SharedUserSetting) obj;
3105                return sus.pkgPrivateFlags;
3106            } else if (obj instanceof PackageSetting) {
3107                final PackageSetting ps = (PackageSetting) obj;
3108                return ps.pkgPrivateFlags;
3109            }
3110        }
3111        return 0;
3112    }
3113
3114    @Override
3115    public boolean isUidPrivileged(int uid) {
3116        uid = UserHandle.getAppId(uid);
3117        // reader
3118        synchronized (mPackages) {
3119            Object obj = mSettings.getUserIdLPr(uid);
3120            if (obj instanceof SharedUserSetting) {
3121                final SharedUserSetting sus = (SharedUserSetting) obj;
3122                final Iterator<PackageSetting> it = sus.packages.iterator();
3123                while (it.hasNext()) {
3124                    if (it.next().isPrivileged()) {
3125                        return true;
3126                    }
3127                }
3128            } else if (obj instanceof PackageSetting) {
3129                final PackageSetting ps = (PackageSetting) obj;
3130                return ps.isPrivileged();
3131            }
3132        }
3133        return false;
3134    }
3135
3136    @Override
3137    public String[] getAppOpPermissionPackages(String permissionName) {
3138        synchronized (mPackages) {
3139            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3140            if (pkgs == null) {
3141                return null;
3142            }
3143            return pkgs.toArray(new String[pkgs.size()]);
3144        }
3145    }
3146
3147    @Override
3148    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3149            int flags, int userId) {
3150        if (!sUserManager.exists(userId)) return null;
3151        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3152        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3153        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3154    }
3155
3156    @Override
3157    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3158            IntentFilter filter, int match, ComponentName activity) {
3159        final int userId = UserHandle.getCallingUserId();
3160        if (DEBUG_PREFERRED) {
3161            Log.v(TAG, "setLastChosenActivity intent=" + intent
3162                + " resolvedType=" + resolvedType
3163                + " flags=" + flags
3164                + " filter=" + filter
3165                + " match=" + match
3166                + " activity=" + activity);
3167            filter.dump(new PrintStreamPrinter(System.out), "    ");
3168        }
3169        intent.setComponent(null);
3170        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3171        // Find any earlier preferred or last chosen entries and nuke them
3172        findPreferredActivity(intent, resolvedType,
3173                flags, query, 0, false, true, false, userId);
3174        // Add the new activity as the last chosen for this filter
3175        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3176                "Setting last chosen");
3177    }
3178
3179    @Override
3180    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3181        final int userId = UserHandle.getCallingUserId();
3182        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3183        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3184        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3185                false, false, false, userId);
3186    }
3187
3188    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3189            int flags, List<ResolveInfo> query, int userId) {
3190        if (query != null) {
3191            final int N = query.size();
3192            if (N == 1) {
3193                return query.get(0);
3194            } else if (N > 1) {
3195                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3196                // If there is more than one activity with the same priority,
3197                // then let the user decide between them.
3198                ResolveInfo r0 = query.get(0);
3199                ResolveInfo r1 = query.get(1);
3200                if (DEBUG_INTENT_MATCHING || debug) {
3201                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3202                            + r1.activityInfo.name + "=" + r1.priority);
3203                }
3204                // If the first activity has a higher priority, or a different
3205                // default, then it is always desireable to pick it.
3206                if (r0.priority != r1.priority
3207                        || r0.preferredOrder != r1.preferredOrder
3208                        || r0.isDefault != r1.isDefault) {
3209                    return query.get(0);
3210                }
3211                // If we have saved a preference for a preferred activity for
3212                // this Intent, use that.
3213                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3214                        flags, query, r0.priority, true, false, debug, userId);
3215                if (ri != null) {
3216                    return ri;
3217                }
3218                if (userId != 0) {
3219                    ri = new ResolveInfo(mResolveInfo);
3220                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3221                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3222                            ri.activityInfo.applicationInfo);
3223                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3224                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3225                    return ri;
3226                }
3227                return mResolveInfo;
3228            }
3229        }
3230        return null;
3231    }
3232
3233    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3234            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3235        final int N = query.size();
3236        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3237                .get(userId);
3238        // Get the list of persistent preferred activities that handle the intent
3239        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3240        List<PersistentPreferredActivity> pprefs = ppir != null
3241                ? ppir.queryIntent(intent, resolvedType,
3242                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3243                : null;
3244        if (pprefs != null && pprefs.size() > 0) {
3245            final int M = pprefs.size();
3246            for (int i=0; i<M; i++) {
3247                final PersistentPreferredActivity ppa = pprefs.get(i);
3248                if (DEBUG_PREFERRED || debug) {
3249                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3250                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3251                            + "\n  component=" + ppa.mComponent);
3252                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3253                }
3254                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3255                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3256                if (DEBUG_PREFERRED || debug) {
3257                    Slog.v(TAG, "Found persistent preferred activity:");
3258                    if (ai != null) {
3259                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3260                    } else {
3261                        Slog.v(TAG, "  null");
3262                    }
3263                }
3264                if (ai == null) {
3265                    // This previously registered persistent preferred activity
3266                    // component is no longer known. Ignore it and do NOT remove it.
3267                    continue;
3268                }
3269                for (int j=0; j<N; j++) {
3270                    final ResolveInfo ri = query.get(j);
3271                    if (!ri.activityInfo.applicationInfo.packageName
3272                            .equals(ai.applicationInfo.packageName)) {
3273                        continue;
3274                    }
3275                    if (!ri.activityInfo.name.equals(ai.name)) {
3276                        continue;
3277                    }
3278                    //  Found a persistent preference that can handle the intent.
3279                    if (DEBUG_PREFERRED || debug) {
3280                        Slog.v(TAG, "Returning persistent preferred activity: " +
3281                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3282                    }
3283                    return ri;
3284                }
3285            }
3286        }
3287        return null;
3288    }
3289
3290    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3291            List<ResolveInfo> query, int priority, boolean always,
3292            boolean removeMatches, boolean debug, int userId) {
3293        if (!sUserManager.exists(userId)) return null;
3294        // writer
3295        synchronized (mPackages) {
3296            if (intent.getSelector() != null) {
3297                intent = intent.getSelector();
3298            }
3299            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3300
3301            // Try to find a matching persistent preferred activity.
3302            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3303                    debug, userId);
3304
3305            // If a persistent preferred activity matched, use it.
3306            if (pri != null) {
3307                return pri;
3308            }
3309
3310            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3311            // Get the list of preferred activities that handle the intent
3312            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3313            List<PreferredActivity> prefs = pir != null
3314                    ? pir.queryIntent(intent, resolvedType,
3315                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3316                    : null;
3317            if (prefs != null && prefs.size() > 0) {
3318                boolean changed = false;
3319                try {
3320                    // First figure out how good the original match set is.
3321                    // We will only allow preferred activities that came
3322                    // from the same match quality.
3323                    int match = 0;
3324
3325                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3326
3327                    final int N = query.size();
3328                    for (int j=0; j<N; j++) {
3329                        final ResolveInfo ri = query.get(j);
3330                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3331                                + ": 0x" + Integer.toHexString(match));
3332                        if (ri.match > match) {
3333                            match = ri.match;
3334                        }
3335                    }
3336
3337                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3338                            + Integer.toHexString(match));
3339
3340                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3341                    final int M = prefs.size();
3342                    for (int i=0; i<M; i++) {
3343                        final PreferredActivity pa = prefs.get(i);
3344                        if (DEBUG_PREFERRED || debug) {
3345                            Slog.v(TAG, "Checking PreferredActivity ds="
3346                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3347                                    + "\n  component=" + pa.mPref.mComponent);
3348                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3349                        }
3350                        if (pa.mPref.mMatch != match) {
3351                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3352                                    + Integer.toHexString(pa.mPref.mMatch));
3353                            continue;
3354                        }
3355                        // If it's not an "always" type preferred activity and that's what we're
3356                        // looking for, skip it.
3357                        if (always && !pa.mPref.mAlways) {
3358                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3359                            continue;
3360                        }
3361                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3362                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3363                        if (DEBUG_PREFERRED || debug) {
3364                            Slog.v(TAG, "Found preferred activity:");
3365                            if (ai != null) {
3366                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3367                            } else {
3368                                Slog.v(TAG, "  null");
3369                            }
3370                        }
3371                        if (ai == null) {
3372                            // This previously registered preferred activity
3373                            // component is no longer known.  Most likely an update
3374                            // to the app was installed and in the new version this
3375                            // component no longer exists.  Clean it up by removing
3376                            // it from the preferred activities list, and skip it.
3377                            Slog.w(TAG, "Removing dangling preferred activity: "
3378                                    + pa.mPref.mComponent);
3379                            pir.removeFilter(pa);
3380                            changed = true;
3381                            continue;
3382                        }
3383                        for (int j=0; j<N; j++) {
3384                            final ResolveInfo ri = query.get(j);
3385                            if (!ri.activityInfo.applicationInfo.packageName
3386                                    .equals(ai.applicationInfo.packageName)) {
3387                                continue;
3388                            }
3389                            if (!ri.activityInfo.name.equals(ai.name)) {
3390                                continue;
3391                            }
3392
3393                            if (removeMatches) {
3394                                pir.removeFilter(pa);
3395                                changed = true;
3396                                if (DEBUG_PREFERRED) {
3397                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3398                                }
3399                                break;
3400                            }
3401
3402                            // Okay we found a previously set preferred or last chosen app.
3403                            // If the result set is different from when this
3404                            // was created, we need to clear it and re-ask the
3405                            // user their preference, if we're looking for an "always" type entry.
3406                            if (always && !pa.mPref.sameSet(query)) {
3407                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3408                                        + intent + " type " + resolvedType);
3409                                if (DEBUG_PREFERRED) {
3410                                    Slog.v(TAG, "Removing preferred activity since set changed "
3411                                            + pa.mPref.mComponent);
3412                                }
3413                                pir.removeFilter(pa);
3414                                // Re-add the filter as a "last chosen" entry (!always)
3415                                PreferredActivity lastChosen = new PreferredActivity(
3416                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3417                                pir.addFilter(lastChosen);
3418                                changed = true;
3419                                return null;
3420                            }
3421
3422                            // Yay! Either the set matched or we're looking for the last chosen
3423                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3424                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3425                            return ri;
3426                        }
3427                    }
3428                } finally {
3429                    if (changed) {
3430                        if (DEBUG_PREFERRED) {
3431                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3432                        }
3433                        scheduleWritePackageRestrictionsLocked(userId);
3434                    }
3435                }
3436            }
3437        }
3438        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3439        return null;
3440    }
3441
3442    /*
3443     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3444     */
3445    @Override
3446    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3447            int targetUserId) {
3448        mContext.enforceCallingOrSelfPermission(
3449                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3450        List<CrossProfileIntentFilter> matches =
3451                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3452        if (matches != null) {
3453            int size = matches.size();
3454            for (int i = 0; i < size; i++) {
3455                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3456            }
3457        }
3458        return false;
3459    }
3460
3461    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3462            String resolvedType, int userId) {
3463        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3464        if (resolver != null) {
3465            return resolver.queryIntent(intent, resolvedType, false, userId);
3466        }
3467        return null;
3468    }
3469
3470    @Override
3471    public List<ResolveInfo> queryIntentActivities(Intent intent,
3472            String resolvedType, int flags, int userId) {
3473        if (!sUserManager.exists(userId)) return Collections.emptyList();
3474        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3475        ComponentName comp = intent.getComponent();
3476        if (comp == null) {
3477            if (intent.getSelector() != null) {
3478                intent = intent.getSelector();
3479                comp = intent.getComponent();
3480            }
3481        }
3482
3483        if (comp != null) {
3484            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3485            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3486            if (ai != null) {
3487                final ResolveInfo ri = new ResolveInfo();
3488                ri.activityInfo = ai;
3489                list.add(ri);
3490            }
3491            return list;
3492        }
3493
3494        // reader
3495        synchronized (mPackages) {
3496            final String pkgName = intent.getPackage();
3497            if (pkgName == null) {
3498                List<CrossProfileIntentFilter> matchingFilters =
3499                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3500                // Check for results that need to skip the current profile.
3501                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3502                        resolvedType, flags, userId);
3503                if (resolveInfo != null) {
3504                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3505                    result.add(resolveInfo);
3506                    return filterIfNotPrimaryUser(result, userId);
3507                }
3508                // Check for cross profile results.
3509                resolveInfo = queryCrossProfileIntents(
3510                        matchingFilters, intent, resolvedType, flags, userId);
3511
3512                // Check for results in the current profile.
3513                List<ResolveInfo> result = mActivities.queryIntent(
3514                        intent, resolvedType, flags, userId);
3515                if (resolveInfo != null) {
3516                    result.add(resolveInfo);
3517                    Collections.sort(result, mResolvePrioritySorter);
3518                }
3519                return filterIfNotPrimaryUser(result, userId);
3520            }
3521            final PackageParser.Package pkg = mPackages.get(pkgName);
3522            if (pkg != null) {
3523                return filterIfNotPrimaryUser(
3524                        mActivities.queryIntentForPackage(
3525                                intent, resolvedType, flags, pkg.activities, userId),
3526                        userId);
3527            }
3528            return new ArrayList<ResolveInfo>();
3529        }
3530    }
3531
3532    /**
3533     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3534     *
3535     * @return filtered list
3536     */
3537    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3538        if (userId == UserHandle.USER_OWNER) {
3539            return resolveInfos;
3540        }
3541        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3542            ResolveInfo info = resolveInfos.get(i);
3543            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3544                resolveInfos.remove(i);
3545            }
3546        }
3547        return resolveInfos;
3548    }
3549
3550
3551    private ResolveInfo querySkipCurrentProfileIntents(
3552            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3553            int flags, int sourceUserId) {
3554        if (matchingFilters != null) {
3555            int size = matchingFilters.size();
3556            for (int i = 0; i < size; i ++) {
3557                CrossProfileIntentFilter filter = matchingFilters.get(i);
3558                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3559                    // Checking if there are activities in the target user that can handle the
3560                    // intent.
3561                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3562                            flags, sourceUserId);
3563                    if (resolveInfo != null) {
3564                        return resolveInfo;
3565                    }
3566                }
3567            }
3568        }
3569        return null;
3570    }
3571
3572    // Return matching ResolveInfo if any for skip current profile intent filters.
3573    private ResolveInfo queryCrossProfileIntents(
3574            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3575            int flags, int sourceUserId) {
3576        if (matchingFilters != null) {
3577            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3578            // match the same intent. For performance reasons, it is better not to
3579            // run queryIntent twice for the same userId
3580            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3581            int size = matchingFilters.size();
3582            for (int i = 0; i < size; i++) {
3583                CrossProfileIntentFilter filter = matchingFilters.get(i);
3584                int targetUserId = filter.getTargetUserId();
3585                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3586                        && !alreadyTriedUserIds.get(targetUserId)) {
3587                    // Checking if there are activities in the target user that can handle the
3588                    // intent.
3589                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3590                            flags, sourceUserId);
3591                    if (resolveInfo != null) return resolveInfo;
3592                    alreadyTriedUserIds.put(targetUserId, true);
3593                }
3594            }
3595        }
3596        return null;
3597    }
3598
3599    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3600            String resolvedType, int flags, int sourceUserId) {
3601        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3602                resolvedType, flags, filter.getTargetUserId());
3603        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3604            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3605        }
3606        return null;
3607    }
3608
3609    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3610            int sourceUserId, int targetUserId) {
3611        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3612        String className;
3613        if (targetUserId == UserHandle.USER_OWNER) {
3614            className = FORWARD_INTENT_TO_USER_OWNER;
3615        } else {
3616            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3617        }
3618        ComponentName forwardingActivityComponentName = new ComponentName(
3619                mAndroidApplication.packageName, className);
3620        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3621                sourceUserId);
3622        if (targetUserId == UserHandle.USER_OWNER) {
3623            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3624            forwardingResolveInfo.noResourceId = true;
3625        }
3626        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3627        forwardingResolveInfo.priority = 0;
3628        forwardingResolveInfo.preferredOrder = 0;
3629        forwardingResolveInfo.match = 0;
3630        forwardingResolveInfo.isDefault = true;
3631        forwardingResolveInfo.filter = filter;
3632        forwardingResolveInfo.targetUserId = targetUserId;
3633        return forwardingResolveInfo;
3634    }
3635
3636    @Override
3637    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3638            Intent[] specifics, String[] specificTypes, Intent intent,
3639            String resolvedType, int flags, int userId) {
3640        if (!sUserManager.exists(userId)) return Collections.emptyList();
3641        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3642                false, "query intent activity options");
3643        final String resultsAction = intent.getAction();
3644
3645        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3646                | PackageManager.GET_RESOLVED_FILTER, userId);
3647
3648        if (DEBUG_INTENT_MATCHING) {
3649            Log.v(TAG, "Query " + intent + ": " + results);
3650        }
3651
3652        int specificsPos = 0;
3653        int N;
3654
3655        // todo: note that the algorithm used here is O(N^2).  This
3656        // isn't a problem in our current environment, but if we start running
3657        // into situations where we have more than 5 or 10 matches then this
3658        // should probably be changed to something smarter...
3659
3660        // First we go through and resolve each of the specific items
3661        // that were supplied, taking care of removing any corresponding
3662        // duplicate items in the generic resolve list.
3663        if (specifics != null) {
3664            for (int i=0; i<specifics.length; i++) {
3665                final Intent sintent = specifics[i];
3666                if (sintent == null) {
3667                    continue;
3668                }
3669
3670                if (DEBUG_INTENT_MATCHING) {
3671                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3672                }
3673
3674                String action = sintent.getAction();
3675                if (resultsAction != null && resultsAction.equals(action)) {
3676                    // If this action was explicitly requested, then don't
3677                    // remove things that have it.
3678                    action = null;
3679                }
3680
3681                ResolveInfo ri = null;
3682                ActivityInfo ai = null;
3683
3684                ComponentName comp = sintent.getComponent();
3685                if (comp == null) {
3686                    ri = resolveIntent(
3687                        sintent,
3688                        specificTypes != null ? specificTypes[i] : null,
3689                            flags, userId);
3690                    if (ri == null) {
3691                        continue;
3692                    }
3693                    if (ri == mResolveInfo) {
3694                        // ACK!  Must do something better with this.
3695                    }
3696                    ai = ri.activityInfo;
3697                    comp = new ComponentName(ai.applicationInfo.packageName,
3698                            ai.name);
3699                } else {
3700                    ai = getActivityInfo(comp, flags, userId);
3701                    if (ai == null) {
3702                        continue;
3703                    }
3704                }
3705
3706                // Look for any generic query activities that are duplicates
3707                // of this specific one, and remove them from the results.
3708                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3709                N = results.size();
3710                int j;
3711                for (j=specificsPos; j<N; j++) {
3712                    ResolveInfo sri = results.get(j);
3713                    if ((sri.activityInfo.name.equals(comp.getClassName())
3714                            && sri.activityInfo.applicationInfo.packageName.equals(
3715                                    comp.getPackageName()))
3716                        || (action != null && sri.filter.matchAction(action))) {
3717                        results.remove(j);
3718                        if (DEBUG_INTENT_MATCHING) Log.v(
3719                            TAG, "Removing duplicate item from " + j
3720                            + " due to specific " + specificsPos);
3721                        if (ri == null) {
3722                            ri = sri;
3723                        }
3724                        j--;
3725                        N--;
3726                    }
3727                }
3728
3729                // Add this specific item to its proper place.
3730                if (ri == null) {
3731                    ri = new ResolveInfo();
3732                    ri.activityInfo = ai;
3733                }
3734                results.add(specificsPos, ri);
3735                ri.specificIndex = i;
3736                specificsPos++;
3737            }
3738        }
3739
3740        // Now we go through the remaining generic results and remove any
3741        // duplicate actions that are found here.
3742        N = results.size();
3743        for (int i=specificsPos; i<N-1; i++) {
3744            final ResolveInfo rii = results.get(i);
3745            if (rii.filter == null) {
3746                continue;
3747            }
3748
3749            // Iterate over all of the actions of this result's intent
3750            // filter...  typically this should be just one.
3751            final Iterator<String> it = rii.filter.actionsIterator();
3752            if (it == null) {
3753                continue;
3754            }
3755            while (it.hasNext()) {
3756                final String action = it.next();
3757                if (resultsAction != null && resultsAction.equals(action)) {
3758                    // If this action was explicitly requested, then don't
3759                    // remove things that have it.
3760                    continue;
3761                }
3762                for (int j=i+1; j<N; j++) {
3763                    final ResolveInfo rij = results.get(j);
3764                    if (rij.filter != null && rij.filter.hasAction(action)) {
3765                        results.remove(j);
3766                        if (DEBUG_INTENT_MATCHING) Log.v(
3767                            TAG, "Removing duplicate item from " + j
3768                            + " due to action " + action + " at " + i);
3769                        j--;
3770                        N--;
3771                    }
3772                }
3773            }
3774
3775            // If the caller didn't request filter information, drop it now
3776            // so we don't have to marshall/unmarshall it.
3777            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3778                rii.filter = null;
3779            }
3780        }
3781
3782        // Filter out the caller activity if so requested.
3783        if (caller != null) {
3784            N = results.size();
3785            for (int i=0; i<N; i++) {
3786                ActivityInfo ainfo = results.get(i).activityInfo;
3787                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3788                        && caller.getClassName().equals(ainfo.name)) {
3789                    results.remove(i);
3790                    break;
3791                }
3792            }
3793        }
3794
3795        // If the caller didn't request filter information,
3796        // drop them now so we don't have to
3797        // marshall/unmarshall it.
3798        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3799            N = results.size();
3800            for (int i=0; i<N; i++) {
3801                results.get(i).filter = null;
3802            }
3803        }
3804
3805        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3806        return results;
3807    }
3808
3809    @Override
3810    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3811            int userId) {
3812        if (!sUserManager.exists(userId)) return Collections.emptyList();
3813        ComponentName comp = intent.getComponent();
3814        if (comp == null) {
3815            if (intent.getSelector() != null) {
3816                intent = intent.getSelector();
3817                comp = intent.getComponent();
3818            }
3819        }
3820        if (comp != null) {
3821            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3822            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3823            if (ai != null) {
3824                ResolveInfo ri = new ResolveInfo();
3825                ri.activityInfo = ai;
3826                list.add(ri);
3827            }
3828            return list;
3829        }
3830
3831        // reader
3832        synchronized (mPackages) {
3833            String pkgName = intent.getPackage();
3834            if (pkgName == null) {
3835                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3836            }
3837            final PackageParser.Package pkg = mPackages.get(pkgName);
3838            if (pkg != null) {
3839                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3840                        userId);
3841            }
3842            return null;
3843        }
3844    }
3845
3846    @Override
3847    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3848        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3849        if (!sUserManager.exists(userId)) return null;
3850        if (query != null) {
3851            if (query.size() >= 1) {
3852                // If there is more than one service with the same priority,
3853                // just arbitrarily pick the first one.
3854                return query.get(0);
3855            }
3856        }
3857        return null;
3858    }
3859
3860    @Override
3861    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3862            int userId) {
3863        if (!sUserManager.exists(userId)) return Collections.emptyList();
3864        ComponentName comp = intent.getComponent();
3865        if (comp == null) {
3866            if (intent.getSelector() != null) {
3867                intent = intent.getSelector();
3868                comp = intent.getComponent();
3869            }
3870        }
3871        if (comp != null) {
3872            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3873            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3874            if (si != null) {
3875                final ResolveInfo ri = new ResolveInfo();
3876                ri.serviceInfo = si;
3877                list.add(ri);
3878            }
3879            return list;
3880        }
3881
3882        // reader
3883        synchronized (mPackages) {
3884            String pkgName = intent.getPackage();
3885            if (pkgName == null) {
3886                return mServices.queryIntent(intent, resolvedType, flags, userId);
3887            }
3888            final PackageParser.Package pkg = mPackages.get(pkgName);
3889            if (pkg != null) {
3890                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3891                        userId);
3892            }
3893            return null;
3894        }
3895    }
3896
3897    @Override
3898    public List<ResolveInfo> queryIntentContentProviders(
3899            Intent intent, String resolvedType, int flags, int userId) {
3900        if (!sUserManager.exists(userId)) return Collections.emptyList();
3901        ComponentName comp = intent.getComponent();
3902        if (comp == null) {
3903            if (intent.getSelector() != null) {
3904                intent = intent.getSelector();
3905                comp = intent.getComponent();
3906            }
3907        }
3908        if (comp != null) {
3909            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3910            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3911            if (pi != null) {
3912                final ResolveInfo ri = new ResolveInfo();
3913                ri.providerInfo = pi;
3914                list.add(ri);
3915            }
3916            return list;
3917        }
3918
3919        // reader
3920        synchronized (mPackages) {
3921            String pkgName = intent.getPackage();
3922            if (pkgName == null) {
3923                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3924            }
3925            final PackageParser.Package pkg = mPackages.get(pkgName);
3926            if (pkg != null) {
3927                return mProviders.queryIntentForPackage(
3928                        intent, resolvedType, flags, pkg.providers, userId);
3929            }
3930            return null;
3931        }
3932    }
3933
3934    @Override
3935    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3936        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3937
3938        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3939
3940        // writer
3941        synchronized (mPackages) {
3942            ArrayList<PackageInfo> list;
3943            if (listUninstalled) {
3944                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3945                for (PackageSetting ps : mSettings.mPackages.values()) {
3946                    PackageInfo pi;
3947                    if (ps.pkg != null) {
3948                        pi = generatePackageInfo(ps.pkg, flags, userId);
3949                    } else {
3950                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3951                    }
3952                    if (pi != null) {
3953                        list.add(pi);
3954                    }
3955                }
3956            } else {
3957                list = new ArrayList<PackageInfo>(mPackages.size());
3958                for (PackageParser.Package p : mPackages.values()) {
3959                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3960                    if (pi != null) {
3961                        list.add(pi);
3962                    }
3963                }
3964            }
3965
3966            return new ParceledListSlice<PackageInfo>(list);
3967        }
3968    }
3969
3970    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3971            String[] permissions, boolean[] tmp, int flags, int userId) {
3972        int numMatch = 0;
3973        final PermissionsState permissionsState = ps.getPermissionsState();
3974        for (int i=0; i<permissions.length; i++) {
3975            final String permission = permissions[i];
3976            if (permissionsState.hasPermission(permission, userId)) {
3977                tmp[i] = true;
3978                numMatch++;
3979            } else {
3980                tmp[i] = false;
3981            }
3982        }
3983        if (numMatch == 0) {
3984            return;
3985        }
3986        PackageInfo pi;
3987        if (ps.pkg != null) {
3988            pi = generatePackageInfo(ps.pkg, flags, userId);
3989        } else {
3990            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3991        }
3992        // The above might return null in cases of uninstalled apps or install-state
3993        // skew across users/profiles.
3994        if (pi != null) {
3995            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3996                if (numMatch == permissions.length) {
3997                    pi.requestedPermissions = permissions;
3998                } else {
3999                    pi.requestedPermissions = new String[numMatch];
4000                    numMatch = 0;
4001                    for (int i=0; i<permissions.length; i++) {
4002                        if (tmp[i]) {
4003                            pi.requestedPermissions[numMatch] = permissions[i];
4004                            numMatch++;
4005                        }
4006                    }
4007                }
4008            }
4009            list.add(pi);
4010        }
4011    }
4012
4013    @Override
4014    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4015            String[] permissions, int flags, int userId) {
4016        if (!sUserManager.exists(userId)) return null;
4017        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4018
4019        // writer
4020        synchronized (mPackages) {
4021            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4022            boolean[] tmpBools = new boolean[permissions.length];
4023            if (listUninstalled) {
4024                for (PackageSetting ps : mSettings.mPackages.values()) {
4025                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4026                }
4027            } else {
4028                for (PackageParser.Package pkg : mPackages.values()) {
4029                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4030                    if (ps != null) {
4031                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4032                                userId);
4033                    }
4034                }
4035            }
4036
4037            return new ParceledListSlice<PackageInfo>(list);
4038        }
4039    }
4040
4041    @Override
4042    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4043        if (!sUserManager.exists(userId)) return null;
4044        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4045
4046        // writer
4047        synchronized (mPackages) {
4048            ArrayList<ApplicationInfo> list;
4049            if (listUninstalled) {
4050                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4051                for (PackageSetting ps : mSettings.mPackages.values()) {
4052                    ApplicationInfo ai;
4053                    if (ps.pkg != null) {
4054                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4055                                ps.readUserState(userId), userId);
4056                    } else {
4057                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4058                    }
4059                    if (ai != null) {
4060                        list.add(ai);
4061                    }
4062                }
4063            } else {
4064                list = new ArrayList<ApplicationInfo>(mPackages.size());
4065                for (PackageParser.Package p : mPackages.values()) {
4066                    if (p.mExtras != null) {
4067                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4068                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4069                        if (ai != null) {
4070                            list.add(ai);
4071                        }
4072                    }
4073                }
4074            }
4075
4076            return new ParceledListSlice<ApplicationInfo>(list);
4077        }
4078    }
4079
4080    public List<ApplicationInfo> getPersistentApplications(int flags) {
4081        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4082
4083        // reader
4084        synchronized (mPackages) {
4085            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4086            final int userId = UserHandle.getCallingUserId();
4087            while (i.hasNext()) {
4088                final PackageParser.Package p = i.next();
4089                if (p.applicationInfo != null
4090                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4091                        && (!mSafeMode || isSystemApp(p))) {
4092                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4093                    if (ps != null) {
4094                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4095                                ps.readUserState(userId), userId);
4096                        if (ai != null) {
4097                            finalList.add(ai);
4098                        }
4099                    }
4100                }
4101            }
4102        }
4103
4104        return finalList;
4105    }
4106
4107    @Override
4108    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4109        if (!sUserManager.exists(userId)) return null;
4110        // reader
4111        synchronized (mPackages) {
4112            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4113            PackageSetting ps = provider != null
4114                    ? mSettings.mPackages.get(provider.owner.packageName)
4115                    : null;
4116            return ps != null
4117                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4118                    && (!mSafeMode || (provider.info.applicationInfo.flags
4119                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4120                    ? PackageParser.generateProviderInfo(provider, flags,
4121                            ps.readUserState(userId), userId)
4122                    : null;
4123        }
4124    }
4125
4126    /**
4127     * @deprecated
4128     */
4129    @Deprecated
4130    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4131        // reader
4132        synchronized (mPackages) {
4133            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4134                    .entrySet().iterator();
4135            final int userId = UserHandle.getCallingUserId();
4136            while (i.hasNext()) {
4137                Map.Entry<String, PackageParser.Provider> entry = i.next();
4138                PackageParser.Provider p = entry.getValue();
4139                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4140
4141                if (ps != null && p.syncable
4142                        && (!mSafeMode || (p.info.applicationInfo.flags
4143                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4144                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4145                            ps.readUserState(userId), userId);
4146                    if (info != null) {
4147                        outNames.add(entry.getKey());
4148                        outInfo.add(info);
4149                    }
4150                }
4151            }
4152        }
4153    }
4154
4155    @Override
4156    public List<ProviderInfo> queryContentProviders(String processName,
4157            int uid, int flags) {
4158        ArrayList<ProviderInfo> finalList = null;
4159        // reader
4160        synchronized (mPackages) {
4161            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4162            final int userId = processName != null ?
4163                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4164            while (i.hasNext()) {
4165                final PackageParser.Provider p = i.next();
4166                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4167                if (ps != null && p.info.authority != null
4168                        && (processName == null
4169                                || (p.info.processName.equals(processName)
4170                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4171                        && mSettings.isEnabledLPr(p.info, flags, userId)
4172                        && (!mSafeMode
4173                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4174                    if (finalList == null) {
4175                        finalList = new ArrayList<ProviderInfo>(3);
4176                    }
4177                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4178                            ps.readUserState(userId), userId);
4179                    if (info != null) {
4180                        finalList.add(info);
4181                    }
4182                }
4183            }
4184        }
4185
4186        if (finalList != null) {
4187            Collections.sort(finalList, mProviderInitOrderSorter);
4188        }
4189
4190        return finalList;
4191    }
4192
4193    @Override
4194    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4195            int flags) {
4196        // reader
4197        synchronized (mPackages) {
4198            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4199            return PackageParser.generateInstrumentationInfo(i, flags);
4200        }
4201    }
4202
4203    @Override
4204    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4205            int flags) {
4206        ArrayList<InstrumentationInfo> finalList =
4207            new ArrayList<InstrumentationInfo>();
4208
4209        // reader
4210        synchronized (mPackages) {
4211            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4212            while (i.hasNext()) {
4213                final PackageParser.Instrumentation p = i.next();
4214                if (targetPackage == null
4215                        || targetPackage.equals(p.info.targetPackage)) {
4216                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4217                            flags);
4218                    if (ii != null) {
4219                        finalList.add(ii);
4220                    }
4221                }
4222            }
4223        }
4224
4225        return finalList;
4226    }
4227
4228    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4229        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4230        if (overlays == null) {
4231            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4232            return;
4233        }
4234        for (PackageParser.Package opkg : overlays.values()) {
4235            // Not much to do if idmap fails: we already logged the error
4236            // and we certainly don't want to abort installation of pkg simply
4237            // because an overlay didn't fit properly. For these reasons,
4238            // ignore the return value of createIdmapForPackagePairLI.
4239            createIdmapForPackagePairLI(pkg, opkg);
4240        }
4241    }
4242
4243    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4244            PackageParser.Package opkg) {
4245        if (!opkg.mTrustedOverlay) {
4246            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4247                    opkg.baseCodePath + ": overlay not trusted");
4248            return false;
4249        }
4250        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4251        if (overlaySet == null) {
4252            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4253                    opkg.baseCodePath + " but target package has no known overlays");
4254            return false;
4255        }
4256        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4257        // TODO: generate idmap for split APKs
4258        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4259            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4260                    + opkg.baseCodePath);
4261            return false;
4262        }
4263        PackageParser.Package[] overlayArray =
4264            overlaySet.values().toArray(new PackageParser.Package[0]);
4265        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4266            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4267                return p1.mOverlayPriority - p2.mOverlayPriority;
4268            }
4269        };
4270        Arrays.sort(overlayArray, cmp);
4271
4272        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4273        int i = 0;
4274        for (PackageParser.Package p : overlayArray) {
4275            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4276        }
4277        return true;
4278    }
4279
4280    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4281        final File[] files = dir.listFiles();
4282        if (ArrayUtils.isEmpty(files)) {
4283            Log.d(TAG, "No files in app dir " + dir);
4284            return;
4285        }
4286
4287        if (DEBUG_PACKAGE_SCANNING) {
4288            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4289                    + " flags=0x" + Integer.toHexString(parseFlags));
4290        }
4291
4292        for (File file : files) {
4293            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4294                    && !PackageInstallerService.isStageName(file.getName());
4295            if (!isPackage) {
4296                // Ignore entries which are not packages
4297                continue;
4298            }
4299            try {
4300                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4301                        scanFlags, currentTime, null);
4302            } catch (PackageManagerException e) {
4303                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4304
4305                // Delete invalid userdata apps
4306                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4307                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4308                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4309                    if (file.isDirectory()) {
4310                        FileUtils.deleteContents(file);
4311                    }
4312                    file.delete();
4313                }
4314            }
4315        }
4316    }
4317
4318    private static File getSettingsProblemFile() {
4319        File dataDir = Environment.getDataDirectory();
4320        File systemDir = new File(dataDir, "system");
4321        File fname = new File(systemDir, "uiderrors.txt");
4322        return fname;
4323    }
4324
4325    static void reportSettingsProblem(int priority, String msg) {
4326        logCriticalInfo(priority, msg);
4327    }
4328
4329    static void logCriticalInfo(int priority, String msg) {
4330        Slog.println(priority, TAG, msg);
4331        EventLogTags.writePmCriticalInfo(msg);
4332        try {
4333            File fname = getSettingsProblemFile();
4334            FileOutputStream out = new FileOutputStream(fname, true);
4335            PrintWriter pw = new FastPrintWriter(out);
4336            SimpleDateFormat formatter = new SimpleDateFormat();
4337            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4338            pw.println(dateString + ": " + msg);
4339            pw.close();
4340            FileUtils.setPermissions(
4341                    fname.toString(),
4342                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4343                    -1, -1);
4344        } catch (java.io.IOException e) {
4345        }
4346    }
4347
4348    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4349            PackageParser.Package pkg, File srcFile, int parseFlags)
4350            throws PackageManagerException {
4351        if (ps != null
4352                && ps.codePath.equals(srcFile)
4353                && ps.timeStamp == srcFile.lastModified()
4354                && !isCompatSignatureUpdateNeeded(pkg)
4355                && !isRecoverSignatureUpdateNeeded(pkg)) {
4356            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4357            if (ps.signatures.mSignatures != null
4358                    && ps.signatures.mSignatures.length != 0
4359                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4360                // Optimization: reuse the existing cached certificates
4361                // if the package appears to be unchanged.
4362                pkg.mSignatures = ps.signatures.mSignatures;
4363                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4364                synchronized (mPackages) {
4365                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4366                }
4367                return;
4368            }
4369
4370            Slog.w(TAG, "PackageSetting for " + ps.name
4371                    + " is missing signatures.  Collecting certs again to recover them.");
4372        } else {
4373            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4374        }
4375
4376        try {
4377            pp.collectCertificates(pkg, parseFlags);
4378            pp.collectManifestDigest(pkg);
4379        } catch (PackageParserException e) {
4380            throw PackageManagerException.from(e);
4381        }
4382    }
4383
4384    /*
4385     *  Scan a package and return the newly parsed package.
4386     *  Returns null in case of errors and the error code is stored in mLastScanError
4387     */
4388    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4389            long currentTime, UserHandle user) throws PackageManagerException {
4390        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4391        parseFlags |= mDefParseFlags;
4392        PackageParser pp = new PackageParser();
4393        pp.setSeparateProcesses(mSeparateProcesses);
4394        pp.setOnlyCoreApps(mOnlyCore);
4395        pp.setDisplayMetrics(mMetrics);
4396
4397        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4398            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4399        }
4400
4401        final PackageParser.Package pkg;
4402        try {
4403            pkg = pp.parsePackage(scanFile, parseFlags);
4404        } catch (PackageParserException e) {
4405            throw PackageManagerException.from(e);
4406        }
4407
4408        PackageSetting ps = null;
4409        PackageSetting updatedPkg;
4410        // reader
4411        synchronized (mPackages) {
4412            // Look to see if we already know about this package.
4413            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4414            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4415                // This package has been renamed to its original name.  Let's
4416                // use that.
4417                ps = mSettings.peekPackageLPr(oldName);
4418            }
4419            // If there was no original package, see one for the real package name.
4420            if (ps == null) {
4421                ps = mSettings.peekPackageLPr(pkg.packageName);
4422            }
4423            // Check to see if this package could be hiding/updating a system
4424            // package.  Must look for it either under the original or real
4425            // package name depending on our state.
4426            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4427            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4428        }
4429        boolean updatedPkgBetter = false;
4430        // First check if this is a system package that may involve an update
4431        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4432            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4433            // it needs to drop FLAG_PRIVILEGED.
4434            if (locationIsPrivileged(scanFile)) {
4435                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4436            } else {
4437                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4438            }
4439
4440            if (ps != null && !ps.codePath.equals(scanFile)) {
4441                // The path has changed from what was last scanned...  check the
4442                // version of the new path against what we have stored to determine
4443                // what to do.
4444                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4445                if (pkg.mVersionCode <= ps.versionCode) {
4446                    // The system package has been updated and the code path does not match
4447                    // Ignore entry. Skip it.
4448                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4449                            + " ignored: updated version " + ps.versionCode
4450                            + " better than this " + pkg.mVersionCode);
4451                    if (!updatedPkg.codePath.equals(scanFile)) {
4452                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4453                                + ps.name + " changing from " + updatedPkg.codePathString
4454                                + " to " + scanFile);
4455                        updatedPkg.codePath = scanFile;
4456                        updatedPkg.codePathString = scanFile.toString();
4457                        updatedPkg.resourcePath = scanFile;
4458                        updatedPkg.resourcePathString = scanFile.toString();
4459                    }
4460                    updatedPkg.pkg = pkg;
4461                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4462                } else {
4463                    // The current app on the system partition is better than
4464                    // what we have updated to on the data partition; switch
4465                    // back to the system partition version.
4466                    // At this point, its safely assumed that package installation for
4467                    // apps in system partition will go through. If not there won't be a working
4468                    // version of the app
4469                    // writer
4470                    synchronized (mPackages) {
4471                        // Just remove the loaded entries from package lists.
4472                        mPackages.remove(ps.name);
4473                    }
4474
4475                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4476                            + " reverting from " + ps.codePathString
4477                            + ": new version " + pkg.mVersionCode
4478                            + " better than installed " + ps.versionCode);
4479
4480                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4481                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4482                            getAppDexInstructionSets(ps));
4483                    synchronized (mInstallLock) {
4484                        args.cleanUpResourcesLI();
4485                    }
4486                    synchronized (mPackages) {
4487                        mSettings.enableSystemPackageLPw(ps.name);
4488                    }
4489                    updatedPkgBetter = true;
4490                }
4491            }
4492        }
4493
4494        if (updatedPkg != null) {
4495            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4496            // initially
4497            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4498
4499            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4500            // flag set initially
4501            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4502                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4503            }
4504        }
4505
4506        // Verify certificates against what was last scanned
4507        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4508
4509        /*
4510         * A new system app appeared, but we already had a non-system one of the
4511         * same name installed earlier.
4512         */
4513        boolean shouldHideSystemApp = false;
4514        if (updatedPkg == null && ps != null
4515                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4516            /*
4517             * Check to make sure the signatures match first. If they don't,
4518             * wipe the installed application and its data.
4519             */
4520            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4521                    != PackageManager.SIGNATURE_MATCH) {
4522                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4523                        + " signatures don't match existing userdata copy; removing");
4524                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4525                ps = null;
4526            } else {
4527                /*
4528                 * If the newly-added system app is an older version than the
4529                 * already installed version, hide it. It will be scanned later
4530                 * and re-added like an update.
4531                 */
4532                if (pkg.mVersionCode <= ps.versionCode) {
4533                    shouldHideSystemApp = true;
4534                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4535                            + " but new version " + pkg.mVersionCode + " better than installed "
4536                            + ps.versionCode + "; hiding system");
4537                } else {
4538                    /*
4539                     * The newly found system app is a newer version that the
4540                     * one previously installed. Simply remove the
4541                     * already-installed application and replace it with our own
4542                     * while keeping the application data.
4543                     */
4544                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4545                            + " reverting from " + ps.codePathString + ": new version "
4546                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4547                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4548                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4549                            getAppDexInstructionSets(ps));
4550                    synchronized (mInstallLock) {
4551                        args.cleanUpResourcesLI();
4552                    }
4553                }
4554            }
4555        }
4556
4557        // The apk is forward locked (not public) if its code and resources
4558        // are kept in different files. (except for app in either system or
4559        // vendor path).
4560        // TODO grab this value from PackageSettings
4561        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4562            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4563                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4564            }
4565        }
4566
4567        // TODO: extend to support forward-locked splits
4568        String resourcePath = null;
4569        String baseResourcePath = null;
4570        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4571            if (ps != null && ps.resourcePathString != null) {
4572                resourcePath = ps.resourcePathString;
4573                baseResourcePath = ps.resourcePathString;
4574            } else {
4575                // Should not happen at all. Just log an error.
4576                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4577            }
4578        } else {
4579            resourcePath = pkg.codePath;
4580            baseResourcePath = pkg.baseCodePath;
4581        }
4582
4583        // Set application objects path explicitly.
4584        pkg.applicationInfo.setCodePath(pkg.codePath);
4585        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4586        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4587        pkg.applicationInfo.setResourcePath(resourcePath);
4588        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4589        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4590
4591        // Note that we invoke the following method only if we are about to unpack an application
4592        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4593                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4594
4595        /*
4596         * If the system app should be overridden by a previously installed
4597         * data, hide the system app now and let the /data/app scan pick it up
4598         * again.
4599         */
4600        if (shouldHideSystemApp) {
4601            synchronized (mPackages) {
4602                /*
4603                 * We have to grant systems permissions before we hide, because
4604                 * grantPermissions will assume the package update is trying to
4605                 * expand its permissions.
4606                 */
4607                grantPermissionsLPw(pkg, true, pkg.packageName);
4608                mSettings.disableSystemPackageLPw(pkg.packageName);
4609            }
4610        }
4611
4612        return scannedPkg;
4613    }
4614
4615    private static String fixProcessName(String defProcessName,
4616            String processName, int uid) {
4617        if (processName == null) {
4618            return defProcessName;
4619        }
4620        return processName;
4621    }
4622
4623    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4624            throws PackageManagerException {
4625        if (pkgSetting.signatures.mSignatures != null) {
4626            // Already existing package. Make sure signatures match
4627            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4628                    == PackageManager.SIGNATURE_MATCH;
4629            if (!match) {
4630                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4631                        == PackageManager.SIGNATURE_MATCH;
4632            }
4633            if (!match) {
4634                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4635                        == PackageManager.SIGNATURE_MATCH;
4636            }
4637            if (!match) {
4638                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4639                        + pkg.packageName + " signatures do not match the "
4640                        + "previously installed version; ignoring!");
4641            }
4642        }
4643
4644        // Check for shared user signatures
4645        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4646            // Already existing package. Make sure signatures match
4647            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4648                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4649            if (!match) {
4650                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4651                        == PackageManager.SIGNATURE_MATCH;
4652            }
4653            if (!match) {
4654                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4655                        == PackageManager.SIGNATURE_MATCH;
4656            }
4657            if (!match) {
4658                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4659                        "Package " + pkg.packageName
4660                        + " has no signatures that match those in shared user "
4661                        + pkgSetting.sharedUser.name + "; ignoring!");
4662            }
4663        }
4664    }
4665
4666    /**
4667     * Enforces that only the system UID or root's UID can call a method exposed
4668     * via Binder.
4669     *
4670     * @param message used as message if SecurityException is thrown
4671     * @throws SecurityException if the caller is not system or root
4672     */
4673    private static final void enforceSystemOrRoot(String message) {
4674        final int uid = Binder.getCallingUid();
4675        if (uid != Process.SYSTEM_UID && uid != 0) {
4676            throw new SecurityException(message);
4677        }
4678    }
4679
4680    @Override
4681    public void performBootDexOpt() {
4682        enforceSystemOrRoot("Only the system can request dexopt be performed");
4683
4684        // Before everything else, see whether we need to fstrim.
4685        try {
4686            IMountService ms = PackageHelper.getMountService();
4687            if (ms != null) {
4688                final boolean isUpgrade = isUpgrade();
4689                boolean doTrim = isUpgrade;
4690                if (doTrim) {
4691                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
4692                } else {
4693                    final long interval = android.provider.Settings.Global.getLong(
4694                            mContext.getContentResolver(),
4695                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
4696                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
4697                    if (interval > 0) {
4698                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
4699                        if (timeSinceLast > interval) {
4700                            doTrim = true;
4701                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
4702                                    + "; running immediately");
4703                        }
4704                    }
4705                }
4706                if (doTrim) {
4707                    if (!isFirstBoot()) {
4708                        try {
4709                            ActivityManagerNative.getDefault().showBootMessage(
4710                                    mContext.getResources().getString(
4711                                            R.string.android_upgrading_fstrim), true);
4712                        } catch (RemoteException e) {
4713                        }
4714                    }
4715                    ms.runMaintenance();
4716                }
4717            } else {
4718                Slog.e(TAG, "Mount service unavailable!");
4719            }
4720        } catch (RemoteException e) {
4721            // Can't happen; MountService is local
4722        }
4723
4724        final ArraySet<PackageParser.Package> pkgs;
4725        synchronized (mPackages) {
4726            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
4727        }
4728
4729        if (pkgs != null) {
4730            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4731            // in case the device runs out of space.
4732            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4733            // Give priority to core apps.
4734            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4735                PackageParser.Package pkg = it.next();
4736                if (pkg.coreApp) {
4737                    if (DEBUG_DEXOPT) {
4738                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4739                    }
4740                    sortedPkgs.add(pkg);
4741                    it.remove();
4742                }
4743            }
4744            // Give priority to system apps that listen for pre boot complete.
4745            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4746            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4747            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4748                PackageParser.Package pkg = it.next();
4749                if (pkgNames.contains(pkg.packageName)) {
4750                    if (DEBUG_DEXOPT) {
4751                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4752                    }
4753                    sortedPkgs.add(pkg);
4754                    it.remove();
4755                }
4756            }
4757            // Give priority to system apps.
4758            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4759                PackageParser.Package pkg = it.next();
4760                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4761                    if (DEBUG_DEXOPT) {
4762                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4763                    }
4764                    sortedPkgs.add(pkg);
4765                    it.remove();
4766                }
4767            }
4768            // Give priority to updated system apps.
4769            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4770                PackageParser.Package pkg = it.next();
4771                if (isUpdatedSystemApp(pkg)) {
4772                    if (DEBUG_DEXOPT) {
4773                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4774                    }
4775                    sortedPkgs.add(pkg);
4776                    it.remove();
4777                }
4778            }
4779            // Give priority to apps that listen for boot complete.
4780            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4781            pkgNames = getPackageNamesForIntent(intent);
4782            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4783                PackageParser.Package pkg = it.next();
4784                if (pkgNames.contains(pkg.packageName)) {
4785                    if (DEBUG_DEXOPT) {
4786                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4787                    }
4788                    sortedPkgs.add(pkg);
4789                    it.remove();
4790                }
4791            }
4792            // Filter out packages that aren't recently used.
4793            filterRecentlyUsedApps(pkgs);
4794            // Add all remaining apps.
4795            for (PackageParser.Package pkg : pkgs) {
4796                if (DEBUG_DEXOPT) {
4797                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4798                }
4799                sortedPkgs.add(pkg);
4800            }
4801
4802            // If we want to be lazy, filter everything that wasn't recently used.
4803            if (mLazyDexOpt) {
4804                filterRecentlyUsedApps(sortedPkgs);
4805            }
4806
4807            int i = 0;
4808            int total = sortedPkgs.size();
4809            File dataDir = Environment.getDataDirectory();
4810            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4811            if (lowThreshold == 0) {
4812                throw new IllegalStateException("Invalid low memory threshold");
4813            }
4814            for (PackageParser.Package pkg : sortedPkgs) {
4815                long usableSpace = dataDir.getUsableSpace();
4816                if (usableSpace < lowThreshold) {
4817                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4818                    break;
4819                }
4820                performBootDexOpt(pkg, ++i, total);
4821            }
4822        }
4823    }
4824
4825    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4826        // Filter out packages that aren't recently used.
4827        //
4828        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4829        // should do a full dexopt.
4830        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4831            int total = pkgs.size();
4832            int skipped = 0;
4833            long now = System.currentTimeMillis();
4834            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4835                PackageParser.Package pkg = i.next();
4836                long then = pkg.mLastPackageUsageTimeInMills;
4837                if (then + mDexOptLRUThresholdInMills < now) {
4838                    if (DEBUG_DEXOPT) {
4839                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4840                              ((then == 0) ? "never" : new Date(then)));
4841                    }
4842                    i.remove();
4843                    skipped++;
4844                }
4845            }
4846            if (DEBUG_DEXOPT) {
4847                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4848            }
4849        }
4850    }
4851
4852    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4853        List<ResolveInfo> ris = null;
4854        try {
4855            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4856                    intent, null, 0, UserHandle.USER_OWNER);
4857        } catch (RemoteException e) {
4858        }
4859        ArraySet<String> pkgNames = new ArraySet<String>();
4860        if (ris != null) {
4861            for (ResolveInfo ri : ris) {
4862                pkgNames.add(ri.activityInfo.packageName);
4863            }
4864        }
4865        return pkgNames;
4866    }
4867
4868    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4869        if (DEBUG_DEXOPT) {
4870            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4871        }
4872        if (!isFirstBoot()) {
4873            try {
4874                ActivityManagerNative.getDefault().showBootMessage(
4875                        mContext.getResources().getString(R.string.android_upgrading_apk,
4876                                curr, total), true);
4877            } catch (RemoteException e) {
4878            }
4879        }
4880        PackageParser.Package p = pkg;
4881        synchronized (mInstallLock) {
4882            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
4883                    false /* force dex */, false /* defer */, true /* include dependencies */);
4884        }
4885    }
4886
4887    @Override
4888    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4889        return performDexOpt(packageName, instructionSet, false);
4890    }
4891
4892    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4893        if (info.primaryCpuAbi == null) {
4894            return getPreferredInstructionSet();
4895        }
4896
4897        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4898    }
4899
4900    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4901        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4902        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4903        if (!dexopt && !updateUsage) {
4904            // We aren't going to dexopt or update usage, so bail early.
4905            return false;
4906        }
4907        PackageParser.Package p;
4908        final String targetInstructionSet;
4909        synchronized (mPackages) {
4910            p = mPackages.get(packageName);
4911            if (p == null) {
4912                return false;
4913            }
4914            if (updateUsage) {
4915                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4916            }
4917            mPackageUsage.write(false);
4918            if (!dexopt) {
4919                // We aren't going to dexopt, so bail early.
4920                return false;
4921            }
4922
4923            targetInstructionSet = instructionSet != null ? instructionSet :
4924                    getPrimaryInstructionSet(p.applicationInfo);
4925            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4926                return false;
4927            }
4928        }
4929
4930        synchronized (mInstallLock) {
4931            final String[] instructionSets = new String[] { targetInstructionSet };
4932            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
4933                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
4934            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
4935        }
4936    }
4937
4938    public ArraySet<String> getPackagesThatNeedDexOpt() {
4939        ArraySet<String> pkgs = null;
4940        synchronized (mPackages) {
4941            for (PackageParser.Package p : mPackages.values()) {
4942                if (DEBUG_DEXOPT) {
4943                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4944                }
4945                if (!p.mDexOptPerformed.isEmpty()) {
4946                    continue;
4947                }
4948                if (pkgs == null) {
4949                    pkgs = new ArraySet<String>();
4950                }
4951                pkgs.add(p.packageName);
4952            }
4953        }
4954        return pkgs;
4955    }
4956
4957    public void shutdown() {
4958        mPackageUsage.write(true);
4959    }
4960
4961    @Override
4962    public void forceDexOpt(String packageName) {
4963        enforceSystemOrRoot("forceDexOpt");
4964
4965        PackageParser.Package pkg;
4966        synchronized (mPackages) {
4967            pkg = mPackages.get(packageName);
4968            if (pkg == null) {
4969                throw new IllegalArgumentException("Missing package: " + packageName);
4970            }
4971        }
4972
4973        synchronized (mInstallLock) {
4974            final String[] instructionSets = new String[] {
4975                    getPrimaryInstructionSet(pkg.applicationInfo) };
4976            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
4977                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
4978            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
4979                throw new IllegalStateException("Failed to dexopt: " + res);
4980            }
4981        }
4982    }
4983
4984    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4985        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4986            Slog.w(TAG, "Unable to update from " + oldPkg.name
4987                    + " to " + newPkg.packageName
4988                    + ": old package not in system partition");
4989            return false;
4990        } else if (mPackages.get(oldPkg.name) != null) {
4991            Slog.w(TAG, "Unable to update from " + oldPkg.name
4992                    + " to " + newPkg.packageName
4993                    + ": old package still exists");
4994            return false;
4995        }
4996        return true;
4997    }
4998
4999    private File getDataPathForPackage(String packageName, int userId) {
5000        /*
5001         * Until we fully support multiple users, return the directory we
5002         * previously would have. The PackageManagerTests will need to be
5003         * revised when this is changed back..
5004         */
5005        if (userId == 0) {
5006            return new File(mAppDataDir, packageName);
5007        } else {
5008            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5009                + File.separator + packageName);
5010        }
5011    }
5012
5013    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5014        int[] users = sUserManager.getUserIds();
5015        int res = mInstaller.install(packageName, uid, uid, seinfo);
5016        if (res < 0) {
5017            return res;
5018        }
5019        for (int user : users) {
5020            if (user != 0) {
5021                res = mInstaller.createUserData(packageName,
5022                        UserHandle.getUid(user, uid), user, seinfo);
5023                if (res < 0) {
5024                    return res;
5025                }
5026            }
5027        }
5028        return res;
5029    }
5030
5031    private int removeDataDirsLI(String packageName) {
5032        int[] users = sUserManager.getUserIds();
5033        int res = 0;
5034        for (int user : users) {
5035            int resInner = mInstaller.remove(packageName, user);
5036            if (resInner < 0) {
5037                res = resInner;
5038            }
5039        }
5040
5041        return res;
5042    }
5043
5044    private int deleteCodeCacheDirsLI(String packageName) {
5045        int[] users = sUserManager.getUserIds();
5046        int res = 0;
5047        for (int user : users) {
5048            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5049            if (resInner < 0) {
5050                res = resInner;
5051            }
5052        }
5053        return res;
5054    }
5055
5056    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5057            PackageParser.Package changingLib) {
5058        if (file.path != null) {
5059            usesLibraryFiles.add(file.path);
5060            return;
5061        }
5062        PackageParser.Package p = mPackages.get(file.apk);
5063        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5064            // If we are doing this while in the middle of updating a library apk,
5065            // then we need to make sure to use that new apk for determining the
5066            // dependencies here.  (We haven't yet finished committing the new apk
5067            // to the package manager state.)
5068            if (p == null || p.packageName.equals(changingLib.packageName)) {
5069                p = changingLib;
5070            }
5071        }
5072        if (p != null) {
5073            usesLibraryFiles.addAll(p.getAllCodePaths());
5074        }
5075    }
5076
5077    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5078            PackageParser.Package changingLib) throws PackageManagerException {
5079        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5080            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5081            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5082            for (int i=0; i<N; i++) {
5083                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5084                if (file == null) {
5085                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5086                            "Package " + pkg.packageName + " requires unavailable shared library "
5087                            + pkg.usesLibraries.get(i) + "; failing!");
5088                }
5089                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5090            }
5091            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5092            for (int i=0; i<N; i++) {
5093                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5094                if (file == null) {
5095                    Slog.w(TAG, "Package " + pkg.packageName
5096                            + " desires unavailable shared library "
5097                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5098                } else {
5099                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5100                }
5101            }
5102            N = usesLibraryFiles.size();
5103            if (N > 0) {
5104                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5105            } else {
5106                pkg.usesLibraryFiles = null;
5107            }
5108        }
5109    }
5110
5111    private static boolean hasString(List<String> list, List<String> which) {
5112        if (list == null) {
5113            return false;
5114        }
5115        for (int i=list.size()-1; i>=0; i--) {
5116            for (int j=which.size()-1; j>=0; j--) {
5117                if (which.get(j).equals(list.get(i))) {
5118                    return true;
5119                }
5120            }
5121        }
5122        return false;
5123    }
5124
5125    private void updateAllSharedLibrariesLPw() {
5126        for (PackageParser.Package pkg : mPackages.values()) {
5127            try {
5128                updateSharedLibrariesLPw(pkg, null);
5129            } catch (PackageManagerException e) {
5130                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5131            }
5132        }
5133    }
5134
5135    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5136            PackageParser.Package changingPkg) {
5137        ArrayList<PackageParser.Package> res = null;
5138        for (PackageParser.Package pkg : mPackages.values()) {
5139            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5140                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5141                if (res == null) {
5142                    res = new ArrayList<PackageParser.Package>();
5143                }
5144                res.add(pkg);
5145                try {
5146                    updateSharedLibrariesLPw(pkg, changingPkg);
5147                } catch (PackageManagerException e) {
5148                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5149                }
5150            }
5151        }
5152        return res;
5153    }
5154
5155    /**
5156     * Derive the value of the {@code cpuAbiOverride} based on the provided
5157     * value and an optional stored value from the package settings.
5158     */
5159    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5160        String cpuAbiOverride = null;
5161
5162        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5163            cpuAbiOverride = null;
5164        } else if (abiOverride != null) {
5165            cpuAbiOverride = abiOverride;
5166        } else if (settings != null) {
5167            cpuAbiOverride = settings.cpuAbiOverrideString;
5168        }
5169
5170        return cpuAbiOverride;
5171    }
5172
5173    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5174            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5175        boolean success = false;
5176        try {
5177            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5178                    currentTime, user);
5179            success = true;
5180            return res;
5181        } finally {
5182            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5183                removeDataDirsLI(pkg.packageName);
5184            }
5185        }
5186    }
5187
5188    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5189            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5190        final File scanFile = new File(pkg.codePath);
5191        if (pkg.applicationInfo.getCodePath() == null ||
5192                pkg.applicationInfo.getResourcePath() == null) {
5193            // Bail out. The resource and code paths haven't been set.
5194            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5195                    "Code and resource paths haven't been set correctly");
5196        }
5197
5198        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5199            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5200        } else {
5201            // Only allow system apps to be flagged as core apps.
5202            pkg.coreApp = false;
5203        }
5204
5205        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5206            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5207        }
5208
5209        if (mCustomResolverComponentName != null &&
5210                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5211            setUpCustomResolverActivity(pkg);
5212        }
5213
5214        if (pkg.packageName.equals("android")) {
5215            synchronized (mPackages) {
5216                if (mAndroidApplication != null) {
5217                    Slog.w(TAG, "*************************************************");
5218                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5219                    Slog.w(TAG, " file=" + scanFile);
5220                    Slog.w(TAG, "*************************************************");
5221                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5222                            "Core android package being redefined.  Skipping.");
5223                }
5224
5225                // Set up information for our fall-back user intent resolution activity.
5226                mPlatformPackage = pkg;
5227                pkg.mVersionCode = mSdkVersion;
5228                mAndroidApplication = pkg.applicationInfo;
5229
5230                if (!mResolverReplaced) {
5231                    mResolveActivity.applicationInfo = mAndroidApplication;
5232                    mResolveActivity.name = ResolverActivity.class.getName();
5233                    mResolveActivity.packageName = mAndroidApplication.packageName;
5234                    mResolveActivity.processName = "system:ui";
5235                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5236                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5237                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5238                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5239                    mResolveActivity.exported = true;
5240                    mResolveActivity.enabled = true;
5241                    mResolveInfo.activityInfo = mResolveActivity;
5242                    mResolveInfo.priority = 0;
5243                    mResolveInfo.preferredOrder = 0;
5244                    mResolveInfo.match = 0;
5245                    mResolveComponentName = new ComponentName(
5246                            mAndroidApplication.packageName, mResolveActivity.name);
5247                }
5248            }
5249        }
5250
5251        if (DEBUG_PACKAGE_SCANNING) {
5252            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5253                Log.d(TAG, "Scanning package " + pkg.packageName);
5254        }
5255
5256        if (mPackages.containsKey(pkg.packageName)
5257                || mSharedLibraries.containsKey(pkg.packageName)) {
5258            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5259                    "Application package " + pkg.packageName
5260                    + " already installed.  Skipping duplicate.");
5261        }
5262
5263        // Initialize package source and resource directories
5264        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5265        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5266
5267        SharedUserSetting suid = null;
5268        PackageSetting pkgSetting = null;
5269
5270        if (!isSystemApp(pkg)) {
5271            // Only system apps can use these features.
5272            pkg.mOriginalPackages = null;
5273            pkg.mRealPackage = null;
5274            pkg.mAdoptPermissions = null;
5275        }
5276
5277        // writer
5278        synchronized (mPackages) {
5279            if (pkg.mSharedUserId != null) {
5280                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5281                if (suid == null) {
5282                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5283                            "Creating application package " + pkg.packageName
5284                            + " for shared user failed");
5285                }
5286                if (DEBUG_PACKAGE_SCANNING) {
5287                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5288                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5289                                + "): packages=" + suid.packages);
5290                }
5291            }
5292
5293            // Check if we are renaming from an original package name.
5294            PackageSetting origPackage = null;
5295            String realName = null;
5296            if (pkg.mOriginalPackages != null) {
5297                // This package may need to be renamed to a previously
5298                // installed name.  Let's check on that...
5299                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5300                if (pkg.mOriginalPackages.contains(renamed)) {
5301                    // This package had originally been installed as the
5302                    // original name, and we have already taken care of
5303                    // transitioning to the new one.  Just update the new
5304                    // one to continue using the old name.
5305                    realName = pkg.mRealPackage;
5306                    if (!pkg.packageName.equals(renamed)) {
5307                        // Callers into this function may have already taken
5308                        // care of renaming the package; only do it here if
5309                        // it is not already done.
5310                        pkg.setPackageName(renamed);
5311                    }
5312
5313                } else {
5314                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5315                        if ((origPackage = mSettings.peekPackageLPr(
5316                                pkg.mOriginalPackages.get(i))) != null) {
5317                            // We do have the package already installed under its
5318                            // original name...  should we use it?
5319                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5320                                // New package is not compatible with original.
5321                                origPackage = null;
5322                                continue;
5323                            } else if (origPackage.sharedUser != null) {
5324                                // Make sure uid is compatible between packages.
5325                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5326                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5327                                            + " to " + pkg.packageName + ": old uid "
5328                                            + origPackage.sharedUser.name
5329                                            + " differs from " + pkg.mSharedUserId);
5330                                    origPackage = null;
5331                                    continue;
5332                                }
5333                            } else {
5334                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5335                                        + pkg.packageName + " to old name " + origPackage.name);
5336                            }
5337                            break;
5338                        }
5339                    }
5340                }
5341            }
5342
5343            if (mTransferedPackages.contains(pkg.packageName)) {
5344                Slog.w(TAG, "Package " + pkg.packageName
5345                        + " was transferred to another, but its .apk remains");
5346            }
5347
5348            // Just create the setting, don't add it yet. For already existing packages
5349            // the PkgSetting exists already and doesn't have to be created.
5350            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5351                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5352                    pkg.applicationInfo.primaryCpuAbi,
5353                    pkg.applicationInfo.secondaryCpuAbi,
5354                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5355                    user, false);
5356            if (pkgSetting == null) {
5357                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5358                        "Creating application package " + pkg.packageName + " failed");
5359            }
5360
5361            if (pkgSetting.origPackage != null) {
5362                // If we are first transitioning from an original package,
5363                // fix up the new package's name now.  We need to do this after
5364                // looking up the package under its new name, so getPackageLP
5365                // can take care of fiddling things correctly.
5366                pkg.setPackageName(origPackage.name);
5367
5368                // File a report about this.
5369                String msg = "New package " + pkgSetting.realName
5370                        + " renamed to replace old package " + pkgSetting.name;
5371                reportSettingsProblem(Log.WARN, msg);
5372
5373                // Make a note of it.
5374                mTransferedPackages.add(origPackage.name);
5375
5376                // No longer need to retain this.
5377                pkgSetting.origPackage = null;
5378            }
5379
5380            if (realName != null) {
5381                // Make a note of it.
5382                mTransferedPackages.add(pkg.packageName);
5383            }
5384
5385            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5386                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5387            }
5388
5389            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5390                // Check all shared libraries and map to their actual file path.
5391                // We only do this here for apps not on a system dir, because those
5392                // are the only ones that can fail an install due to this.  We
5393                // will take care of the system apps by updating all of their
5394                // library paths after the scan is done.
5395                updateSharedLibrariesLPw(pkg, null);
5396            }
5397
5398            if (mFoundPolicyFile) {
5399                SELinuxMMAC.assignSeinfoValue(pkg);
5400            }
5401
5402            pkg.applicationInfo.uid = pkgSetting.appId;
5403            pkg.mExtras = pkgSetting;
5404            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5405                try {
5406                    verifySignaturesLP(pkgSetting, pkg);
5407                    // We just determined the app is signed correctly, so bring
5408                    // over the latest parsed certs.
5409                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5410                } catch (PackageManagerException e) {
5411                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5412                        throw e;
5413                    }
5414                    // The signature has changed, but this package is in the system
5415                    // image...  let's recover!
5416                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5417                    // However...  if this package is part of a shared user, but it
5418                    // doesn't match the signature of the shared user, let's fail.
5419                    // What this means is that you can't change the signatures
5420                    // associated with an overall shared user, which doesn't seem all
5421                    // that unreasonable.
5422                    if (pkgSetting.sharedUser != null) {
5423                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5424                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5425                            throw new PackageManagerException(
5426                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5427                                            "Signature mismatch for shared user : "
5428                                            + pkgSetting.sharedUser);
5429                        }
5430                    }
5431                    // File a report about this.
5432                    String msg = "System package " + pkg.packageName
5433                        + " signature changed; retaining data.";
5434                    reportSettingsProblem(Log.WARN, msg);
5435                }
5436            } else {
5437                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5438                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5439                            + pkg.packageName + " upgrade keys do not match the "
5440                            + "previously installed version");
5441                } else {
5442                    // We just determined the app is signed correctly, so bring
5443                    // over the latest parsed certs.
5444                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5445                }
5446            }
5447            // Verify that this new package doesn't have any content providers
5448            // that conflict with existing packages.  Only do this if the
5449            // package isn't already installed, since we don't want to break
5450            // things that are installed.
5451            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5452                final int N = pkg.providers.size();
5453                int i;
5454                for (i=0; i<N; i++) {
5455                    PackageParser.Provider p = pkg.providers.get(i);
5456                    if (p.info.authority != null) {
5457                        String names[] = p.info.authority.split(";");
5458                        for (int j = 0; j < names.length; j++) {
5459                            if (mProvidersByAuthority.containsKey(names[j])) {
5460                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5461                                final String otherPackageName =
5462                                        ((other != null && other.getComponentName() != null) ?
5463                                                other.getComponentName().getPackageName() : "?");
5464                                throw new PackageManagerException(
5465                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5466                                                "Can't install because provider name " + names[j]
5467                                                + " (in package " + pkg.applicationInfo.packageName
5468                                                + ") is already used by " + otherPackageName);
5469                            }
5470                        }
5471                    }
5472                }
5473            }
5474
5475            if (pkg.mAdoptPermissions != null) {
5476                // This package wants to adopt ownership of permissions from
5477                // another package.
5478                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5479                    final String origName = pkg.mAdoptPermissions.get(i);
5480                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5481                    if (orig != null) {
5482                        if (verifyPackageUpdateLPr(orig, pkg)) {
5483                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5484                                    + pkg.packageName);
5485                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5486                        }
5487                    }
5488                }
5489            }
5490        }
5491
5492        final String pkgName = pkg.packageName;
5493
5494        final long scanFileTime = scanFile.lastModified();
5495        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5496        pkg.applicationInfo.processName = fixProcessName(
5497                pkg.applicationInfo.packageName,
5498                pkg.applicationInfo.processName,
5499                pkg.applicationInfo.uid);
5500
5501        File dataPath;
5502        if (mPlatformPackage == pkg) {
5503            // The system package is special.
5504            dataPath = new File(Environment.getDataDirectory(), "system");
5505
5506            pkg.applicationInfo.dataDir = dataPath.getPath();
5507
5508        } else {
5509            // This is a normal package, need to make its data directory.
5510            dataPath = getDataPathForPackage(pkg.packageName, 0);
5511
5512            boolean uidError = false;
5513            if (dataPath.exists()) {
5514                int currentUid = 0;
5515                try {
5516                    StructStat stat = Os.stat(dataPath.getPath());
5517                    currentUid = stat.st_uid;
5518                } catch (ErrnoException e) {
5519                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5520                }
5521
5522                // If we have mismatched owners for the data path, we have a problem.
5523                if (currentUid != pkg.applicationInfo.uid) {
5524                    boolean recovered = false;
5525                    if (currentUid == 0) {
5526                        // The directory somehow became owned by root.  Wow.
5527                        // This is probably because the system was stopped while
5528                        // installd was in the middle of messing with its libs
5529                        // directory.  Ask installd to fix that.
5530                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5531                                pkg.applicationInfo.uid);
5532                        if (ret >= 0) {
5533                            recovered = true;
5534                            String msg = "Package " + pkg.packageName
5535                                    + " unexpectedly changed to uid 0; recovered to " +
5536                                    + pkg.applicationInfo.uid;
5537                            reportSettingsProblem(Log.WARN, msg);
5538                        }
5539                    }
5540                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5541                            || (scanFlags&SCAN_BOOTING) != 0)) {
5542                        // If this is a system app, we can at least delete its
5543                        // current data so the application will still work.
5544                        int ret = removeDataDirsLI(pkgName);
5545                        if (ret >= 0) {
5546                            // TODO: Kill the processes first
5547                            // Old data gone!
5548                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5549                                    ? "System package " : "Third party package ";
5550                            String msg = prefix + pkg.packageName
5551                                    + " has changed from uid: "
5552                                    + currentUid + " to "
5553                                    + pkg.applicationInfo.uid + "; old data erased";
5554                            reportSettingsProblem(Log.WARN, msg);
5555                            recovered = true;
5556
5557                            // And now re-install the app.
5558                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5559                                                   pkg.applicationInfo.seinfo);
5560                            if (ret == -1) {
5561                                // Ack should not happen!
5562                                msg = prefix + pkg.packageName
5563                                        + " could not have data directory re-created after delete.";
5564                                reportSettingsProblem(Log.WARN, msg);
5565                                throw new PackageManagerException(
5566                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5567                            }
5568                        }
5569                        if (!recovered) {
5570                            mHasSystemUidErrors = true;
5571                        }
5572                    } else if (!recovered) {
5573                        // If we allow this install to proceed, we will be broken.
5574                        // Abort, abort!
5575                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5576                                "scanPackageLI");
5577                    }
5578                    if (!recovered) {
5579                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5580                            + pkg.applicationInfo.uid + "/fs_"
5581                            + currentUid;
5582                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5583                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5584                        String msg = "Package " + pkg.packageName
5585                                + " has mismatched uid: "
5586                                + currentUid + " on disk, "
5587                                + pkg.applicationInfo.uid + " in settings";
5588                        // writer
5589                        synchronized (mPackages) {
5590                            mSettings.mReadMessages.append(msg);
5591                            mSettings.mReadMessages.append('\n');
5592                            uidError = true;
5593                            if (!pkgSetting.uidError) {
5594                                reportSettingsProblem(Log.ERROR, msg);
5595                            }
5596                        }
5597                    }
5598                }
5599                pkg.applicationInfo.dataDir = dataPath.getPath();
5600                if (mShouldRestoreconData) {
5601                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5602                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5603                                pkg.applicationInfo.uid);
5604                }
5605            } else {
5606                if (DEBUG_PACKAGE_SCANNING) {
5607                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5608                        Log.v(TAG, "Want this data dir: " + dataPath);
5609                }
5610                //invoke installer to do the actual installation
5611                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5612                                           pkg.applicationInfo.seinfo);
5613                if (ret < 0) {
5614                    // Error from installer
5615                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5616                            "Unable to create data dirs [errorCode=" + ret + "]");
5617                }
5618
5619                if (dataPath.exists()) {
5620                    pkg.applicationInfo.dataDir = dataPath.getPath();
5621                } else {
5622                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5623                    pkg.applicationInfo.dataDir = null;
5624                }
5625            }
5626
5627            pkgSetting.uidError = uidError;
5628        }
5629
5630        final String path = scanFile.getPath();
5631        final String codePath = pkg.applicationInfo.getCodePath();
5632        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5633        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5634            setBundledAppAbisAndRoots(pkg, pkgSetting);
5635
5636            // If we haven't found any native libraries for the app, check if it has
5637            // renderscript code. We'll need to force the app to 32 bit if it has
5638            // renderscript bitcode.
5639            if (pkg.applicationInfo.primaryCpuAbi == null
5640                    && pkg.applicationInfo.secondaryCpuAbi == null
5641                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5642                NativeLibraryHelper.Handle handle = null;
5643                try {
5644                    handle = NativeLibraryHelper.Handle.create(scanFile);
5645                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5646                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5647                    }
5648                } catch (IOException ioe) {
5649                    Slog.w(TAG, "Error scanning system app : " + ioe);
5650                } finally {
5651                    IoUtils.closeQuietly(handle);
5652                }
5653            }
5654
5655            setNativeLibraryPaths(pkg);
5656        } else {
5657            // TODO: We can probably be smarter about this stuff. For installed apps,
5658            // we can calculate this information at install time once and for all. For
5659            // system apps, we can probably assume that this information doesn't change
5660            // after the first boot scan. As things stand, we do lots of unnecessary work.
5661
5662            // Give ourselves some initial paths; we'll come back for another
5663            // pass once we've determined ABI below.
5664            setNativeLibraryPaths(pkg);
5665
5666            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
5667            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5668            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5669
5670            NativeLibraryHelper.Handle handle = null;
5671            try {
5672                handle = NativeLibraryHelper.Handle.create(scanFile);
5673                // TODO(multiArch): This can be null for apps that didn't go through the
5674                // usual installation process. We can calculate it again, like we
5675                // do during install time.
5676                //
5677                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5678                // unnecessary.
5679                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5680
5681                // Null out the abis so that they can be recalculated.
5682                pkg.applicationInfo.primaryCpuAbi = null;
5683                pkg.applicationInfo.secondaryCpuAbi = null;
5684                if (isMultiArch(pkg.applicationInfo)) {
5685                    // Warn if we've set an abiOverride for multi-lib packages..
5686                    // By definition, we need to copy both 32 and 64 bit libraries for
5687                    // such packages.
5688                    if (pkg.cpuAbiOverride != null
5689                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5690                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5691                    }
5692
5693                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5694                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5695                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5696                        if (isAsec) {
5697                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5698                        } else {
5699                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5700                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5701                                    useIsaSpecificSubdirs);
5702                        }
5703                    }
5704
5705                    maybeThrowExceptionForMultiArchCopy(
5706                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5707
5708                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5709                        if (isAsec) {
5710                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5711                        } else {
5712                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5713                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5714                                    useIsaSpecificSubdirs);
5715                        }
5716                    }
5717
5718                    maybeThrowExceptionForMultiArchCopy(
5719                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5720
5721                    if (abi64 >= 0) {
5722                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5723                    }
5724
5725                    if (abi32 >= 0) {
5726                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5727                        if (abi64 >= 0) {
5728                            pkg.applicationInfo.secondaryCpuAbi = abi;
5729                        } else {
5730                            pkg.applicationInfo.primaryCpuAbi = abi;
5731                        }
5732                    }
5733                } else {
5734                    String[] abiList = (cpuAbiOverride != null) ?
5735                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5736
5737                    // Enable gross and lame hacks for apps that are built with old
5738                    // SDK tools. We must scan their APKs for renderscript bitcode and
5739                    // not launch them if it's present. Don't bother checking on devices
5740                    // that don't have 64 bit support.
5741                    boolean needsRenderScriptOverride = false;
5742                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5743                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5744                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5745                        needsRenderScriptOverride = true;
5746                    }
5747
5748                    final int copyRet;
5749                    if (isAsec) {
5750                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5751                    } else {
5752                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5753                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5754                    }
5755
5756                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5757                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5758                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5759                    }
5760
5761                    if (copyRet >= 0) {
5762                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5763                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5764                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5765                    } else if (needsRenderScriptOverride) {
5766                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5767                    }
5768                }
5769            } catch (IOException ioe) {
5770                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5771            } finally {
5772                IoUtils.closeQuietly(handle);
5773            }
5774
5775            // Now that we've calculated the ABIs and determined if it's an internal app,
5776            // we will go ahead and populate the nativeLibraryPath.
5777            setNativeLibraryPaths(pkg);
5778
5779            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5780            final int[] userIds = sUserManager.getUserIds();
5781            synchronized (mInstallLock) {
5782                // Create a native library symlink only if we have native libraries
5783                // and if the native libraries are 32 bit libraries. We do not provide
5784                // this symlink for 64 bit libraries.
5785                if (pkg.applicationInfo.primaryCpuAbi != null &&
5786                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5787                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5788                    for (int userId : userIds) {
5789                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5790                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5791                                    "Failed linking native library dir (user=" + userId + ")");
5792                        }
5793                    }
5794                }
5795            }
5796        }
5797
5798        // This is a special case for the "system" package, where the ABI is
5799        // dictated by the zygote configuration (and init.rc). We should keep track
5800        // of this ABI so that we can deal with "normal" applications that run under
5801        // the same UID correctly.
5802        if (mPlatformPackage == pkg) {
5803            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5804                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5805        }
5806
5807        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5808        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5809        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5810        // Copy the derived override back to the parsed package, so that we can
5811        // update the package settings accordingly.
5812        pkg.cpuAbiOverride = cpuAbiOverride;
5813
5814        if (DEBUG_ABI_SELECTION) {
5815            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5816                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5817                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5818        }
5819
5820        // Push the derived path down into PackageSettings so we know what to
5821        // clean up at uninstall time.
5822        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5823
5824        if (DEBUG_ABI_SELECTION) {
5825            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5826                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5827                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5828        }
5829
5830        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5831            // We don't do this here during boot because we can do it all
5832            // at once after scanning all existing packages.
5833            //
5834            // We also do this *before* we perform dexopt on this package, so that
5835            // we can avoid redundant dexopts, and also to make sure we've got the
5836            // code and package path correct.
5837            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5838                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5839        }
5840
5841        if ((scanFlags & SCAN_NO_DEX) == 0) {
5842            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
5843                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
5844            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5845                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5846            }
5847        }
5848
5849        if (mFactoryTest && pkg.requestedPermissions.contains(
5850                android.Manifest.permission.FACTORY_TEST)) {
5851            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5852        }
5853
5854        ArrayList<PackageParser.Package> clientLibPkgs = null;
5855
5856        // writer
5857        synchronized (mPackages) {
5858            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5859                // Only system apps can add new shared libraries.
5860                if (pkg.libraryNames != null) {
5861                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5862                        String name = pkg.libraryNames.get(i);
5863                        boolean allowed = false;
5864                        if (isUpdatedSystemApp(pkg)) {
5865                            // New library entries can only be added through the
5866                            // system image.  This is important to get rid of a lot
5867                            // of nasty edge cases: for example if we allowed a non-
5868                            // system update of the app to add a library, then uninstalling
5869                            // the update would make the library go away, and assumptions
5870                            // we made such as through app install filtering would now
5871                            // have allowed apps on the device which aren't compatible
5872                            // with it.  Better to just have the restriction here, be
5873                            // conservative, and create many fewer cases that can negatively
5874                            // impact the user experience.
5875                            final PackageSetting sysPs = mSettings
5876                                    .getDisabledSystemPkgLPr(pkg.packageName);
5877                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5878                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5879                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5880                                        allowed = true;
5881                                        allowed = true;
5882                                        break;
5883                                    }
5884                                }
5885                            }
5886                        } else {
5887                            allowed = true;
5888                        }
5889                        if (allowed) {
5890                            if (!mSharedLibraries.containsKey(name)) {
5891                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5892                            } else if (!name.equals(pkg.packageName)) {
5893                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5894                                        + name + " already exists; skipping");
5895                            }
5896                        } else {
5897                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5898                                    + name + " that is not declared on system image; skipping");
5899                        }
5900                    }
5901                    if ((scanFlags&SCAN_BOOTING) == 0) {
5902                        // If we are not booting, we need to update any applications
5903                        // that are clients of our shared library.  If we are booting,
5904                        // this will all be done once the scan is complete.
5905                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5906                    }
5907                }
5908            }
5909        }
5910
5911        // We also need to dexopt any apps that are dependent on this library.  Note that
5912        // if these fail, we should abort the install since installing the library will
5913        // result in some apps being broken.
5914        if (clientLibPkgs != null) {
5915            if ((scanFlags & SCAN_NO_DEX) == 0) {
5916                for (int i = 0; i < clientLibPkgs.size(); i++) {
5917                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5918                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
5919                            null /* instruction sets */, forceDex,
5920                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
5921                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5922                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5923                                "scanPackageLI failed to dexopt clientLibPkgs");
5924                    }
5925                }
5926            }
5927        }
5928
5929        // Request the ActivityManager to kill the process(only for existing packages)
5930        // so that we do not end up in a confused state while the user is still using the older
5931        // version of the application while the new one gets installed.
5932        if ((scanFlags & SCAN_REPLACING) != 0) {
5933            killApplication(pkg.applicationInfo.packageName,
5934                        pkg.applicationInfo.uid, "update pkg");
5935        }
5936
5937        // Also need to kill any apps that are dependent on the library.
5938        if (clientLibPkgs != null) {
5939            for (int i=0; i<clientLibPkgs.size(); i++) {
5940                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5941                killApplication(clientPkg.applicationInfo.packageName,
5942                        clientPkg.applicationInfo.uid, "update lib");
5943            }
5944        }
5945
5946        // writer
5947        synchronized (mPackages) {
5948            // We don't expect installation to fail beyond this point
5949
5950            // Add the new setting to mSettings
5951            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5952            // Add the new setting to mPackages
5953            mPackages.put(pkg.applicationInfo.packageName, pkg);
5954            // Make sure we don't accidentally delete its data.
5955            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5956            while (iter.hasNext()) {
5957                PackageCleanItem item = iter.next();
5958                if (pkgName.equals(item.packageName)) {
5959                    iter.remove();
5960                }
5961            }
5962
5963            // Take care of first install / last update times.
5964            if (currentTime != 0) {
5965                if (pkgSetting.firstInstallTime == 0) {
5966                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5967                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5968                    pkgSetting.lastUpdateTime = currentTime;
5969                }
5970            } else if (pkgSetting.firstInstallTime == 0) {
5971                // We need *something*.  Take time time stamp of the file.
5972                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5973            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5974                if (scanFileTime != pkgSetting.timeStamp) {
5975                    // A package on the system image has changed; consider this
5976                    // to be an update.
5977                    pkgSetting.lastUpdateTime = scanFileTime;
5978                }
5979            }
5980
5981            // Add the package's KeySets to the global KeySetManagerService
5982            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5983            try {
5984                // Old KeySetData no longer valid.
5985                ksms.removeAppKeySetDataLPw(pkg.packageName);
5986                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5987                if (pkg.mKeySetMapping != null) {
5988                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5989                            pkg.mKeySetMapping.entrySet()) {
5990                        if (entry.getValue() != null) {
5991                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5992                                                          entry.getValue(), entry.getKey());
5993                        }
5994                    }
5995                    if (pkg.mUpgradeKeySets != null) {
5996                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5997                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5998                        }
5999                    }
6000                }
6001            } catch (NullPointerException e) {
6002                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6003            } catch (IllegalArgumentException e) {
6004                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6005            }
6006
6007            int N = pkg.providers.size();
6008            StringBuilder r = null;
6009            int i;
6010            for (i=0; i<N; i++) {
6011                PackageParser.Provider p = pkg.providers.get(i);
6012                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6013                        p.info.processName, pkg.applicationInfo.uid);
6014                mProviders.addProvider(p);
6015                p.syncable = p.info.isSyncable;
6016                if (p.info.authority != null) {
6017                    String names[] = p.info.authority.split(";");
6018                    p.info.authority = null;
6019                    for (int j = 0; j < names.length; j++) {
6020                        if (j == 1 && p.syncable) {
6021                            // We only want the first authority for a provider to possibly be
6022                            // syncable, so if we already added this provider using a different
6023                            // authority clear the syncable flag. We copy the provider before
6024                            // changing it because the mProviders object contains a reference
6025                            // to a provider that we don't want to change.
6026                            // Only do this for the second authority since the resulting provider
6027                            // object can be the same for all future authorities for this provider.
6028                            p = new PackageParser.Provider(p);
6029                            p.syncable = false;
6030                        }
6031                        if (!mProvidersByAuthority.containsKey(names[j])) {
6032                            mProvidersByAuthority.put(names[j], p);
6033                            if (p.info.authority == null) {
6034                                p.info.authority = names[j];
6035                            } else {
6036                                p.info.authority = p.info.authority + ";" + names[j];
6037                            }
6038                            if (DEBUG_PACKAGE_SCANNING) {
6039                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6040                                    Log.d(TAG, "Registered content provider: " + names[j]
6041                                            + ", className = " + p.info.name + ", isSyncable = "
6042                                            + p.info.isSyncable);
6043                            }
6044                        } else {
6045                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6046                            Slog.w(TAG, "Skipping provider name " + names[j] +
6047                                    " (in package " + pkg.applicationInfo.packageName +
6048                                    "): name already used by "
6049                                    + ((other != null && other.getComponentName() != null)
6050                                            ? other.getComponentName().getPackageName() : "?"));
6051                        }
6052                    }
6053                }
6054                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6055                    if (r == null) {
6056                        r = new StringBuilder(256);
6057                    } else {
6058                        r.append(' ');
6059                    }
6060                    r.append(p.info.name);
6061                }
6062            }
6063            if (r != null) {
6064                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6065            }
6066
6067            N = pkg.services.size();
6068            r = null;
6069            for (i=0; i<N; i++) {
6070                PackageParser.Service s = pkg.services.get(i);
6071                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6072                        s.info.processName, pkg.applicationInfo.uid);
6073                mServices.addService(s);
6074                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6075                    if (r == null) {
6076                        r = new StringBuilder(256);
6077                    } else {
6078                        r.append(' ');
6079                    }
6080                    r.append(s.info.name);
6081                }
6082            }
6083            if (r != null) {
6084                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6085            }
6086
6087            N = pkg.receivers.size();
6088            r = null;
6089            for (i=0; i<N; i++) {
6090                PackageParser.Activity a = pkg.receivers.get(i);
6091                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6092                        a.info.processName, pkg.applicationInfo.uid);
6093                mReceivers.addActivity(a, "receiver");
6094                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6095                    if (r == null) {
6096                        r = new StringBuilder(256);
6097                    } else {
6098                        r.append(' ');
6099                    }
6100                    r.append(a.info.name);
6101                }
6102            }
6103            if (r != null) {
6104                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6105            }
6106
6107            N = pkg.activities.size();
6108            r = null;
6109            for (i=0; i<N; i++) {
6110                PackageParser.Activity a = pkg.activities.get(i);
6111                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6112                        a.info.processName, pkg.applicationInfo.uid);
6113                mActivities.addActivity(a, "activity");
6114                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6115                    if (r == null) {
6116                        r = new StringBuilder(256);
6117                    } else {
6118                        r.append(' ');
6119                    }
6120                    r.append(a.info.name);
6121                }
6122            }
6123            if (r != null) {
6124                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6125            }
6126
6127            N = pkg.permissionGroups.size();
6128            r = null;
6129            for (i=0; i<N; i++) {
6130                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6131                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6132                if (cur == null) {
6133                    mPermissionGroups.put(pg.info.name, pg);
6134                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6135                        if (r == null) {
6136                            r = new StringBuilder(256);
6137                        } else {
6138                            r.append(' ');
6139                        }
6140                        r.append(pg.info.name);
6141                    }
6142                } else {
6143                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6144                            + pg.info.packageName + " ignored: original from "
6145                            + cur.info.packageName);
6146                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6147                        if (r == null) {
6148                            r = new StringBuilder(256);
6149                        } else {
6150                            r.append(' ');
6151                        }
6152                        r.append("DUP:");
6153                        r.append(pg.info.name);
6154                    }
6155                }
6156            }
6157            if (r != null) {
6158                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6159            }
6160
6161            N = pkg.permissions.size();
6162            r = null;
6163            for (i=0; i<N; i++) {
6164                PackageParser.Permission p = pkg.permissions.get(i);
6165                ArrayMap<String, BasePermission> permissionMap =
6166                        p.tree ? mSettings.mPermissionTrees
6167                        : mSettings.mPermissions;
6168                p.group = mPermissionGroups.get(p.info.group);
6169                if (p.info.group == null || p.group != null) {
6170                    BasePermission bp = permissionMap.get(p.info.name);
6171
6172                    // Allow system apps to redefine non-system permissions
6173                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6174                        final boolean currentOwnerIsSystem = (bp.perm != null
6175                                && isSystemApp(bp.perm.owner));
6176                        if (isSystemApp(p.owner)) {
6177                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6178                                // It's a built-in permission and no owner, take ownership now
6179                                bp.packageSetting = pkgSetting;
6180                                bp.perm = p;
6181                                bp.uid = pkg.applicationInfo.uid;
6182                                bp.sourcePackage = p.info.packageName;
6183                            } else if (!currentOwnerIsSystem) {
6184                                String msg = "New decl " + p.owner + " of permission  "
6185                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6186                                reportSettingsProblem(Log.WARN, msg);
6187                                bp = null;
6188                            }
6189                        }
6190                    }
6191
6192                    if (bp == null) {
6193                        bp = new BasePermission(p.info.name, p.info.packageName,
6194                                BasePermission.TYPE_NORMAL);
6195                        permissionMap.put(p.info.name, bp);
6196                    }
6197
6198                    if (bp.perm == null) {
6199                        if (bp.sourcePackage == null
6200                                || bp.sourcePackage.equals(p.info.packageName)) {
6201                            BasePermission tree = findPermissionTreeLP(p.info.name);
6202                            if (tree == null
6203                                    || tree.sourcePackage.equals(p.info.packageName)) {
6204                                bp.packageSetting = pkgSetting;
6205                                bp.perm = p;
6206                                bp.uid = pkg.applicationInfo.uid;
6207                                bp.sourcePackage = p.info.packageName;
6208                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6209                                    if (r == null) {
6210                                        r = new StringBuilder(256);
6211                                    } else {
6212                                        r.append(' ');
6213                                    }
6214                                    r.append(p.info.name);
6215                                }
6216                            } else {
6217                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6218                                        + p.info.packageName + " ignored: base tree "
6219                                        + tree.name + " is from package "
6220                                        + tree.sourcePackage);
6221                            }
6222                        } else {
6223                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6224                                    + p.info.packageName + " ignored: original from "
6225                                    + bp.sourcePackage);
6226                        }
6227                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6228                        if (r == null) {
6229                            r = new StringBuilder(256);
6230                        } else {
6231                            r.append(' ');
6232                        }
6233                        r.append("DUP:");
6234                        r.append(p.info.name);
6235                    }
6236                    if (bp.perm == p) {
6237                        bp.protectionLevel = p.info.protectionLevel;
6238                    }
6239                } else {
6240                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6241                            + p.info.packageName + " ignored: no group "
6242                            + p.group);
6243                }
6244            }
6245            if (r != null) {
6246                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6247            }
6248
6249            N = pkg.instrumentation.size();
6250            r = null;
6251            for (i=0; i<N; i++) {
6252                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6253                a.info.packageName = pkg.applicationInfo.packageName;
6254                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6255                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6256                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6257                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6258                a.info.dataDir = pkg.applicationInfo.dataDir;
6259
6260                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6261                // need other information about the application, like the ABI and what not ?
6262                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6263                mInstrumentation.put(a.getComponentName(), a);
6264                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6265                    if (r == null) {
6266                        r = new StringBuilder(256);
6267                    } else {
6268                        r.append(' ');
6269                    }
6270                    r.append(a.info.name);
6271                }
6272            }
6273            if (r != null) {
6274                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6275            }
6276
6277            if (pkg.protectedBroadcasts != null) {
6278                N = pkg.protectedBroadcasts.size();
6279                for (i=0; i<N; i++) {
6280                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6281                }
6282            }
6283
6284            pkgSetting.setTimeStamp(scanFileTime);
6285
6286            // Create idmap files for pairs of (packages, overlay packages).
6287            // Note: "android", ie framework-res.apk, is handled by native layers.
6288            if (pkg.mOverlayTarget != null) {
6289                // This is an overlay package.
6290                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6291                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6292                        mOverlays.put(pkg.mOverlayTarget,
6293                                new ArrayMap<String, PackageParser.Package>());
6294                    }
6295                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6296                    map.put(pkg.packageName, pkg);
6297                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6298                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6299                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6300                                "scanPackageLI failed to createIdmap");
6301                    }
6302                }
6303            } else if (mOverlays.containsKey(pkg.packageName) &&
6304                    !pkg.packageName.equals("android")) {
6305                // This is a regular package, with one or more known overlay packages.
6306                createIdmapsForPackageLI(pkg);
6307            }
6308        }
6309
6310        return pkg;
6311    }
6312
6313    /**
6314     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6315     * i.e, so that all packages can be run inside a single process if required.
6316     *
6317     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6318     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6319     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6320     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6321     * updating a package that belongs to a shared user.
6322     *
6323     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6324     * adds unnecessary complexity.
6325     */
6326    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6327            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6328        String requiredInstructionSet = null;
6329        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6330            requiredInstructionSet = VMRuntime.getInstructionSet(
6331                     scannedPackage.applicationInfo.primaryCpuAbi);
6332        }
6333
6334        PackageSetting requirer = null;
6335        for (PackageSetting ps : packagesForUser) {
6336            // If packagesForUser contains scannedPackage, we skip it. This will happen
6337            // when scannedPackage is an update of an existing package. Without this check,
6338            // we will never be able to change the ABI of any package belonging to a shared
6339            // user, even if it's compatible with other packages.
6340            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6341                if (ps.primaryCpuAbiString == null) {
6342                    continue;
6343                }
6344
6345                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6346                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6347                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6348                    // this but there's not much we can do.
6349                    String errorMessage = "Instruction set mismatch, "
6350                            + ((requirer == null) ? "[caller]" : requirer)
6351                            + " requires " + requiredInstructionSet + " whereas " + ps
6352                            + " requires " + instructionSet;
6353                    Slog.w(TAG, errorMessage);
6354                }
6355
6356                if (requiredInstructionSet == null) {
6357                    requiredInstructionSet = instructionSet;
6358                    requirer = ps;
6359                }
6360            }
6361        }
6362
6363        if (requiredInstructionSet != null) {
6364            String adjustedAbi;
6365            if (requirer != null) {
6366                // requirer != null implies that either scannedPackage was null or that scannedPackage
6367                // did not require an ABI, in which case we have to adjust scannedPackage to match
6368                // the ABI of the set (which is the same as requirer's ABI)
6369                adjustedAbi = requirer.primaryCpuAbiString;
6370                if (scannedPackage != null) {
6371                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6372                }
6373            } else {
6374                // requirer == null implies that we're updating all ABIs in the set to
6375                // match scannedPackage.
6376                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6377            }
6378
6379            for (PackageSetting ps : packagesForUser) {
6380                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6381                    if (ps.primaryCpuAbiString != null) {
6382                        continue;
6383                    }
6384
6385                    ps.primaryCpuAbiString = adjustedAbi;
6386                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6387                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6388                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6389
6390                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6391                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6392                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6393                            ps.primaryCpuAbiString = null;
6394                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6395                            return;
6396                        } else {
6397                            mInstaller.rmdex(ps.codePathString,
6398                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6399                        }
6400                    }
6401                }
6402            }
6403        }
6404    }
6405
6406    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6407        synchronized (mPackages) {
6408            mResolverReplaced = true;
6409            // Set up information for custom user intent resolution activity.
6410            mResolveActivity.applicationInfo = pkg.applicationInfo;
6411            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6412            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6413            mResolveActivity.processName = pkg.applicationInfo.packageName;
6414            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6415            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6416                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6417            mResolveActivity.theme = 0;
6418            mResolveActivity.exported = true;
6419            mResolveActivity.enabled = true;
6420            mResolveInfo.activityInfo = mResolveActivity;
6421            mResolveInfo.priority = 0;
6422            mResolveInfo.preferredOrder = 0;
6423            mResolveInfo.match = 0;
6424            mResolveComponentName = mCustomResolverComponentName;
6425            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6426                    mResolveComponentName);
6427        }
6428    }
6429
6430    private static String calculateBundledApkRoot(final String codePathString) {
6431        final File codePath = new File(codePathString);
6432        final File codeRoot;
6433        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6434            codeRoot = Environment.getRootDirectory();
6435        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6436            codeRoot = Environment.getOemDirectory();
6437        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6438            codeRoot = Environment.getVendorDirectory();
6439        } else {
6440            // Unrecognized code path; take its top real segment as the apk root:
6441            // e.g. /something/app/blah.apk => /something
6442            try {
6443                File f = codePath.getCanonicalFile();
6444                File parent = f.getParentFile();    // non-null because codePath is a file
6445                File tmp;
6446                while ((tmp = parent.getParentFile()) != null) {
6447                    f = parent;
6448                    parent = tmp;
6449                }
6450                codeRoot = f;
6451                Slog.w(TAG, "Unrecognized code path "
6452                        + codePath + " - using " + codeRoot);
6453            } catch (IOException e) {
6454                // Can't canonicalize the code path -- shenanigans?
6455                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6456                return Environment.getRootDirectory().getPath();
6457            }
6458        }
6459        return codeRoot.getPath();
6460    }
6461
6462    /**
6463     * Derive and set the location of native libraries for the given package,
6464     * which varies depending on where and how the package was installed.
6465     */
6466    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6467        final ApplicationInfo info = pkg.applicationInfo;
6468        final String codePath = pkg.codePath;
6469        final File codeFile = new File(codePath);
6470        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6471        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6472
6473        info.nativeLibraryRootDir = null;
6474        info.nativeLibraryRootRequiresIsa = false;
6475        info.nativeLibraryDir = null;
6476        info.secondaryNativeLibraryDir = null;
6477
6478        if (isApkFile(codeFile)) {
6479            // Monolithic install
6480            if (bundledApp) {
6481                // If "/system/lib64/apkname" exists, assume that is the per-package
6482                // native library directory to use; otherwise use "/system/lib/apkname".
6483                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6484                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6485                        getPrimaryInstructionSet(info));
6486
6487                // This is a bundled system app so choose the path based on the ABI.
6488                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6489                // is just the default path.
6490                final String apkName = deriveCodePathName(codePath);
6491                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6492                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6493                        apkName).getAbsolutePath();
6494
6495                if (info.secondaryCpuAbi != null) {
6496                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6497                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6498                            secondaryLibDir, apkName).getAbsolutePath();
6499                }
6500            } else if (asecApp) {
6501                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6502                        .getAbsolutePath();
6503            } else {
6504                final String apkName = deriveCodePathName(codePath);
6505                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6506                        .getAbsolutePath();
6507            }
6508
6509            info.nativeLibraryRootRequiresIsa = false;
6510            info.nativeLibraryDir = info.nativeLibraryRootDir;
6511        } else {
6512            // Cluster install
6513            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6514            info.nativeLibraryRootRequiresIsa = true;
6515
6516            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6517                    getPrimaryInstructionSet(info)).getAbsolutePath();
6518
6519            if (info.secondaryCpuAbi != null) {
6520                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6521                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6522            }
6523        }
6524    }
6525
6526    /**
6527     * Calculate the abis and roots for a bundled app. These can uniquely
6528     * be determined from the contents of the system partition, i.e whether
6529     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6530     * of this information, and instead assume that the system was built
6531     * sensibly.
6532     */
6533    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6534                                           PackageSetting pkgSetting) {
6535        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6536
6537        // If "/system/lib64/apkname" exists, assume that is the per-package
6538        // native library directory to use; otherwise use "/system/lib/apkname".
6539        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6540        setBundledAppAbi(pkg, apkRoot, apkName);
6541        // pkgSetting might be null during rescan following uninstall of updates
6542        // to a bundled app, so accommodate that possibility.  The settings in
6543        // that case will be established later from the parsed package.
6544        //
6545        // If the settings aren't null, sync them up with what we've just derived.
6546        // note that apkRoot isn't stored in the package settings.
6547        if (pkgSetting != null) {
6548            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6549            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6550        }
6551    }
6552
6553    /**
6554     * Deduces the ABI of a bundled app and sets the relevant fields on the
6555     * parsed pkg object.
6556     *
6557     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6558     *        under which system libraries are installed.
6559     * @param apkName the name of the installed package.
6560     */
6561    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6562        final File codeFile = new File(pkg.codePath);
6563
6564        final boolean has64BitLibs;
6565        final boolean has32BitLibs;
6566        if (isApkFile(codeFile)) {
6567            // Monolithic install
6568            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6569            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6570        } else {
6571            // Cluster install
6572            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6573            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6574                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6575                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6576                has64BitLibs = (new File(rootDir, isa)).exists();
6577            } else {
6578                has64BitLibs = false;
6579            }
6580            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6581                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6582                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6583                has32BitLibs = (new File(rootDir, isa)).exists();
6584            } else {
6585                has32BitLibs = false;
6586            }
6587        }
6588
6589        if (has64BitLibs && !has32BitLibs) {
6590            // The package has 64 bit libs, but not 32 bit libs. Its primary
6591            // ABI should be 64 bit. We can safely assume here that the bundled
6592            // native libraries correspond to the most preferred ABI in the list.
6593
6594            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6595            pkg.applicationInfo.secondaryCpuAbi = null;
6596        } else if (has32BitLibs && !has64BitLibs) {
6597            // The package has 32 bit libs but not 64 bit libs. Its primary
6598            // ABI should be 32 bit.
6599
6600            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6601            pkg.applicationInfo.secondaryCpuAbi = null;
6602        } else if (has32BitLibs && has64BitLibs) {
6603            // The application has both 64 and 32 bit bundled libraries. We check
6604            // here that the app declares multiArch support, and warn if it doesn't.
6605            //
6606            // We will be lenient here and record both ABIs. The primary will be the
6607            // ABI that's higher on the list, i.e, a device that's configured to prefer
6608            // 64 bit apps will see a 64 bit primary ABI,
6609
6610            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6611                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6612            }
6613
6614            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6615                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6616                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6617            } else {
6618                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6619                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6620            }
6621        } else {
6622            pkg.applicationInfo.primaryCpuAbi = null;
6623            pkg.applicationInfo.secondaryCpuAbi = null;
6624        }
6625    }
6626
6627    private void killApplication(String pkgName, int appId, String reason) {
6628        // Request the ActivityManager to kill the process(only for existing packages)
6629        // so that we do not end up in a confused state while the user is still using the older
6630        // version of the application while the new one gets installed.
6631        IActivityManager am = ActivityManagerNative.getDefault();
6632        if (am != null) {
6633            try {
6634                am.killApplicationWithAppId(pkgName, appId, reason);
6635            } catch (RemoteException e) {
6636            }
6637        }
6638    }
6639
6640    void removePackageLI(PackageSetting ps, boolean chatty) {
6641        if (DEBUG_INSTALL) {
6642            if (chatty)
6643                Log.d(TAG, "Removing package " + ps.name);
6644        }
6645
6646        // writer
6647        synchronized (mPackages) {
6648            mPackages.remove(ps.name);
6649            final PackageParser.Package pkg = ps.pkg;
6650            if (pkg != null) {
6651                cleanPackageDataStructuresLILPw(pkg, chatty);
6652            }
6653        }
6654    }
6655
6656    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6657        if (DEBUG_INSTALL) {
6658            if (chatty)
6659                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6660        }
6661
6662        // writer
6663        synchronized (mPackages) {
6664            mPackages.remove(pkg.applicationInfo.packageName);
6665            cleanPackageDataStructuresLILPw(pkg, chatty);
6666        }
6667    }
6668
6669    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6670        int N = pkg.providers.size();
6671        StringBuilder r = null;
6672        int i;
6673        for (i=0; i<N; i++) {
6674            PackageParser.Provider p = pkg.providers.get(i);
6675            mProviders.removeProvider(p);
6676            if (p.info.authority == null) {
6677
6678                /* There was another ContentProvider with this authority when
6679                 * this app was installed so this authority is null,
6680                 * Ignore it as we don't have to unregister the provider.
6681                 */
6682                continue;
6683            }
6684            String names[] = p.info.authority.split(";");
6685            for (int j = 0; j < names.length; j++) {
6686                if (mProvidersByAuthority.get(names[j]) == p) {
6687                    mProvidersByAuthority.remove(names[j]);
6688                    if (DEBUG_REMOVE) {
6689                        if (chatty)
6690                            Log.d(TAG, "Unregistered content provider: " + names[j]
6691                                    + ", className = " + p.info.name + ", isSyncable = "
6692                                    + p.info.isSyncable);
6693                    }
6694                }
6695            }
6696            if (DEBUG_REMOVE && chatty) {
6697                if (r == null) {
6698                    r = new StringBuilder(256);
6699                } else {
6700                    r.append(' ');
6701                }
6702                r.append(p.info.name);
6703            }
6704        }
6705        if (r != null) {
6706            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6707        }
6708
6709        N = pkg.services.size();
6710        r = null;
6711        for (i=0; i<N; i++) {
6712            PackageParser.Service s = pkg.services.get(i);
6713            mServices.removeService(s);
6714            if (chatty) {
6715                if (r == null) {
6716                    r = new StringBuilder(256);
6717                } else {
6718                    r.append(' ');
6719                }
6720                r.append(s.info.name);
6721            }
6722        }
6723        if (r != null) {
6724            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6725        }
6726
6727        N = pkg.receivers.size();
6728        r = null;
6729        for (i=0; i<N; i++) {
6730            PackageParser.Activity a = pkg.receivers.get(i);
6731            mReceivers.removeActivity(a, "receiver");
6732            if (DEBUG_REMOVE && chatty) {
6733                if (r == null) {
6734                    r = new StringBuilder(256);
6735                } else {
6736                    r.append(' ');
6737                }
6738                r.append(a.info.name);
6739            }
6740        }
6741        if (r != null) {
6742            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6743        }
6744
6745        N = pkg.activities.size();
6746        r = null;
6747        for (i=0; i<N; i++) {
6748            PackageParser.Activity a = pkg.activities.get(i);
6749            mActivities.removeActivity(a, "activity");
6750            if (DEBUG_REMOVE && chatty) {
6751                if (r == null) {
6752                    r = new StringBuilder(256);
6753                } else {
6754                    r.append(' ');
6755                }
6756                r.append(a.info.name);
6757            }
6758        }
6759        if (r != null) {
6760            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6761        }
6762
6763        N = pkg.permissions.size();
6764        r = null;
6765        for (i=0; i<N; i++) {
6766            PackageParser.Permission p = pkg.permissions.get(i);
6767            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6768            if (bp == null) {
6769                bp = mSettings.mPermissionTrees.get(p.info.name);
6770            }
6771            if (bp != null && bp.perm == p) {
6772                bp.perm = null;
6773                if (DEBUG_REMOVE && chatty) {
6774                    if (r == null) {
6775                        r = new StringBuilder(256);
6776                    } else {
6777                        r.append(' ');
6778                    }
6779                    r.append(p.info.name);
6780                }
6781            }
6782            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6783                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6784                if (appOpPerms != null) {
6785                    appOpPerms.remove(pkg.packageName);
6786                }
6787            }
6788        }
6789        if (r != null) {
6790            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6791        }
6792
6793        N = pkg.requestedPermissions.size();
6794        r = null;
6795        for (i=0; i<N; i++) {
6796            String perm = pkg.requestedPermissions.get(i);
6797            BasePermission bp = mSettings.mPermissions.get(perm);
6798            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6799                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6800                if (appOpPerms != null) {
6801                    appOpPerms.remove(pkg.packageName);
6802                    if (appOpPerms.isEmpty()) {
6803                        mAppOpPermissionPackages.remove(perm);
6804                    }
6805                }
6806            }
6807        }
6808        if (r != null) {
6809            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6810        }
6811
6812        N = pkg.instrumentation.size();
6813        r = null;
6814        for (i=0; i<N; i++) {
6815            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6816            mInstrumentation.remove(a.getComponentName());
6817            if (DEBUG_REMOVE && chatty) {
6818                if (r == null) {
6819                    r = new StringBuilder(256);
6820                } else {
6821                    r.append(' ');
6822                }
6823                r.append(a.info.name);
6824            }
6825        }
6826        if (r != null) {
6827            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6828        }
6829
6830        r = null;
6831        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6832            // Only system apps can hold shared libraries.
6833            if (pkg.libraryNames != null) {
6834                for (i=0; i<pkg.libraryNames.size(); i++) {
6835                    String name = pkg.libraryNames.get(i);
6836                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6837                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6838                        mSharedLibraries.remove(name);
6839                        if (DEBUG_REMOVE && chatty) {
6840                            if (r == null) {
6841                                r = new StringBuilder(256);
6842                            } else {
6843                                r.append(' ');
6844                            }
6845                            r.append(name);
6846                        }
6847                    }
6848                }
6849            }
6850        }
6851        if (r != null) {
6852            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6853        }
6854    }
6855
6856    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6857        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6858            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6859                return true;
6860            }
6861        }
6862        return false;
6863    }
6864
6865    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6866    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6867    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6868
6869    private void updatePermissionsLPw(String changingPkg,
6870            PackageParser.Package pkgInfo, int flags) {
6871        // Make sure there are no dangling permission trees.
6872        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6873        while (it.hasNext()) {
6874            final BasePermission bp = it.next();
6875            if (bp.packageSetting == null) {
6876                // We may not yet have parsed the package, so just see if
6877                // we still know about its settings.
6878                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6879            }
6880            if (bp.packageSetting == null) {
6881                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6882                        + " from package " + bp.sourcePackage);
6883                it.remove();
6884            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6885                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6886                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6887                            + " from package " + bp.sourcePackage);
6888                    flags |= UPDATE_PERMISSIONS_ALL;
6889                    it.remove();
6890                }
6891            }
6892        }
6893
6894        // Make sure all dynamic permissions have been assigned to a package,
6895        // and make sure there are no dangling permissions.
6896        it = mSettings.mPermissions.values().iterator();
6897        while (it.hasNext()) {
6898            final BasePermission bp = it.next();
6899            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6900                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6901                        + bp.name + " pkg=" + bp.sourcePackage
6902                        + " info=" + bp.pendingInfo);
6903                if (bp.packageSetting == null && bp.pendingInfo != null) {
6904                    final BasePermission tree = findPermissionTreeLP(bp.name);
6905                    if (tree != null && tree.perm != null) {
6906                        bp.packageSetting = tree.packageSetting;
6907                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6908                                new PermissionInfo(bp.pendingInfo));
6909                        bp.perm.info.packageName = tree.perm.info.packageName;
6910                        bp.perm.info.name = bp.name;
6911                        bp.uid = tree.uid;
6912                    }
6913                }
6914            }
6915            if (bp.packageSetting == null) {
6916                // We may not yet have parsed the package, so just see if
6917                // we still know about its settings.
6918                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6919            }
6920            if (bp.packageSetting == null) {
6921                Slog.w(TAG, "Removing dangling permission: " + bp.name
6922                        + " from package " + bp.sourcePackage);
6923                it.remove();
6924            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6925                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6926                    Slog.i(TAG, "Removing old permission: " + bp.name
6927                            + " from package " + bp.sourcePackage);
6928                    flags |= UPDATE_PERMISSIONS_ALL;
6929                    it.remove();
6930                }
6931            }
6932        }
6933
6934        // Now update the permissions for all packages, in particular
6935        // replace the granted permissions of the system packages.
6936        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6937            for (PackageParser.Package pkg : mPackages.values()) {
6938                if (pkg != pkgInfo) {
6939                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6940                            changingPkg);
6941                }
6942            }
6943        }
6944
6945        if (pkgInfo != null) {
6946            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6947        }
6948    }
6949
6950    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6951            String packageOfInterest) {
6952        // IMPORTANT: There are two types of permissions: install and runtime.
6953        // Install time permissions are granted when the app is installed to
6954        // all device users and users added in the future. Runtime permissions
6955        // are granted at runtime explicitly to specific users. Normal and signature
6956        // protected permissions are install time permissions. Dangerous permissions
6957        // are install permissions if the app's target SDK is Lollipop MR1 or older,
6958        // otherwise they are runtime permissions. This function does not manage
6959        // runtime permissions except for the case an app targeting Lollipop MR1
6960        // being upgraded to target a newer SDK, in which case dangerous permissions
6961        // are transformed from install time to runtime ones.
6962
6963        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6964        if (ps == null) {
6965            return;
6966        }
6967
6968        PermissionsState permissionsState = ps.getPermissionsState();
6969        PermissionsState origPermissions = permissionsState;
6970
6971        boolean changedPermission = false;
6972
6973        if (replace) {
6974            ps.permissionsFixed = false;
6975            origPermissions = new PermissionsState(permissionsState);
6976            permissionsState.reset();
6977        }
6978
6979        permissionsState.setGlobalGids(mGlobalGids);
6980
6981        final int N = pkg.requestedPermissions.size();
6982        for (int i=0; i<N; i++) {
6983            final String name = pkg.requestedPermissions.get(i);
6984            final BasePermission bp = mSettings.mPermissions.get(name);
6985
6986            if (DEBUG_INSTALL) {
6987                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6988            }
6989
6990            if (bp == null || bp.packageSetting == null) {
6991                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6992                    Slog.w(TAG, "Unknown permission " + name
6993                            + " in package " + pkg.packageName);
6994                }
6995                continue;
6996            }
6997
6998            final String perm = bp.name;
6999            boolean allowedSig = false;
7000            int grant = GRANT_DENIED;
7001
7002            // Keep track of app op permissions.
7003            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7004                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7005                if (pkgs == null) {
7006                    pkgs = new ArraySet<>();
7007                    mAppOpPermissionPackages.put(bp.name, pkgs);
7008                }
7009                pkgs.add(pkg.packageName);
7010            }
7011
7012            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7013            switch (level) {
7014                case PermissionInfo.PROTECTION_NORMAL: {
7015                    // For all apps normal permissions are install time ones.
7016                    grant = GRANT_INSTALL;
7017                } break;
7018
7019                case PermissionInfo.PROTECTION_DANGEROUS: {
7020                    if (!RUNTIME_PERMISSIONS_ENABLED
7021                            || pkg.applicationInfo.targetSdkVersion
7022                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7023                        // For legacy apps dangerous permissions are install time ones.
7024                        grant = GRANT_INSTALL;
7025                    } else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7026                        // For modern system apps dangerous permissions are install time ones.
7027                        grant = GRANT_INSTALL;
7028                    } else {
7029                        if (origPermissions.hasInstallPermission(bp.name)) {
7030                            // For legacy apps that became modern, install becomes runtime.
7031                            grant = GRANT_UPGRADE;
7032                        } else if (replace) {
7033                            // For upgraded modern apps keep runtime permissions unchanged.
7034                            grant = GRANT_RUNTIME;
7035                        }
7036                    }
7037                } break;
7038
7039                case PermissionInfo.PROTECTION_SIGNATURE: {
7040                    // For all apps signature permissions are install time ones.
7041                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7042                    if (allowedSig) {
7043                        grant = GRANT_INSTALL;
7044                    }
7045                } break;
7046            }
7047
7048            if (DEBUG_INSTALL) {
7049                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7050            }
7051
7052            if (grant != GRANT_DENIED) {
7053                if (!isSystemApp(ps) && ps.permissionsFixed) {
7054                    // If this is an existing, non-system package, then
7055                    // we can't add any new permissions to it.
7056                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7057                        // Except...  if this is a permission that was added
7058                        // to the platform (note: need to only do this when
7059                        // updating the platform).
7060                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7061                            grant = GRANT_DENIED;
7062                        }
7063                    }
7064                }
7065
7066                switch (grant) {
7067                    case GRANT_INSTALL: {
7068                        // Grant an install permission.
7069                        if (permissionsState.grantInstallPermission(bp) !=
7070                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7071                            changedPermission = true;
7072                        }
7073                    } break;
7074
7075                    case GRANT_RUNTIME: {
7076                        // Grant previously granted runtime permissions.
7077                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7078                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7079                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7080                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7081                                    changedPermission = true;
7082                                }
7083                            }
7084                        }
7085                    } break;
7086
7087                    case GRANT_UPGRADE: {
7088                        // Grant runtime permissions for a previously held install permission.
7089                        permissionsState.revokeInstallPermission(bp);
7090                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7091                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7092                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7093                                changedPermission = true;
7094                            }
7095                        }
7096                    } break;
7097
7098                    default: {
7099                        if (packageOfInterest == null
7100                                || packageOfInterest.equals(pkg.packageName)) {
7101                            Slog.w(TAG, "Not granting permission " + perm
7102                                    + " to package " + pkg.packageName
7103                                    + " because it was previously installed without");
7104                        }
7105                    } break;
7106                }
7107            } else {
7108                if (permissionsState.revokeInstallPermission(bp) !=
7109                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7110                    changedPermission = true;
7111                    Slog.i(TAG, "Un-granting permission " + perm
7112                            + " from package " + pkg.packageName
7113                            + " (protectionLevel=" + bp.protectionLevel
7114                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7115                            + ")");
7116                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7117                    // Don't print warning for app op permissions, since it is fine for them
7118                    // not to be granted, there is a UI for the user to decide.
7119                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7120                        Slog.w(TAG, "Not granting permission " + perm
7121                                + " to package " + pkg.packageName
7122                                + " (protectionLevel=" + bp.protectionLevel
7123                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7124                                + ")");
7125                    }
7126                }
7127            }
7128        }
7129
7130        if ((changedPermission || replace) && !ps.permissionsFixed &&
7131                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7132            // This is the first that we have heard about this package, so the
7133            // permissions we have now selected are fixed until explicitly
7134            // changed.
7135            ps.permissionsFixed = true;
7136        }
7137    }
7138
7139    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7140        boolean allowed = false;
7141        final int NP = PackageParser.NEW_PERMISSIONS.length;
7142        for (int ip=0; ip<NP; ip++) {
7143            final PackageParser.NewPermissionInfo npi
7144                    = PackageParser.NEW_PERMISSIONS[ip];
7145            if (npi.name.equals(perm)
7146                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7147                allowed = true;
7148                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7149                        + pkg.packageName);
7150                break;
7151            }
7152        }
7153        return allowed;
7154    }
7155
7156    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7157            BasePermission bp, PermissionsState origPermissions) {
7158        boolean allowed;
7159        allowed = (compareSignatures(
7160                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7161                        == PackageManager.SIGNATURE_MATCH)
7162                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7163                        == PackageManager.SIGNATURE_MATCH);
7164        if (!allowed && (bp.protectionLevel
7165                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7166            if (isSystemApp(pkg)) {
7167                // For updated system applications, a system permission
7168                // is granted only if it had been defined by the original application.
7169                if (isUpdatedSystemApp(pkg)) {
7170                    final PackageSetting sysPs = mSettings
7171                            .getDisabledSystemPkgLPr(pkg.packageName);
7172                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7173                        // If the original was granted this permission, we take
7174                        // that grant decision as read and propagate it to the
7175                        // update.
7176                        if (sysPs.isPrivileged()) {
7177                            allowed = true;
7178                        }
7179                    } else {
7180                        // The system apk may have been updated with an older
7181                        // version of the one on the data partition, but which
7182                        // granted a new system permission that it didn't have
7183                        // before.  In this case we do want to allow the app to
7184                        // now get the new permission if the ancestral apk is
7185                        // privileged to get it.
7186                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7187                            for (int j=0;
7188                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7189                                if (perm.equals(
7190                                        sysPs.pkg.requestedPermissions.get(j))) {
7191                                    allowed = true;
7192                                    break;
7193                                }
7194                            }
7195                        }
7196                    }
7197                } else {
7198                    allowed = isPrivilegedApp(pkg);
7199                }
7200            }
7201        }
7202        if (!allowed && (bp.protectionLevel
7203                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7204            // For development permissions, a development permission
7205            // is granted only if it was already granted.
7206            allowed = origPermissions.hasInstallPermission(perm);
7207        }
7208        return allowed;
7209    }
7210
7211    final class ActivityIntentResolver
7212            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7213        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7214                boolean defaultOnly, int userId) {
7215            if (!sUserManager.exists(userId)) return null;
7216            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7217            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7218        }
7219
7220        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7221                int userId) {
7222            if (!sUserManager.exists(userId)) return null;
7223            mFlags = flags;
7224            return super.queryIntent(intent, resolvedType,
7225                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7226        }
7227
7228        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7229                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7230            if (!sUserManager.exists(userId)) return null;
7231            if (packageActivities == null) {
7232                return null;
7233            }
7234            mFlags = flags;
7235            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7236            final int N = packageActivities.size();
7237            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7238                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7239
7240            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7241            for (int i = 0; i < N; ++i) {
7242                intentFilters = packageActivities.get(i).intents;
7243                if (intentFilters != null && intentFilters.size() > 0) {
7244                    PackageParser.ActivityIntentInfo[] array =
7245                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7246                    intentFilters.toArray(array);
7247                    listCut.add(array);
7248                }
7249            }
7250            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7251        }
7252
7253        public final void addActivity(PackageParser.Activity a, String type) {
7254            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7255            mActivities.put(a.getComponentName(), a);
7256            if (DEBUG_SHOW_INFO)
7257                Log.v(
7258                TAG, "  " + type + " " +
7259                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7260            if (DEBUG_SHOW_INFO)
7261                Log.v(TAG, "    Class=" + a.info.name);
7262            final int NI = a.intents.size();
7263            for (int j=0; j<NI; j++) {
7264                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7265                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7266                    intent.setPriority(0);
7267                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7268                            + a.className + " with priority > 0, forcing to 0");
7269                }
7270                if (DEBUG_SHOW_INFO) {
7271                    Log.v(TAG, "    IntentFilter:");
7272                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7273                }
7274                if (!intent.debugCheck()) {
7275                    Log.w(TAG, "==> For Activity " + a.info.name);
7276                }
7277                addFilter(intent);
7278            }
7279        }
7280
7281        public final void removeActivity(PackageParser.Activity a, String type) {
7282            mActivities.remove(a.getComponentName());
7283            if (DEBUG_SHOW_INFO) {
7284                Log.v(TAG, "  " + type + " "
7285                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7286                                : a.info.name) + ":");
7287                Log.v(TAG, "    Class=" + a.info.name);
7288            }
7289            final int NI = a.intents.size();
7290            for (int j=0; j<NI; j++) {
7291                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7292                if (DEBUG_SHOW_INFO) {
7293                    Log.v(TAG, "    IntentFilter:");
7294                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7295                }
7296                removeFilter(intent);
7297            }
7298        }
7299
7300        @Override
7301        protected boolean allowFilterResult(
7302                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7303            ActivityInfo filterAi = filter.activity.info;
7304            for (int i=dest.size()-1; i>=0; i--) {
7305                ActivityInfo destAi = dest.get(i).activityInfo;
7306                if (destAi.name == filterAi.name
7307                        && destAi.packageName == filterAi.packageName) {
7308                    return false;
7309                }
7310            }
7311            return true;
7312        }
7313
7314        @Override
7315        protected ActivityIntentInfo[] newArray(int size) {
7316            return new ActivityIntentInfo[size];
7317        }
7318
7319        @Override
7320        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7321            if (!sUserManager.exists(userId)) return true;
7322            PackageParser.Package p = filter.activity.owner;
7323            if (p != null) {
7324                PackageSetting ps = (PackageSetting)p.mExtras;
7325                if (ps != null) {
7326                    // System apps are never considered stopped for purposes of
7327                    // filtering, because there may be no way for the user to
7328                    // actually re-launch them.
7329                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7330                            && ps.getStopped(userId);
7331                }
7332            }
7333            return false;
7334        }
7335
7336        @Override
7337        protected boolean isPackageForFilter(String packageName,
7338                PackageParser.ActivityIntentInfo info) {
7339            return packageName.equals(info.activity.owner.packageName);
7340        }
7341
7342        @Override
7343        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7344                int match, int userId) {
7345            if (!sUserManager.exists(userId)) return null;
7346            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7347                return null;
7348            }
7349            final PackageParser.Activity activity = info.activity;
7350            if (mSafeMode && (activity.info.applicationInfo.flags
7351                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7352                return null;
7353            }
7354            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7355            if (ps == null) {
7356                return null;
7357            }
7358            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7359                    ps.readUserState(userId), userId);
7360            if (ai == null) {
7361                return null;
7362            }
7363            final ResolveInfo res = new ResolveInfo();
7364            res.activityInfo = ai;
7365            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7366                res.filter = info;
7367            }
7368            res.priority = info.getPriority();
7369            res.preferredOrder = activity.owner.mPreferredOrder;
7370            //System.out.println("Result: " + res.activityInfo.className +
7371            //                   " = " + res.priority);
7372            res.match = match;
7373            res.isDefault = info.hasDefault;
7374            res.labelRes = info.labelRes;
7375            res.nonLocalizedLabel = info.nonLocalizedLabel;
7376            if (userNeedsBadging(userId)) {
7377                res.noResourceId = true;
7378            } else {
7379                res.icon = info.icon;
7380            }
7381            res.system = isSystemApp(res.activityInfo.applicationInfo);
7382            return res;
7383        }
7384
7385        @Override
7386        protected void sortResults(List<ResolveInfo> results) {
7387            Collections.sort(results, mResolvePrioritySorter);
7388        }
7389
7390        @Override
7391        protected void dumpFilter(PrintWriter out, String prefix,
7392                PackageParser.ActivityIntentInfo filter) {
7393            out.print(prefix); out.print(
7394                    Integer.toHexString(System.identityHashCode(filter.activity)));
7395                    out.print(' ');
7396                    filter.activity.printComponentShortName(out);
7397                    out.print(" filter ");
7398                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7399        }
7400
7401        @Override
7402        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7403            return filter.activity;
7404        }
7405
7406        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7407            PackageParser.Activity activity = (PackageParser.Activity)label;
7408            out.print(prefix); out.print(
7409                    Integer.toHexString(System.identityHashCode(activity)));
7410                    out.print(' ');
7411                    activity.printComponentShortName(out);
7412            if (count > 1) {
7413                out.print(" ("); out.print(count); out.print(" filters)");
7414            }
7415            out.println();
7416        }
7417
7418//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7419//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7420//            final List<ResolveInfo> retList = Lists.newArrayList();
7421//            while (i.hasNext()) {
7422//                final ResolveInfo resolveInfo = i.next();
7423//                if (isEnabledLP(resolveInfo.activityInfo)) {
7424//                    retList.add(resolveInfo);
7425//                }
7426//            }
7427//            return retList;
7428//        }
7429
7430        // Keys are String (activity class name), values are Activity.
7431        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7432                = new ArrayMap<ComponentName, PackageParser.Activity>();
7433        private int mFlags;
7434    }
7435
7436    private final class ServiceIntentResolver
7437            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7438        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7439                boolean defaultOnly, int userId) {
7440            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7441            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7442        }
7443
7444        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7445                int userId) {
7446            if (!sUserManager.exists(userId)) return null;
7447            mFlags = flags;
7448            return super.queryIntent(intent, resolvedType,
7449                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7450        }
7451
7452        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7453                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7454            if (!sUserManager.exists(userId)) return null;
7455            if (packageServices == null) {
7456                return null;
7457            }
7458            mFlags = flags;
7459            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7460            final int N = packageServices.size();
7461            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7462                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7463
7464            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7465            for (int i = 0; i < N; ++i) {
7466                intentFilters = packageServices.get(i).intents;
7467                if (intentFilters != null && intentFilters.size() > 0) {
7468                    PackageParser.ServiceIntentInfo[] array =
7469                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7470                    intentFilters.toArray(array);
7471                    listCut.add(array);
7472                }
7473            }
7474            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7475        }
7476
7477        public final void addService(PackageParser.Service s) {
7478            mServices.put(s.getComponentName(), s);
7479            if (DEBUG_SHOW_INFO) {
7480                Log.v(TAG, "  "
7481                        + (s.info.nonLocalizedLabel != null
7482                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7483                Log.v(TAG, "    Class=" + s.info.name);
7484            }
7485            final int NI = s.intents.size();
7486            int j;
7487            for (j=0; j<NI; j++) {
7488                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7489                if (DEBUG_SHOW_INFO) {
7490                    Log.v(TAG, "    IntentFilter:");
7491                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7492                }
7493                if (!intent.debugCheck()) {
7494                    Log.w(TAG, "==> For Service " + s.info.name);
7495                }
7496                addFilter(intent);
7497            }
7498        }
7499
7500        public final void removeService(PackageParser.Service s) {
7501            mServices.remove(s.getComponentName());
7502            if (DEBUG_SHOW_INFO) {
7503                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7504                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7505                Log.v(TAG, "    Class=" + s.info.name);
7506            }
7507            final int NI = s.intents.size();
7508            int j;
7509            for (j=0; j<NI; j++) {
7510                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7511                if (DEBUG_SHOW_INFO) {
7512                    Log.v(TAG, "    IntentFilter:");
7513                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7514                }
7515                removeFilter(intent);
7516            }
7517        }
7518
7519        @Override
7520        protected boolean allowFilterResult(
7521                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7522            ServiceInfo filterSi = filter.service.info;
7523            for (int i=dest.size()-1; i>=0; i--) {
7524                ServiceInfo destAi = dest.get(i).serviceInfo;
7525                if (destAi.name == filterSi.name
7526                        && destAi.packageName == filterSi.packageName) {
7527                    return false;
7528                }
7529            }
7530            return true;
7531        }
7532
7533        @Override
7534        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7535            return new PackageParser.ServiceIntentInfo[size];
7536        }
7537
7538        @Override
7539        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7540            if (!sUserManager.exists(userId)) return true;
7541            PackageParser.Package p = filter.service.owner;
7542            if (p != null) {
7543                PackageSetting ps = (PackageSetting)p.mExtras;
7544                if (ps != null) {
7545                    // System apps are never considered stopped for purposes of
7546                    // filtering, because there may be no way for the user to
7547                    // actually re-launch them.
7548                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7549                            && ps.getStopped(userId);
7550                }
7551            }
7552            return false;
7553        }
7554
7555        @Override
7556        protected boolean isPackageForFilter(String packageName,
7557                PackageParser.ServiceIntentInfo info) {
7558            return packageName.equals(info.service.owner.packageName);
7559        }
7560
7561        @Override
7562        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7563                int match, int userId) {
7564            if (!sUserManager.exists(userId)) return null;
7565            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7566            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7567                return null;
7568            }
7569            final PackageParser.Service service = info.service;
7570            if (mSafeMode && (service.info.applicationInfo.flags
7571                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7572                return null;
7573            }
7574            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7575            if (ps == null) {
7576                return null;
7577            }
7578            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7579                    ps.readUserState(userId), userId);
7580            if (si == null) {
7581                return null;
7582            }
7583            final ResolveInfo res = new ResolveInfo();
7584            res.serviceInfo = si;
7585            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7586                res.filter = filter;
7587            }
7588            res.priority = info.getPriority();
7589            res.preferredOrder = service.owner.mPreferredOrder;
7590            //System.out.println("Result: " + res.activityInfo.className +
7591            //                   " = " + res.priority);
7592            res.match = match;
7593            res.isDefault = info.hasDefault;
7594            res.labelRes = info.labelRes;
7595            res.nonLocalizedLabel = info.nonLocalizedLabel;
7596            res.icon = info.icon;
7597            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7598            return res;
7599        }
7600
7601        @Override
7602        protected void sortResults(List<ResolveInfo> results) {
7603            Collections.sort(results, mResolvePrioritySorter);
7604        }
7605
7606        @Override
7607        protected void dumpFilter(PrintWriter out, String prefix,
7608                PackageParser.ServiceIntentInfo filter) {
7609            out.print(prefix); out.print(
7610                    Integer.toHexString(System.identityHashCode(filter.service)));
7611                    out.print(' ');
7612                    filter.service.printComponentShortName(out);
7613                    out.print(" filter ");
7614                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7615        }
7616
7617        @Override
7618        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7619            return filter.service;
7620        }
7621
7622        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7623            PackageParser.Service service = (PackageParser.Service)label;
7624            out.print(prefix); out.print(
7625                    Integer.toHexString(System.identityHashCode(service)));
7626                    out.print(' ');
7627                    service.printComponentShortName(out);
7628            if (count > 1) {
7629                out.print(" ("); out.print(count); out.print(" filters)");
7630            }
7631            out.println();
7632        }
7633
7634//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7635//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7636//            final List<ResolveInfo> retList = Lists.newArrayList();
7637//            while (i.hasNext()) {
7638//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7639//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7640//                    retList.add(resolveInfo);
7641//                }
7642//            }
7643//            return retList;
7644//        }
7645
7646        // Keys are String (activity class name), values are Activity.
7647        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7648                = new ArrayMap<ComponentName, PackageParser.Service>();
7649        private int mFlags;
7650    };
7651
7652    private final class ProviderIntentResolver
7653            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7654        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7655                boolean defaultOnly, int userId) {
7656            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7657            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7658        }
7659
7660        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7661                int userId) {
7662            if (!sUserManager.exists(userId))
7663                return null;
7664            mFlags = flags;
7665            return super.queryIntent(intent, resolvedType,
7666                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7667        }
7668
7669        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7670                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7671            if (!sUserManager.exists(userId))
7672                return null;
7673            if (packageProviders == null) {
7674                return null;
7675            }
7676            mFlags = flags;
7677            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7678            final int N = packageProviders.size();
7679            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7680                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7681
7682            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7683            for (int i = 0; i < N; ++i) {
7684                intentFilters = packageProviders.get(i).intents;
7685                if (intentFilters != null && intentFilters.size() > 0) {
7686                    PackageParser.ProviderIntentInfo[] array =
7687                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7688                    intentFilters.toArray(array);
7689                    listCut.add(array);
7690                }
7691            }
7692            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7693        }
7694
7695        public final void addProvider(PackageParser.Provider p) {
7696            if (mProviders.containsKey(p.getComponentName())) {
7697                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7698                return;
7699            }
7700
7701            mProviders.put(p.getComponentName(), p);
7702            if (DEBUG_SHOW_INFO) {
7703                Log.v(TAG, "  "
7704                        + (p.info.nonLocalizedLabel != null
7705                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7706                Log.v(TAG, "    Class=" + p.info.name);
7707            }
7708            final int NI = p.intents.size();
7709            int j;
7710            for (j = 0; j < NI; j++) {
7711                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7712                if (DEBUG_SHOW_INFO) {
7713                    Log.v(TAG, "    IntentFilter:");
7714                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7715                }
7716                if (!intent.debugCheck()) {
7717                    Log.w(TAG, "==> For Provider " + p.info.name);
7718                }
7719                addFilter(intent);
7720            }
7721        }
7722
7723        public final void removeProvider(PackageParser.Provider p) {
7724            mProviders.remove(p.getComponentName());
7725            if (DEBUG_SHOW_INFO) {
7726                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7727                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7728                Log.v(TAG, "    Class=" + p.info.name);
7729            }
7730            final int NI = p.intents.size();
7731            int j;
7732            for (j = 0; j < NI; j++) {
7733                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7734                if (DEBUG_SHOW_INFO) {
7735                    Log.v(TAG, "    IntentFilter:");
7736                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7737                }
7738                removeFilter(intent);
7739            }
7740        }
7741
7742        @Override
7743        protected boolean allowFilterResult(
7744                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7745            ProviderInfo filterPi = filter.provider.info;
7746            for (int i = dest.size() - 1; i >= 0; i--) {
7747                ProviderInfo destPi = dest.get(i).providerInfo;
7748                if (destPi.name == filterPi.name
7749                        && destPi.packageName == filterPi.packageName) {
7750                    return false;
7751                }
7752            }
7753            return true;
7754        }
7755
7756        @Override
7757        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7758            return new PackageParser.ProviderIntentInfo[size];
7759        }
7760
7761        @Override
7762        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7763            if (!sUserManager.exists(userId))
7764                return true;
7765            PackageParser.Package p = filter.provider.owner;
7766            if (p != null) {
7767                PackageSetting ps = (PackageSetting) p.mExtras;
7768                if (ps != null) {
7769                    // System apps are never considered stopped for purposes of
7770                    // filtering, because there may be no way for the user to
7771                    // actually re-launch them.
7772                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7773                            && ps.getStopped(userId);
7774                }
7775            }
7776            return false;
7777        }
7778
7779        @Override
7780        protected boolean isPackageForFilter(String packageName,
7781                PackageParser.ProviderIntentInfo info) {
7782            return packageName.equals(info.provider.owner.packageName);
7783        }
7784
7785        @Override
7786        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7787                int match, int userId) {
7788            if (!sUserManager.exists(userId))
7789                return null;
7790            final PackageParser.ProviderIntentInfo info = filter;
7791            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7792                return null;
7793            }
7794            final PackageParser.Provider provider = info.provider;
7795            if (mSafeMode && (provider.info.applicationInfo.flags
7796                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7797                return null;
7798            }
7799            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7800            if (ps == null) {
7801                return null;
7802            }
7803            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7804                    ps.readUserState(userId), userId);
7805            if (pi == null) {
7806                return null;
7807            }
7808            final ResolveInfo res = new ResolveInfo();
7809            res.providerInfo = pi;
7810            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7811                res.filter = filter;
7812            }
7813            res.priority = info.getPriority();
7814            res.preferredOrder = provider.owner.mPreferredOrder;
7815            res.match = match;
7816            res.isDefault = info.hasDefault;
7817            res.labelRes = info.labelRes;
7818            res.nonLocalizedLabel = info.nonLocalizedLabel;
7819            res.icon = info.icon;
7820            res.system = isSystemApp(res.providerInfo.applicationInfo);
7821            return res;
7822        }
7823
7824        @Override
7825        protected void sortResults(List<ResolveInfo> results) {
7826            Collections.sort(results, mResolvePrioritySorter);
7827        }
7828
7829        @Override
7830        protected void dumpFilter(PrintWriter out, String prefix,
7831                PackageParser.ProviderIntentInfo filter) {
7832            out.print(prefix);
7833            out.print(
7834                    Integer.toHexString(System.identityHashCode(filter.provider)));
7835            out.print(' ');
7836            filter.provider.printComponentShortName(out);
7837            out.print(" filter ");
7838            out.println(Integer.toHexString(System.identityHashCode(filter)));
7839        }
7840
7841        @Override
7842        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7843            return filter.provider;
7844        }
7845
7846        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7847            PackageParser.Provider provider = (PackageParser.Provider)label;
7848            out.print(prefix); out.print(
7849                    Integer.toHexString(System.identityHashCode(provider)));
7850                    out.print(' ');
7851                    provider.printComponentShortName(out);
7852            if (count > 1) {
7853                out.print(" ("); out.print(count); out.print(" filters)");
7854            }
7855            out.println();
7856        }
7857
7858        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7859                = new ArrayMap<ComponentName, PackageParser.Provider>();
7860        private int mFlags;
7861    };
7862
7863    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7864            new Comparator<ResolveInfo>() {
7865        public int compare(ResolveInfo r1, ResolveInfo r2) {
7866            int v1 = r1.priority;
7867            int v2 = r2.priority;
7868            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7869            if (v1 != v2) {
7870                return (v1 > v2) ? -1 : 1;
7871            }
7872            v1 = r1.preferredOrder;
7873            v2 = r2.preferredOrder;
7874            if (v1 != v2) {
7875                return (v1 > v2) ? -1 : 1;
7876            }
7877            if (r1.isDefault != r2.isDefault) {
7878                return r1.isDefault ? -1 : 1;
7879            }
7880            v1 = r1.match;
7881            v2 = r2.match;
7882            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7883            if (v1 != v2) {
7884                return (v1 > v2) ? -1 : 1;
7885            }
7886            if (r1.system != r2.system) {
7887                return r1.system ? -1 : 1;
7888            }
7889            return 0;
7890        }
7891    };
7892
7893    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7894            new Comparator<ProviderInfo>() {
7895        public int compare(ProviderInfo p1, ProviderInfo p2) {
7896            final int v1 = p1.initOrder;
7897            final int v2 = p2.initOrder;
7898            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7899        }
7900    };
7901
7902    static final void sendPackageBroadcast(String action, String pkg,
7903            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7904            int[] userIds) {
7905        IActivityManager am = ActivityManagerNative.getDefault();
7906        if (am != null) {
7907            try {
7908                if (userIds == null) {
7909                    userIds = am.getRunningUserIds();
7910                }
7911                for (int id : userIds) {
7912                    final Intent intent = new Intent(action,
7913                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7914                    if (extras != null) {
7915                        intent.putExtras(extras);
7916                    }
7917                    if (targetPkg != null) {
7918                        intent.setPackage(targetPkg);
7919                    }
7920                    // Modify the UID when posting to other users
7921                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7922                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7923                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7924                        intent.putExtra(Intent.EXTRA_UID, uid);
7925                    }
7926                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7927                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7928                    if (DEBUG_BROADCASTS) {
7929                        RuntimeException here = new RuntimeException("here");
7930                        here.fillInStackTrace();
7931                        Slog.d(TAG, "Sending to user " + id + ": "
7932                                + intent.toShortString(false, true, false, false)
7933                                + " " + intent.getExtras(), here);
7934                    }
7935                    am.broadcastIntent(null, intent, null, finishedReceiver,
7936                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7937                            finishedReceiver != null, false, id);
7938                }
7939            } catch (RemoteException ex) {
7940            }
7941        }
7942    }
7943
7944    /**
7945     * Check if the external storage media is available. This is true if there
7946     * is a mounted external storage medium or if the external storage is
7947     * emulated.
7948     */
7949    private boolean isExternalMediaAvailable() {
7950        return mMediaMounted || Environment.isExternalStorageEmulated();
7951    }
7952
7953    @Override
7954    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7955        // writer
7956        synchronized (mPackages) {
7957            if (!isExternalMediaAvailable()) {
7958                // If the external storage is no longer mounted at this point,
7959                // the caller may not have been able to delete all of this
7960                // packages files and can not delete any more.  Bail.
7961                return null;
7962            }
7963            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7964            if (lastPackage != null) {
7965                pkgs.remove(lastPackage);
7966            }
7967            if (pkgs.size() > 0) {
7968                return pkgs.get(0);
7969            }
7970        }
7971        return null;
7972    }
7973
7974    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7975        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7976                userId, andCode ? 1 : 0, packageName);
7977        if (mSystemReady) {
7978            msg.sendToTarget();
7979        } else {
7980            if (mPostSystemReadyMessages == null) {
7981                mPostSystemReadyMessages = new ArrayList<>();
7982            }
7983            mPostSystemReadyMessages.add(msg);
7984        }
7985    }
7986
7987    void startCleaningPackages() {
7988        // reader
7989        synchronized (mPackages) {
7990            if (!isExternalMediaAvailable()) {
7991                return;
7992            }
7993            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7994                return;
7995            }
7996        }
7997        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7998        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7999        IActivityManager am = ActivityManagerNative.getDefault();
8000        if (am != null) {
8001            try {
8002                am.startService(null, intent, null, UserHandle.USER_OWNER);
8003            } catch (RemoteException e) {
8004            }
8005        }
8006    }
8007
8008    @Override
8009    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8010            int installFlags, String installerPackageName, VerificationParams verificationParams,
8011            String packageAbiOverride) {
8012        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
8013                packageAbiOverride, UserHandle.getCallingUserId());
8014    }
8015
8016    @Override
8017    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8018            int installFlags, String installerPackageName, VerificationParams verificationParams,
8019            String packageAbiOverride, int userId) {
8020        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8021
8022        final int callingUid = Binder.getCallingUid();
8023        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8024
8025        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8026            try {
8027                if (observer != null) {
8028                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8029                }
8030            } catch (RemoteException re) {
8031            }
8032            return;
8033        }
8034
8035        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8036            installFlags |= PackageManager.INSTALL_FROM_ADB;
8037
8038        } else {
8039            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8040            // about installerPackageName.
8041
8042            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8043            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8044        }
8045
8046        UserHandle user;
8047        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8048            user = UserHandle.ALL;
8049        } else {
8050            user = new UserHandle(userId);
8051        }
8052
8053        verificationParams.setInstallerUid(callingUid);
8054
8055        final File originFile = new File(originPath);
8056        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8057
8058        final Message msg = mHandler.obtainMessage(INIT_COPY);
8059        msg.obj = new InstallParams(origin, observer, installFlags,
8060                installerPackageName, verificationParams, user, packageAbiOverride);
8061        mHandler.sendMessage(msg);
8062    }
8063
8064    void installStage(String packageName, File stagedDir, String stagedCid,
8065            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8066            String installerPackageName, int installerUid, UserHandle user) {
8067        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8068                params.referrerUri, installerUid, null);
8069
8070        final OriginInfo origin;
8071        if (stagedDir != null) {
8072            origin = OriginInfo.fromStagedFile(stagedDir);
8073        } else {
8074            origin = OriginInfo.fromStagedContainer(stagedCid);
8075        }
8076
8077        final Message msg = mHandler.obtainMessage(INIT_COPY);
8078        msg.obj = new InstallParams(origin, observer, params.installFlags,
8079                installerPackageName, verifParams, user, params.abiOverride);
8080        mHandler.sendMessage(msg);
8081    }
8082
8083    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8084        Bundle extras = new Bundle(1);
8085        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8086
8087        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8088                packageName, extras, null, null, new int[] {userId});
8089        try {
8090            IActivityManager am = ActivityManagerNative.getDefault();
8091            final boolean isSystem =
8092                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8093            if (isSystem && am.isUserRunning(userId, false)) {
8094                // The just-installed/enabled app is bundled on the system, so presumed
8095                // to be able to run automatically without needing an explicit launch.
8096                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8097                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8098                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8099                        .setPackage(packageName);
8100                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8101                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8102            }
8103        } catch (RemoteException e) {
8104            // shouldn't happen
8105            Slog.w(TAG, "Unable to bootstrap installed package", e);
8106        }
8107    }
8108
8109    @Override
8110    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8111            int userId) {
8112        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8113        PackageSetting pkgSetting;
8114        final int uid = Binder.getCallingUid();
8115        enforceCrossUserPermission(uid, userId, true, true,
8116                "setApplicationHiddenSetting for user " + userId);
8117
8118        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8119            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8120            return false;
8121        }
8122
8123        long callingId = Binder.clearCallingIdentity();
8124        try {
8125            boolean sendAdded = false;
8126            boolean sendRemoved = false;
8127            // writer
8128            synchronized (mPackages) {
8129                pkgSetting = mSettings.mPackages.get(packageName);
8130                if (pkgSetting == null) {
8131                    return false;
8132                }
8133                if (pkgSetting.getHidden(userId) != hidden) {
8134                    pkgSetting.setHidden(hidden, userId);
8135                    mSettings.writePackageRestrictionsLPr(userId);
8136                    if (hidden) {
8137                        sendRemoved = true;
8138                    } else {
8139                        sendAdded = true;
8140                    }
8141                }
8142            }
8143            if (sendAdded) {
8144                sendPackageAddedForUser(packageName, pkgSetting, userId);
8145                return true;
8146            }
8147            if (sendRemoved) {
8148                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8149                        "hiding pkg");
8150                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8151            }
8152        } finally {
8153            Binder.restoreCallingIdentity(callingId);
8154        }
8155        return false;
8156    }
8157
8158    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8159            int userId) {
8160        final PackageRemovedInfo info = new PackageRemovedInfo();
8161        info.removedPackage = packageName;
8162        info.removedUsers = new int[] {userId};
8163        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8164        info.sendBroadcast(false, false, false);
8165    }
8166
8167    /**
8168     * Returns true if application is not found or there was an error. Otherwise it returns
8169     * the hidden state of the package for the given user.
8170     */
8171    @Override
8172    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8173        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8174        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8175                false, "getApplicationHidden for user " + userId);
8176        PackageSetting pkgSetting;
8177        long callingId = Binder.clearCallingIdentity();
8178        try {
8179            // writer
8180            synchronized (mPackages) {
8181                pkgSetting = mSettings.mPackages.get(packageName);
8182                if (pkgSetting == null) {
8183                    return true;
8184                }
8185                return pkgSetting.getHidden(userId);
8186            }
8187        } finally {
8188            Binder.restoreCallingIdentity(callingId);
8189        }
8190    }
8191
8192    /**
8193     * @hide
8194     */
8195    @Override
8196    public int installExistingPackageAsUser(String packageName, int userId) {
8197        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8198                null);
8199        PackageSetting pkgSetting;
8200        final int uid = Binder.getCallingUid();
8201        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8202                + userId);
8203        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8204            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8205        }
8206
8207        long callingId = Binder.clearCallingIdentity();
8208        try {
8209            boolean sendAdded = false;
8210            Bundle extras = new Bundle(1);
8211
8212            // writer
8213            synchronized (mPackages) {
8214                pkgSetting = mSettings.mPackages.get(packageName);
8215                if (pkgSetting == null) {
8216                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8217                }
8218                if (!pkgSetting.getInstalled(userId)) {
8219                    pkgSetting.setInstalled(true, userId);
8220                    pkgSetting.setHidden(false, userId);
8221                    mSettings.writePackageRestrictionsLPr(userId);
8222                    sendAdded = true;
8223                }
8224            }
8225
8226            if (sendAdded) {
8227                sendPackageAddedForUser(packageName, pkgSetting, userId);
8228            }
8229        } finally {
8230            Binder.restoreCallingIdentity(callingId);
8231        }
8232
8233        return PackageManager.INSTALL_SUCCEEDED;
8234    }
8235
8236    boolean isUserRestricted(int userId, String restrictionKey) {
8237        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8238        if (restrictions.getBoolean(restrictionKey, false)) {
8239            Log.w(TAG, "User is restricted: " + restrictionKey);
8240            return true;
8241        }
8242        return false;
8243    }
8244
8245    @Override
8246    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8247        mContext.enforceCallingOrSelfPermission(
8248                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8249                "Only package verification agents can verify applications");
8250
8251        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8252        final PackageVerificationResponse response = new PackageVerificationResponse(
8253                verificationCode, Binder.getCallingUid());
8254        msg.arg1 = id;
8255        msg.obj = response;
8256        mHandler.sendMessage(msg);
8257    }
8258
8259    @Override
8260    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8261            long millisecondsToDelay) {
8262        mContext.enforceCallingOrSelfPermission(
8263                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8264                "Only package verification agents can extend verification timeouts");
8265
8266        final PackageVerificationState state = mPendingVerification.get(id);
8267        final PackageVerificationResponse response = new PackageVerificationResponse(
8268                verificationCodeAtTimeout, Binder.getCallingUid());
8269
8270        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8271            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8272        }
8273        if (millisecondsToDelay < 0) {
8274            millisecondsToDelay = 0;
8275        }
8276        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8277                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8278            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8279        }
8280
8281        if ((state != null) && !state.timeoutExtended()) {
8282            state.extendTimeout();
8283
8284            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8285            msg.arg1 = id;
8286            msg.obj = response;
8287            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8288        }
8289    }
8290
8291    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8292            int verificationCode, UserHandle user) {
8293        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8294        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8295        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8296        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8297        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8298
8299        mContext.sendBroadcastAsUser(intent, user,
8300                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8301    }
8302
8303    private ComponentName matchComponentForVerifier(String packageName,
8304            List<ResolveInfo> receivers) {
8305        ActivityInfo targetReceiver = null;
8306
8307        final int NR = receivers.size();
8308        for (int i = 0; i < NR; i++) {
8309            final ResolveInfo info = receivers.get(i);
8310            if (info.activityInfo == null) {
8311                continue;
8312            }
8313
8314            if (packageName.equals(info.activityInfo.packageName)) {
8315                targetReceiver = info.activityInfo;
8316                break;
8317            }
8318        }
8319
8320        if (targetReceiver == null) {
8321            return null;
8322        }
8323
8324        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8325    }
8326
8327    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8328            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8329        if (pkgInfo.verifiers.length == 0) {
8330            return null;
8331        }
8332
8333        final int N = pkgInfo.verifiers.length;
8334        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8335        for (int i = 0; i < N; i++) {
8336            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8337
8338            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8339                    receivers);
8340            if (comp == null) {
8341                continue;
8342            }
8343
8344            final int verifierUid = getUidForVerifier(verifierInfo);
8345            if (verifierUid == -1) {
8346                continue;
8347            }
8348
8349            if (DEBUG_VERIFY) {
8350                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8351                        + " with the correct signature");
8352            }
8353            sufficientVerifiers.add(comp);
8354            verificationState.addSufficientVerifier(verifierUid);
8355        }
8356
8357        return sufficientVerifiers;
8358    }
8359
8360    private int getUidForVerifier(VerifierInfo verifierInfo) {
8361        synchronized (mPackages) {
8362            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8363            if (pkg == null) {
8364                return -1;
8365            } else if (pkg.mSignatures.length != 1) {
8366                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8367                        + " has more than one signature; ignoring");
8368                return -1;
8369            }
8370
8371            /*
8372             * If the public key of the package's signature does not match
8373             * our expected public key, then this is a different package and
8374             * we should skip.
8375             */
8376
8377            final byte[] expectedPublicKey;
8378            try {
8379                final Signature verifierSig = pkg.mSignatures[0];
8380                final PublicKey publicKey = verifierSig.getPublicKey();
8381                expectedPublicKey = publicKey.getEncoded();
8382            } catch (CertificateException e) {
8383                return -1;
8384            }
8385
8386            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8387
8388            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8389                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8390                        + " does not have the expected public key; ignoring");
8391                return -1;
8392            }
8393
8394            return pkg.applicationInfo.uid;
8395        }
8396    }
8397
8398    @Override
8399    public void finishPackageInstall(int token) {
8400        enforceSystemOrRoot("Only the system is allowed to finish installs");
8401
8402        if (DEBUG_INSTALL) {
8403            Slog.v(TAG, "BM finishing package install for " + token);
8404        }
8405
8406        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8407        mHandler.sendMessage(msg);
8408    }
8409
8410    /**
8411     * Get the verification agent timeout.
8412     *
8413     * @return verification timeout in milliseconds
8414     */
8415    private long getVerificationTimeout() {
8416        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8417                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8418                DEFAULT_VERIFICATION_TIMEOUT);
8419    }
8420
8421    /**
8422     * Get the default verification agent response code.
8423     *
8424     * @return default verification response code
8425     */
8426    private int getDefaultVerificationResponse() {
8427        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8428                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8429                DEFAULT_VERIFICATION_RESPONSE);
8430    }
8431
8432    /**
8433     * Check whether or not package verification has been enabled.
8434     *
8435     * @return true if verification should be performed
8436     */
8437    private boolean isVerificationEnabled(int userId, int installFlags) {
8438        if (!DEFAULT_VERIFY_ENABLE) {
8439            return false;
8440        }
8441
8442        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8443
8444        // Check if installing from ADB
8445        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8446            // Do not run verification in a test harness environment
8447            if (ActivityManager.isRunningInTestHarness()) {
8448                return false;
8449            }
8450            if (ensureVerifyAppsEnabled) {
8451                return true;
8452            }
8453            // Check if the developer does not want package verification for ADB installs
8454            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8455                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8456                return false;
8457            }
8458        }
8459
8460        if (ensureVerifyAppsEnabled) {
8461            return true;
8462        }
8463
8464        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8465                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8466    }
8467
8468    /**
8469     * Get the "allow unknown sources" setting.
8470     *
8471     * @return the current "allow unknown sources" setting
8472     */
8473    private int getUnknownSourcesSettings() {
8474        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8475                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8476                -1);
8477    }
8478
8479    @Override
8480    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8481        final int uid = Binder.getCallingUid();
8482        // writer
8483        synchronized (mPackages) {
8484            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8485            if (targetPackageSetting == null) {
8486                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8487            }
8488
8489            PackageSetting installerPackageSetting;
8490            if (installerPackageName != null) {
8491                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8492                if (installerPackageSetting == null) {
8493                    throw new IllegalArgumentException("Unknown installer package: "
8494                            + installerPackageName);
8495                }
8496            } else {
8497                installerPackageSetting = null;
8498            }
8499
8500            Signature[] callerSignature;
8501            Object obj = mSettings.getUserIdLPr(uid);
8502            if (obj != null) {
8503                if (obj instanceof SharedUserSetting) {
8504                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8505                } else if (obj instanceof PackageSetting) {
8506                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8507                } else {
8508                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8509                }
8510            } else {
8511                throw new SecurityException("Unknown calling uid " + uid);
8512            }
8513
8514            // Verify: can't set installerPackageName to a package that is
8515            // not signed with the same cert as the caller.
8516            if (installerPackageSetting != null) {
8517                if (compareSignatures(callerSignature,
8518                        installerPackageSetting.signatures.mSignatures)
8519                        != PackageManager.SIGNATURE_MATCH) {
8520                    throw new SecurityException(
8521                            "Caller does not have same cert as new installer package "
8522                            + installerPackageName);
8523                }
8524            }
8525
8526            // Verify: if target already has an installer package, it must
8527            // be signed with the same cert as the caller.
8528            if (targetPackageSetting.installerPackageName != null) {
8529                PackageSetting setting = mSettings.mPackages.get(
8530                        targetPackageSetting.installerPackageName);
8531                // If the currently set package isn't valid, then it's always
8532                // okay to change it.
8533                if (setting != null) {
8534                    if (compareSignatures(callerSignature,
8535                            setting.signatures.mSignatures)
8536                            != PackageManager.SIGNATURE_MATCH) {
8537                        throw new SecurityException(
8538                                "Caller does not have same cert as old installer package "
8539                                + targetPackageSetting.installerPackageName);
8540                    }
8541                }
8542            }
8543
8544            // Okay!
8545            targetPackageSetting.installerPackageName = installerPackageName;
8546            scheduleWriteSettingsLocked();
8547        }
8548    }
8549
8550    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8551        // Queue up an async operation since the package installation may take a little while.
8552        mHandler.post(new Runnable() {
8553            public void run() {
8554                mHandler.removeCallbacks(this);
8555                 // Result object to be returned
8556                PackageInstalledInfo res = new PackageInstalledInfo();
8557                res.returnCode = currentStatus;
8558                res.uid = -1;
8559                res.pkg = null;
8560                res.removedInfo = new PackageRemovedInfo();
8561                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8562                    args.doPreInstall(res.returnCode);
8563                    synchronized (mInstallLock) {
8564                        installPackageLI(args, res);
8565                    }
8566                    args.doPostInstall(res.returnCode, res.uid);
8567                }
8568
8569                // A restore should be performed at this point if (a) the install
8570                // succeeded, (b) the operation is not an update, and (c) the new
8571                // package has not opted out of backup participation.
8572                final boolean update = res.removedInfo.removedPackage != null;
8573                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8574                boolean doRestore = !update
8575                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8576
8577                // Set up the post-install work request bookkeeping.  This will be used
8578                // and cleaned up by the post-install event handling regardless of whether
8579                // there's a restore pass performed.  Token values are >= 1.
8580                int token;
8581                if (mNextInstallToken < 0) mNextInstallToken = 1;
8582                token = mNextInstallToken++;
8583
8584                PostInstallData data = new PostInstallData(args, res);
8585                mRunningInstalls.put(token, data);
8586                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8587
8588                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8589                    // Pass responsibility to the Backup Manager.  It will perform a
8590                    // restore if appropriate, then pass responsibility back to the
8591                    // Package Manager to run the post-install observer callbacks
8592                    // and broadcasts.
8593                    IBackupManager bm = IBackupManager.Stub.asInterface(
8594                            ServiceManager.getService(Context.BACKUP_SERVICE));
8595                    if (bm != null) {
8596                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8597                                + " to BM for possible restore");
8598                        try {
8599                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
8600                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8601                            } else {
8602                                doRestore = false;
8603                            }
8604                        } catch (RemoteException e) {
8605                            // can't happen; the backup manager is local
8606                        } catch (Exception e) {
8607                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8608                            doRestore = false;
8609                        }
8610                    } else {
8611                        Slog.e(TAG, "Backup Manager not found!");
8612                        doRestore = false;
8613                    }
8614                }
8615
8616                if (!doRestore) {
8617                    // No restore possible, or the Backup Manager was mysteriously not
8618                    // available -- just fire the post-install work request directly.
8619                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8620                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8621                    mHandler.sendMessage(msg);
8622                }
8623            }
8624        });
8625    }
8626
8627    private abstract class HandlerParams {
8628        private static final int MAX_RETRIES = 4;
8629
8630        /**
8631         * Number of times startCopy() has been attempted and had a non-fatal
8632         * error.
8633         */
8634        private int mRetries = 0;
8635
8636        /** User handle for the user requesting the information or installation. */
8637        private final UserHandle mUser;
8638
8639        HandlerParams(UserHandle user) {
8640            mUser = user;
8641        }
8642
8643        UserHandle getUser() {
8644            return mUser;
8645        }
8646
8647        final boolean startCopy() {
8648            boolean res;
8649            try {
8650                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8651
8652                if (++mRetries > MAX_RETRIES) {
8653                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8654                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8655                    handleServiceError();
8656                    return false;
8657                } else {
8658                    handleStartCopy();
8659                    res = true;
8660                }
8661            } catch (RemoteException e) {
8662                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8663                mHandler.sendEmptyMessage(MCS_RECONNECT);
8664                res = false;
8665            }
8666            handleReturnCode();
8667            return res;
8668        }
8669
8670        final void serviceError() {
8671            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8672            handleServiceError();
8673            handleReturnCode();
8674        }
8675
8676        abstract void handleStartCopy() throws RemoteException;
8677        abstract void handleServiceError();
8678        abstract void handleReturnCode();
8679    }
8680
8681    class MeasureParams extends HandlerParams {
8682        private final PackageStats mStats;
8683        private boolean mSuccess;
8684
8685        private final IPackageStatsObserver mObserver;
8686
8687        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8688            super(new UserHandle(stats.userHandle));
8689            mObserver = observer;
8690            mStats = stats;
8691        }
8692
8693        @Override
8694        public String toString() {
8695            return "MeasureParams{"
8696                + Integer.toHexString(System.identityHashCode(this))
8697                + " " + mStats.packageName + "}";
8698        }
8699
8700        @Override
8701        void handleStartCopy() throws RemoteException {
8702            synchronized (mInstallLock) {
8703                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8704            }
8705
8706            if (mSuccess) {
8707                final boolean mounted;
8708                if (Environment.isExternalStorageEmulated()) {
8709                    mounted = true;
8710                } else {
8711                    final String status = Environment.getExternalStorageState();
8712                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8713                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8714                }
8715
8716                if (mounted) {
8717                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8718
8719                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8720                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8721
8722                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8723                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8724
8725                    // Always subtract cache size, since it's a subdirectory
8726                    mStats.externalDataSize -= mStats.externalCacheSize;
8727
8728                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8729                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8730
8731                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8732                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8733                }
8734            }
8735        }
8736
8737        @Override
8738        void handleReturnCode() {
8739            if (mObserver != null) {
8740                try {
8741                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8742                } catch (RemoteException e) {
8743                    Slog.i(TAG, "Observer no longer exists.");
8744                }
8745            }
8746        }
8747
8748        @Override
8749        void handleServiceError() {
8750            Slog.e(TAG, "Could not measure application " + mStats.packageName
8751                            + " external storage");
8752        }
8753    }
8754
8755    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8756            throws RemoteException {
8757        long result = 0;
8758        for (File path : paths) {
8759            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8760        }
8761        return result;
8762    }
8763
8764    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8765        for (File path : paths) {
8766            try {
8767                mcs.clearDirectory(path.getAbsolutePath());
8768            } catch (RemoteException e) {
8769            }
8770        }
8771    }
8772
8773    static class OriginInfo {
8774        /**
8775         * Location where install is coming from, before it has been
8776         * copied/renamed into place. This could be a single monolithic APK
8777         * file, or a cluster directory. This location may be untrusted.
8778         */
8779        final File file;
8780        final String cid;
8781
8782        /**
8783         * Flag indicating that {@link #file} or {@link #cid} has already been
8784         * staged, meaning downstream users don't need to defensively copy the
8785         * contents.
8786         */
8787        final boolean staged;
8788
8789        /**
8790         * Flag indicating that {@link #file} or {@link #cid} is an already
8791         * installed app that is being moved.
8792         */
8793        final boolean existing;
8794
8795        final String resolvedPath;
8796        final File resolvedFile;
8797
8798        static OriginInfo fromNothing() {
8799            return new OriginInfo(null, null, false, false);
8800        }
8801
8802        static OriginInfo fromUntrustedFile(File file) {
8803            return new OriginInfo(file, null, false, false);
8804        }
8805
8806        static OriginInfo fromExistingFile(File file) {
8807            return new OriginInfo(file, null, false, true);
8808        }
8809
8810        static OriginInfo fromStagedFile(File file) {
8811            return new OriginInfo(file, null, true, false);
8812        }
8813
8814        static OriginInfo fromStagedContainer(String cid) {
8815            return new OriginInfo(null, cid, true, false);
8816        }
8817
8818        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8819            this.file = file;
8820            this.cid = cid;
8821            this.staged = staged;
8822            this.existing = existing;
8823
8824            if (cid != null) {
8825                resolvedPath = PackageHelper.getSdDir(cid);
8826                resolvedFile = new File(resolvedPath);
8827            } else if (file != null) {
8828                resolvedPath = file.getAbsolutePath();
8829                resolvedFile = file;
8830            } else {
8831                resolvedPath = null;
8832                resolvedFile = null;
8833            }
8834        }
8835    }
8836
8837    class InstallParams extends HandlerParams {
8838        final OriginInfo origin;
8839        final IPackageInstallObserver2 observer;
8840        int installFlags;
8841        final String installerPackageName;
8842        final VerificationParams verificationParams;
8843        private InstallArgs mArgs;
8844        private int mRet;
8845        final String packageAbiOverride;
8846
8847        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8848                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8849                String packageAbiOverride) {
8850            super(user);
8851            this.origin = origin;
8852            this.observer = observer;
8853            this.installFlags = installFlags;
8854            this.installerPackageName = installerPackageName;
8855            this.verificationParams = verificationParams;
8856            this.packageAbiOverride = packageAbiOverride;
8857        }
8858
8859        @Override
8860        public String toString() {
8861            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8862                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8863        }
8864
8865        public ManifestDigest getManifestDigest() {
8866            if (verificationParams == null) {
8867                return null;
8868            }
8869            return verificationParams.getManifestDigest();
8870        }
8871
8872        private int installLocationPolicy(PackageInfoLite pkgLite) {
8873            String packageName = pkgLite.packageName;
8874            int installLocation = pkgLite.installLocation;
8875            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8876            // reader
8877            synchronized (mPackages) {
8878                PackageParser.Package pkg = mPackages.get(packageName);
8879                if (pkg != null) {
8880                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8881                        // Check for downgrading.
8882                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8883                            try {
8884                                checkDowngrade(pkg, pkgLite);
8885                            } catch (PackageManagerException e) {
8886                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8887                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8888                            }
8889                        }
8890                        // Check for updated system application.
8891                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8892                            if (onSd) {
8893                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8894                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8895                            }
8896                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8897                        } else {
8898                            if (onSd) {
8899                                // Install flag overrides everything.
8900                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8901                            }
8902                            // If current upgrade specifies particular preference
8903                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8904                                // Application explicitly specified internal.
8905                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8906                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8907                                // App explictly prefers external. Let policy decide
8908                            } else {
8909                                // Prefer previous location
8910                                if (isExternal(pkg)) {
8911                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8912                                }
8913                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8914                            }
8915                        }
8916                    } else {
8917                        // Invalid install. Return error code
8918                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8919                    }
8920                }
8921            }
8922            // All the special cases have been taken care of.
8923            // Return result based on recommended install location.
8924            if (onSd) {
8925                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8926            }
8927            return pkgLite.recommendedInstallLocation;
8928        }
8929
8930        /*
8931         * Invoke remote method to get package information and install
8932         * location values. Override install location based on default
8933         * policy if needed and then create install arguments based
8934         * on the install location.
8935         */
8936        public void handleStartCopy() throws RemoteException {
8937            int ret = PackageManager.INSTALL_SUCCEEDED;
8938
8939            // If we're already staged, we've firmly committed to an install location
8940            if (origin.staged) {
8941                if (origin.file != null) {
8942                    installFlags |= PackageManager.INSTALL_INTERNAL;
8943                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8944                } else if (origin.cid != null) {
8945                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8946                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8947                } else {
8948                    throw new IllegalStateException("Invalid stage location");
8949                }
8950            }
8951
8952            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8953            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8954
8955            PackageInfoLite pkgLite = null;
8956
8957            if (onInt && onSd) {
8958                // Check if both bits are set.
8959                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8960                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8961            } else {
8962                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8963                        packageAbiOverride);
8964
8965                /*
8966                 * If we have too little free space, try to free cache
8967                 * before giving up.
8968                 */
8969                if (!origin.staged && pkgLite.recommendedInstallLocation
8970                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8971                    // TODO: focus freeing disk space on the target device
8972                    final StorageManager storage = StorageManager.from(mContext);
8973                    final long lowThreshold = storage.getStorageLowBytes(
8974                            Environment.getDataDirectory());
8975
8976                    final long sizeBytes = mContainerService.calculateInstalledSize(
8977                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8978
8979                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8980                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8981                                installFlags, packageAbiOverride);
8982                    }
8983
8984                    /*
8985                     * The cache free must have deleted the file we
8986                     * downloaded to install.
8987                     *
8988                     * TODO: fix the "freeCache" call to not delete
8989                     *       the file we care about.
8990                     */
8991                    if (pkgLite.recommendedInstallLocation
8992                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8993                        pkgLite.recommendedInstallLocation
8994                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8995                    }
8996                }
8997            }
8998
8999            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9000                int loc = pkgLite.recommendedInstallLocation;
9001                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9002                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9003                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9004                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9005                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9006                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9007                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9008                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9009                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9010                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9011                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9012                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9013                } else {
9014                    // Override with defaults if needed.
9015                    loc = installLocationPolicy(pkgLite);
9016                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9017                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9018                    } else if (!onSd && !onInt) {
9019                        // Override install location with flags
9020                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9021                            // Set the flag to install on external media.
9022                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9023                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9024                        } else {
9025                            // Make sure the flag for installing on external
9026                            // media is unset
9027                            installFlags |= PackageManager.INSTALL_INTERNAL;
9028                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9029                        }
9030                    }
9031                }
9032            }
9033
9034            final InstallArgs args = createInstallArgs(this);
9035            mArgs = args;
9036
9037            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9038                 /*
9039                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9040                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9041                 */
9042                int userIdentifier = getUser().getIdentifier();
9043                if (userIdentifier == UserHandle.USER_ALL
9044                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9045                    userIdentifier = UserHandle.USER_OWNER;
9046                }
9047
9048                /*
9049                 * Determine if we have any installed package verifiers. If we
9050                 * do, then we'll defer to them to verify the packages.
9051                 */
9052                final int requiredUid = mRequiredVerifierPackage == null ? -1
9053                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9054                if (!origin.existing && requiredUid != -1
9055                        && isVerificationEnabled(userIdentifier, installFlags)) {
9056                    final Intent verification = new Intent(
9057                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9058                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9059                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9060                            PACKAGE_MIME_TYPE);
9061                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9062
9063                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9064                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9065                            0 /* TODO: Which userId? */);
9066
9067                    if (DEBUG_VERIFY) {
9068                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9069                                + verification.toString() + " with " + pkgLite.verifiers.length
9070                                + " optional verifiers");
9071                    }
9072
9073                    final int verificationId = mPendingVerificationToken++;
9074
9075                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9076
9077                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9078                            installerPackageName);
9079
9080                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9081                            installFlags);
9082
9083                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9084                            pkgLite.packageName);
9085
9086                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9087                            pkgLite.versionCode);
9088
9089                    if (verificationParams != null) {
9090                        if (verificationParams.getVerificationURI() != null) {
9091                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9092                                 verificationParams.getVerificationURI());
9093                        }
9094                        if (verificationParams.getOriginatingURI() != null) {
9095                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9096                                  verificationParams.getOriginatingURI());
9097                        }
9098                        if (verificationParams.getReferrer() != null) {
9099                            verification.putExtra(Intent.EXTRA_REFERRER,
9100                                  verificationParams.getReferrer());
9101                        }
9102                        if (verificationParams.getOriginatingUid() >= 0) {
9103                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9104                                  verificationParams.getOriginatingUid());
9105                        }
9106                        if (verificationParams.getInstallerUid() >= 0) {
9107                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9108                                  verificationParams.getInstallerUid());
9109                        }
9110                    }
9111
9112                    final PackageVerificationState verificationState = new PackageVerificationState(
9113                            requiredUid, args);
9114
9115                    mPendingVerification.append(verificationId, verificationState);
9116
9117                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9118                            receivers, verificationState);
9119
9120                    /*
9121                     * If any sufficient verifiers were listed in the package
9122                     * manifest, attempt to ask them.
9123                     */
9124                    if (sufficientVerifiers != null) {
9125                        final int N = sufficientVerifiers.size();
9126                        if (N == 0) {
9127                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9128                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9129                        } else {
9130                            for (int i = 0; i < N; i++) {
9131                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9132
9133                                final Intent sufficientIntent = new Intent(verification);
9134                                sufficientIntent.setComponent(verifierComponent);
9135
9136                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9137                            }
9138                        }
9139                    }
9140
9141                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9142                            mRequiredVerifierPackage, receivers);
9143                    if (ret == PackageManager.INSTALL_SUCCEEDED
9144                            && mRequiredVerifierPackage != null) {
9145                        /*
9146                         * Send the intent to the required verification agent,
9147                         * but only start the verification timeout after the
9148                         * target BroadcastReceivers have run.
9149                         */
9150                        verification.setComponent(requiredVerifierComponent);
9151                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9152                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9153                                new BroadcastReceiver() {
9154                                    @Override
9155                                    public void onReceive(Context context, Intent intent) {
9156                                        final Message msg = mHandler
9157                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9158                                        msg.arg1 = verificationId;
9159                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9160                                    }
9161                                }, null, 0, null, null);
9162
9163                        /*
9164                         * We don't want the copy to proceed until verification
9165                         * succeeds, so null out this field.
9166                         */
9167                        mArgs = null;
9168                    }
9169                } else {
9170                    /*
9171                     * No package verification is enabled, so immediately start
9172                     * the remote call to initiate copy using temporary file.
9173                     */
9174                    ret = args.copyApk(mContainerService, true);
9175                }
9176            }
9177
9178            mRet = ret;
9179        }
9180
9181        @Override
9182        void handleReturnCode() {
9183            // If mArgs is null, then MCS couldn't be reached. When it
9184            // reconnects, it will try again to install. At that point, this
9185            // will succeed.
9186            if (mArgs != null) {
9187                processPendingInstall(mArgs, mRet);
9188            }
9189        }
9190
9191        @Override
9192        void handleServiceError() {
9193            mArgs = createInstallArgs(this);
9194            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9195        }
9196
9197        public boolean isForwardLocked() {
9198            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9199        }
9200    }
9201
9202    /**
9203     * Used during creation of InstallArgs
9204     *
9205     * @param installFlags package installation flags
9206     * @return true if should be installed on external storage
9207     */
9208    private static boolean installOnSd(int installFlags) {
9209        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9210            return false;
9211        }
9212        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9213            return true;
9214        }
9215        return false;
9216    }
9217
9218    /**
9219     * Used during creation of InstallArgs
9220     *
9221     * @param installFlags package installation flags
9222     * @return true if should be installed as forward locked
9223     */
9224    private static boolean installForwardLocked(int installFlags) {
9225        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9226    }
9227
9228    private InstallArgs createInstallArgs(InstallParams params) {
9229        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9230            return new AsecInstallArgs(params);
9231        } else {
9232            return new FileInstallArgs(params);
9233        }
9234    }
9235
9236    /**
9237     * Create args that describe an existing installed package. Typically used
9238     * when cleaning up old installs, or used as a move source.
9239     */
9240    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9241            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9242        final boolean isInAsec;
9243        if (installOnSd(installFlags)) {
9244            /* Apps on SD card are always in ASEC containers. */
9245            isInAsec = true;
9246        } else if (installForwardLocked(installFlags)
9247                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9248            /*
9249             * Forward-locked apps are only in ASEC containers if they're the
9250             * new style
9251             */
9252            isInAsec = true;
9253        } else {
9254            isInAsec = false;
9255        }
9256
9257        if (isInAsec) {
9258            return new AsecInstallArgs(codePath, instructionSets,
9259                    installOnSd(installFlags), installForwardLocked(installFlags));
9260        } else {
9261            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9262                    instructionSets);
9263        }
9264    }
9265
9266    static abstract class InstallArgs {
9267        /** @see InstallParams#origin */
9268        final OriginInfo origin;
9269
9270        final IPackageInstallObserver2 observer;
9271        // Always refers to PackageManager flags only
9272        final int installFlags;
9273        final String installerPackageName;
9274        final ManifestDigest manifestDigest;
9275        final UserHandle user;
9276        final String abiOverride;
9277
9278        // The list of instruction sets supported by this app. This is currently
9279        // only used during the rmdex() phase to clean up resources. We can get rid of this
9280        // if we move dex files under the common app path.
9281        /* nullable */ String[] instructionSets;
9282
9283        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9284                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9285                String[] instructionSets, String abiOverride) {
9286            this.origin = origin;
9287            this.installFlags = installFlags;
9288            this.observer = observer;
9289            this.installerPackageName = installerPackageName;
9290            this.manifestDigest = manifestDigest;
9291            this.user = user;
9292            this.instructionSets = instructionSets;
9293            this.abiOverride = abiOverride;
9294        }
9295
9296        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9297        abstract int doPreInstall(int status);
9298
9299        /**
9300         * Rename package into final resting place. All paths on the given
9301         * scanned package should be updated to reflect the rename.
9302         */
9303        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9304        abstract int doPostInstall(int status, int uid);
9305
9306        /** @see PackageSettingBase#codePathString */
9307        abstract String getCodePath();
9308        /** @see PackageSettingBase#resourcePathString */
9309        abstract String getResourcePath();
9310        abstract String getLegacyNativeLibraryPath();
9311
9312        // Need installer lock especially for dex file removal.
9313        abstract void cleanUpResourcesLI();
9314        abstract boolean doPostDeleteLI(boolean delete);
9315        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9316
9317        /**
9318         * Called before the source arguments are copied. This is used mostly
9319         * for MoveParams when it needs to read the source file to put it in the
9320         * destination.
9321         */
9322        int doPreCopy() {
9323            return PackageManager.INSTALL_SUCCEEDED;
9324        }
9325
9326        /**
9327         * Called after the source arguments are copied. This is used mostly for
9328         * MoveParams when it needs to read the source file to put it in the
9329         * destination.
9330         *
9331         * @return
9332         */
9333        int doPostCopy(int uid) {
9334            return PackageManager.INSTALL_SUCCEEDED;
9335        }
9336
9337        protected boolean isFwdLocked() {
9338            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9339        }
9340
9341        protected boolean isExternal() {
9342            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9343        }
9344
9345        UserHandle getUser() {
9346            return user;
9347        }
9348    }
9349
9350    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9351        if (!allCodePaths.isEmpty()) {
9352            if (instructionSets == null) {
9353                throw new IllegalStateException("instructionSet == null");
9354            }
9355            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9356            for (String codePath : allCodePaths) {
9357                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9358                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9359                    if (retCode < 0) {
9360                        Slog.w(TAG, "Couldn't remove dex file for package: "
9361                                + " at location " + codePath + ", retcode=" + retCode);
9362                        // we don't consider this to be a failure of the core package deletion
9363                    }
9364                }
9365            }
9366        }
9367    }
9368
9369    /**
9370     * Logic to handle installation of non-ASEC applications, including copying
9371     * and renaming logic.
9372     */
9373    class FileInstallArgs extends InstallArgs {
9374        private File codeFile;
9375        private File resourceFile;
9376        private File legacyNativeLibraryPath;
9377
9378        // Example topology:
9379        // /data/app/com.example/base.apk
9380        // /data/app/com.example/split_foo.apk
9381        // /data/app/com.example/lib/arm/libfoo.so
9382        // /data/app/com.example/lib/arm64/libfoo.so
9383        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9384
9385        /** New install */
9386        FileInstallArgs(InstallParams params) {
9387            super(params.origin, params.observer, params.installFlags,
9388                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9389                    null /* instruction sets */, params.packageAbiOverride);
9390            if (isFwdLocked()) {
9391                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9392            }
9393        }
9394
9395        /** Existing install */
9396        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9397                String[] instructionSets) {
9398            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9399            this.codeFile = (codePath != null) ? new File(codePath) : null;
9400            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9401            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9402                    new File(legacyNativeLibraryPath) : null;
9403        }
9404
9405        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9406            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9407                    isFwdLocked(), abiOverride);
9408
9409            final StorageManager storage = StorageManager.from(mContext);
9410            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9411        }
9412
9413        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9414            if (origin.staged) {
9415                Slog.d(TAG, origin.file + " already staged; skipping copy");
9416                codeFile = origin.file;
9417                resourceFile = origin.file;
9418                return PackageManager.INSTALL_SUCCEEDED;
9419            }
9420
9421            try {
9422                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9423                codeFile = tempDir;
9424                resourceFile = tempDir;
9425            } catch (IOException e) {
9426                Slog.w(TAG, "Failed to create copy file: " + e);
9427                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9428            }
9429
9430            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9431                @Override
9432                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9433                    if (!FileUtils.isValidExtFilename(name)) {
9434                        throw new IllegalArgumentException("Invalid filename: " + name);
9435                    }
9436                    try {
9437                        final File file = new File(codeFile, name);
9438                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9439                                O_RDWR | O_CREAT, 0644);
9440                        Os.chmod(file.getAbsolutePath(), 0644);
9441                        return new ParcelFileDescriptor(fd);
9442                    } catch (ErrnoException e) {
9443                        throw new RemoteException("Failed to open: " + e.getMessage());
9444                    }
9445                }
9446            };
9447
9448            int ret = PackageManager.INSTALL_SUCCEEDED;
9449            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9450            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9451                Slog.e(TAG, "Failed to copy package");
9452                return ret;
9453            }
9454
9455            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9456            NativeLibraryHelper.Handle handle = null;
9457            try {
9458                handle = NativeLibraryHelper.Handle.create(codeFile);
9459                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9460                        abiOverride);
9461            } catch (IOException e) {
9462                Slog.e(TAG, "Copying native libraries failed", e);
9463                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9464            } finally {
9465                IoUtils.closeQuietly(handle);
9466            }
9467
9468            return ret;
9469        }
9470
9471        int doPreInstall(int status) {
9472            if (status != PackageManager.INSTALL_SUCCEEDED) {
9473                cleanUp();
9474            }
9475            return status;
9476        }
9477
9478        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9479            if (status != PackageManager.INSTALL_SUCCEEDED) {
9480                cleanUp();
9481                return false;
9482            } else {
9483                final File beforeCodeFile = codeFile;
9484                final File afterCodeFile = getNextCodePath(pkg.packageName);
9485
9486                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9487                try {
9488                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9489                } catch (ErrnoException e) {
9490                    Slog.d(TAG, "Failed to rename", e);
9491                    return false;
9492                }
9493
9494                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9495                    Slog.d(TAG, "Failed to restorecon");
9496                    return false;
9497                }
9498
9499                // Reflect the rename internally
9500                codeFile = afterCodeFile;
9501                resourceFile = afterCodeFile;
9502
9503                // Reflect the rename in scanned details
9504                pkg.codePath = afterCodeFile.getAbsolutePath();
9505                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9506                        pkg.baseCodePath);
9507                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9508                        pkg.splitCodePaths);
9509
9510                // Reflect the rename in app info
9511                pkg.applicationInfo.setCodePath(pkg.codePath);
9512                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9513                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9514                pkg.applicationInfo.setResourcePath(pkg.codePath);
9515                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9516                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9517
9518                return true;
9519            }
9520        }
9521
9522        int doPostInstall(int status, int uid) {
9523            if (status != PackageManager.INSTALL_SUCCEEDED) {
9524                cleanUp();
9525            }
9526            return status;
9527        }
9528
9529        @Override
9530        String getCodePath() {
9531            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9532        }
9533
9534        @Override
9535        String getResourcePath() {
9536            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9537        }
9538
9539        @Override
9540        String getLegacyNativeLibraryPath() {
9541            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9542        }
9543
9544        private boolean cleanUp() {
9545            if (codeFile == null || !codeFile.exists()) {
9546                return false;
9547            }
9548
9549            if (codeFile.isDirectory()) {
9550                FileUtils.deleteContents(codeFile);
9551            }
9552            codeFile.delete();
9553
9554            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9555                resourceFile.delete();
9556            }
9557
9558            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9559                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9560                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9561                }
9562                legacyNativeLibraryPath.delete();
9563            }
9564
9565            return true;
9566        }
9567
9568        void cleanUpResourcesLI() {
9569            // Try enumerating all code paths before deleting
9570            List<String> allCodePaths = Collections.EMPTY_LIST;
9571            if (codeFile != null && codeFile.exists()) {
9572                try {
9573                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9574                    allCodePaths = pkg.getAllCodePaths();
9575                } catch (PackageParserException e) {
9576                    // Ignored; we tried our best
9577                }
9578            }
9579
9580            cleanUp();
9581            removeDexFiles(allCodePaths, instructionSets);
9582        }
9583
9584        boolean doPostDeleteLI(boolean delete) {
9585            // XXX err, shouldn't we respect the delete flag?
9586            cleanUpResourcesLI();
9587            return true;
9588        }
9589    }
9590
9591    private boolean isAsecExternal(String cid) {
9592        final String asecPath = PackageHelper.getSdFilesystem(cid);
9593        return !asecPath.startsWith(mAsecInternalPath);
9594    }
9595
9596    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9597            PackageManagerException {
9598        if (copyRet < 0) {
9599            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9600                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9601                throw new PackageManagerException(copyRet, message);
9602            }
9603        }
9604    }
9605
9606    /**
9607     * Extract the MountService "container ID" from the full code path of an
9608     * .apk.
9609     */
9610    static String cidFromCodePath(String fullCodePath) {
9611        int eidx = fullCodePath.lastIndexOf("/");
9612        String subStr1 = fullCodePath.substring(0, eidx);
9613        int sidx = subStr1.lastIndexOf("/");
9614        return subStr1.substring(sidx+1, eidx);
9615    }
9616
9617    /**
9618     * Logic to handle installation of ASEC applications, including copying and
9619     * renaming logic.
9620     */
9621    class AsecInstallArgs extends InstallArgs {
9622        static final String RES_FILE_NAME = "pkg.apk";
9623        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9624
9625        String cid;
9626        String packagePath;
9627        String resourcePath;
9628        String legacyNativeLibraryDir;
9629
9630        /** New install */
9631        AsecInstallArgs(InstallParams params) {
9632            super(params.origin, params.observer, params.installFlags,
9633                    params.installerPackageName, params.getManifestDigest(),
9634                    params.getUser(), null /* instruction sets */,
9635                    params.packageAbiOverride);
9636        }
9637
9638        /** Existing install */
9639        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9640                        boolean isExternal, boolean isForwardLocked) {
9641            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9642                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9643                    instructionSets, null);
9644            // Hackily pretend we're still looking at a full code path
9645            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9646                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9647            }
9648
9649            // Extract cid from fullCodePath
9650            int eidx = fullCodePath.lastIndexOf("/");
9651            String subStr1 = fullCodePath.substring(0, eidx);
9652            int sidx = subStr1.lastIndexOf("/");
9653            cid = subStr1.substring(sidx+1, eidx);
9654            setMountPath(subStr1);
9655        }
9656
9657        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9658            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9659                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9660                    instructionSets, null);
9661            this.cid = cid;
9662            setMountPath(PackageHelper.getSdDir(cid));
9663        }
9664
9665        void createCopyFile() {
9666            cid = mInstallerService.allocateExternalStageCidLegacy();
9667        }
9668
9669        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9670            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9671                    abiOverride);
9672
9673            final File target;
9674            if (isExternal()) {
9675                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9676            } else {
9677                target = Environment.getDataDirectory();
9678            }
9679
9680            final StorageManager storage = StorageManager.from(mContext);
9681            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9682        }
9683
9684        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9685            if (origin.staged) {
9686                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9687                cid = origin.cid;
9688                setMountPath(PackageHelper.getSdDir(cid));
9689                return PackageManager.INSTALL_SUCCEEDED;
9690            }
9691
9692            if (temp) {
9693                createCopyFile();
9694            } else {
9695                /*
9696                 * Pre-emptively destroy the container since it's destroyed if
9697                 * copying fails due to it existing anyway.
9698                 */
9699                PackageHelper.destroySdDir(cid);
9700            }
9701
9702            final String newMountPath = imcs.copyPackageToContainer(
9703                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9704                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9705
9706            if (newMountPath != null) {
9707                setMountPath(newMountPath);
9708                return PackageManager.INSTALL_SUCCEEDED;
9709            } else {
9710                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9711            }
9712        }
9713
9714        @Override
9715        String getCodePath() {
9716            return packagePath;
9717        }
9718
9719        @Override
9720        String getResourcePath() {
9721            return resourcePath;
9722        }
9723
9724        @Override
9725        String getLegacyNativeLibraryPath() {
9726            return legacyNativeLibraryDir;
9727        }
9728
9729        int doPreInstall(int status) {
9730            if (status != PackageManager.INSTALL_SUCCEEDED) {
9731                // Destroy container
9732                PackageHelper.destroySdDir(cid);
9733            } else {
9734                boolean mounted = PackageHelper.isContainerMounted(cid);
9735                if (!mounted) {
9736                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9737                            Process.SYSTEM_UID);
9738                    if (newMountPath != null) {
9739                        setMountPath(newMountPath);
9740                    } else {
9741                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9742                    }
9743                }
9744            }
9745            return status;
9746        }
9747
9748        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9749            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9750            String newMountPath = null;
9751            if (PackageHelper.isContainerMounted(cid)) {
9752                // Unmount the container
9753                if (!PackageHelper.unMountSdDir(cid)) {
9754                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9755                    return false;
9756                }
9757            }
9758            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9759                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9760                        " which might be stale. Will try to clean up.");
9761                // Clean up the stale container and proceed to recreate.
9762                if (!PackageHelper.destroySdDir(newCacheId)) {
9763                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9764                    return false;
9765                }
9766                // Successfully cleaned up stale container. Try to rename again.
9767                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9768                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9769                            + " inspite of cleaning it up.");
9770                    return false;
9771                }
9772            }
9773            if (!PackageHelper.isContainerMounted(newCacheId)) {
9774                Slog.w(TAG, "Mounting container " + newCacheId);
9775                newMountPath = PackageHelper.mountSdDir(newCacheId,
9776                        getEncryptKey(), Process.SYSTEM_UID);
9777            } else {
9778                newMountPath = PackageHelper.getSdDir(newCacheId);
9779            }
9780            if (newMountPath == null) {
9781                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9782                return false;
9783            }
9784            Log.i(TAG, "Succesfully renamed " + cid +
9785                    " to " + newCacheId +
9786                    " at new path: " + newMountPath);
9787            cid = newCacheId;
9788
9789            final File beforeCodeFile = new File(packagePath);
9790            setMountPath(newMountPath);
9791            final File afterCodeFile = new File(packagePath);
9792
9793            // Reflect the rename in scanned details
9794            pkg.codePath = afterCodeFile.getAbsolutePath();
9795            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9796                    pkg.baseCodePath);
9797            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9798                    pkg.splitCodePaths);
9799
9800            // Reflect the rename in app info
9801            pkg.applicationInfo.setCodePath(pkg.codePath);
9802            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9803            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9804            pkg.applicationInfo.setResourcePath(pkg.codePath);
9805            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9806            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9807
9808            return true;
9809        }
9810
9811        private void setMountPath(String mountPath) {
9812            final File mountFile = new File(mountPath);
9813
9814            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9815            if (monolithicFile.exists()) {
9816                packagePath = monolithicFile.getAbsolutePath();
9817                if (isFwdLocked()) {
9818                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9819                } else {
9820                    resourcePath = packagePath;
9821                }
9822            } else {
9823                packagePath = mountFile.getAbsolutePath();
9824                resourcePath = packagePath;
9825            }
9826
9827            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9828        }
9829
9830        int doPostInstall(int status, int uid) {
9831            if (status != PackageManager.INSTALL_SUCCEEDED) {
9832                cleanUp();
9833            } else {
9834                final int groupOwner;
9835                final String protectedFile;
9836                if (isFwdLocked()) {
9837                    groupOwner = UserHandle.getSharedAppGid(uid);
9838                    protectedFile = RES_FILE_NAME;
9839                } else {
9840                    groupOwner = -1;
9841                    protectedFile = null;
9842                }
9843
9844                if (uid < Process.FIRST_APPLICATION_UID
9845                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9846                    Slog.e(TAG, "Failed to finalize " + cid);
9847                    PackageHelper.destroySdDir(cid);
9848                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9849                }
9850
9851                boolean mounted = PackageHelper.isContainerMounted(cid);
9852                if (!mounted) {
9853                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9854                }
9855            }
9856            return status;
9857        }
9858
9859        private void cleanUp() {
9860            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9861
9862            // Destroy secure container
9863            PackageHelper.destroySdDir(cid);
9864        }
9865
9866        private List<String> getAllCodePaths() {
9867            final File codeFile = new File(getCodePath());
9868            if (codeFile != null && codeFile.exists()) {
9869                try {
9870                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9871                    return pkg.getAllCodePaths();
9872                } catch (PackageParserException e) {
9873                    // Ignored; we tried our best
9874                }
9875            }
9876            return Collections.EMPTY_LIST;
9877        }
9878
9879        void cleanUpResourcesLI() {
9880            // Enumerate all code paths before deleting
9881            cleanUpResourcesLI(getAllCodePaths());
9882        }
9883
9884        private void cleanUpResourcesLI(List<String> allCodePaths) {
9885            cleanUp();
9886            removeDexFiles(allCodePaths, instructionSets);
9887        }
9888
9889
9890
9891        String getPackageName() {
9892            return getAsecPackageName(cid);
9893        }
9894
9895        boolean doPostDeleteLI(boolean delete) {
9896            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9897            final List<String> allCodePaths = getAllCodePaths();
9898            boolean mounted = PackageHelper.isContainerMounted(cid);
9899            if (mounted) {
9900                // Unmount first
9901                if (PackageHelper.unMountSdDir(cid)) {
9902                    mounted = false;
9903                }
9904            }
9905            if (!mounted && delete) {
9906                cleanUpResourcesLI(allCodePaths);
9907            }
9908            return !mounted;
9909        }
9910
9911        @Override
9912        int doPreCopy() {
9913            if (isFwdLocked()) {
9914                if (!PackageHelper.fixSdPermissions(cid,
9915                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9916                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9917                }
9918            }
9919
9920            return PackageManager.INSTALL_SUCCEEDED;
9921        }
9922
9923        @Override
9924        int doPostCopy(int uid) {
9925            if (isFwdLocked()) {
9926                if (uid < Process.FIRST_APPLICATION_UID
9927                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9928                                RES_FILE_NAME)) {
9929                    Slog.e(TAG, "Failed to finalize " + cid);
9930                    PackageHelper.destroySdDir(cid);
9931                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9932                }
9933            }
9934
9935            return PackageManager.INSTALL_SUCCEEDED;
9936        }
9937    }
9938
9939    static String getAsecPackageName(String packageCid) {
9940        int idx = packageCid.lastIndexOf("-");
9941        if (idx == -1) {
9942            return packageCid;
9943        }
9944        return packageCid.substring(0, idx);
9945    }
9946
9947    // Utility method used to create code paths based on package name and available index.
9948    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9949        String idxStr = "";
9950        int idx = 1;
9951        // Fall back to default value of idx=1 if prefix is not
9952        // part of oldCodePath
9953        if (oldCodePath != null) {
9954            String subStr = oldCodePath;
9955            // Drop the suffix right away
9956            if (suffix != null && subStr.endsWith(suffix)) {
9957                subStr = subStr.substring(0, subStr.length() - suffix.length());
9958            }
9959            // If oldCodePath already contains prefix find out the
9960            // ending index to either increment or decrement.
9961            int sidx = subStr.lastIndexOf(prefix);
9962            if (sidx != -1) {
9963                subStr = subStr.substring(sidx + prefix.length());
9964                if (subStr != null) {
9965                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9966                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9967                    }
9968                    try {
9969                        idx = Integer.parseInt(subStr);
9970                        if (idx <= 1) {
9971                            idx++;
9972                        } else {
9973                            idx--;
9974                        }
9975                    } catch(NumberFormatException e) {
9976                    }
9977                }
9978            }
9979        }
9980        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9981        return prefix + idxStr;
9982    }
9983
9984    private File getNextCodePath(String packageName) {
9985        int suffix = 1;
9986        File result;
9987        do {
9988            result = new File(mAppInstallDir, packageName + "-" + suffix);
9989            suffix++;
9990        } while (result.exists());
9991        return result;
9992    }
9993
9994    // Utility method used to ignore ADD/REMOVE events
9995    // by directory observer.
9996    private static boolean ignoreCodePath(String fullPathStr) {
9997        String apkName = deriveCodePathName(fullPathStr);
9998        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9999        if (idx != -1 && ((idx+1) < apkName.length())) {
10000            // Make sure the package ends with a numeral
10001            String version = apkName.substring(idx+1);
10002            try {
10003                Integer.parseInt(version);
10004                return true;
10005            } catch (NumberFormatException e) {}
10006        }
10007        return false;
10008    }
10009
10010    // Utility method that returns the relative package path with respect
10011    // to the installation directory. Like say for /data/data/com.test-1.apk
10012    // string com.test-1 is returned.
10013    static String deriveCodePathName(String codePath) {
10014        if (codePath == null) {
10015            return null;
10016        }
10017        final File codeFile = new File(codePath);
10018        final String name = codeFile.getName();
10019        if (codeFile.isDirectory()) {
10020            return name;
10021        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10022            final int lastDot = name.lastIndexOf('.');
10023            return name.substring(0, lastDot);
10024        } else {
10025            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10026            return null;
10027        }
10028    }
10029
10030    class PackageInstalledInfo {
10031        String name;
10032        int uid;
10033        // The set of users that originally had this package installed.
10034        int[] origUsers;
10035        // The set of users that now have this package installed.
10036        int[] newUsers;
10037        PackageParser.Package pkg;
10038        int returnCode;
10039        String returnMsg;
10040        PackageRemovedInfo removedInfo;
10041
10042        public void setError(int code, String msg) {
10043            returnCode = code;
10044            returnMsg = msg;
10045            Slog.w(TAG, msg);
10046        }
10047
10048        public void setError(String msg, PackageParserException e) {
10049            returnCode = e.error;
10050            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10051            Slog.w(TAG, msg, e);
10052        }
10053
10054        public void setError(String msg, PackageManagerException e) {
10055            returnCode = e.error;
10056            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10057            Slog.w(TAG, msg, e);
10058        }
10059
10060        // In some error cases we want to convey more info back to the observer
10061        String origPackage;
10062        String origPermission;
10063    }
10064
10065    /*
10066     * Install a non-existing package.
10067     */
10068    private void installNewPackageLI(PackageParser.Package pkg,
10069            int parseFlags, int scanFlags, UserHandle user,
10070            String installerPackageName, PackageInstalledInfo res) {
10071        // Remember this for later, in case we need to rollback this install
10072        String pkgName = pkg.packageName;
10073
10074        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10075        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10076        synchronized(mPackages) {
10077            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10078                // A package with the same name is already installed, though
10079                // it has been renamed to an older name.  The package we
10080                // are trying to install should be installed as an update to
10081                // the existing one, but that has not been requested, so bail.
10082                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10083                        + " without first uninstalling package running as "
10084                        + mSettings.mRenamedPackages.get(pkgName));
10085                return;
10086            }
10087            if (mPackages.containsKey(pkgName)) {
10088                // Don't allow installation over an existing package with the same name.
10089                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10090                        + " without first uninstalling.");
10091                return;
10092            }
10093        }
10094
10095        try {
10096            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10097                    System.currentTimeMillis(), user);
10098
10099            updateSettingsLI(newPackage, installerPackageName, null, null, res, user);
10100            // delete the partially installed application. the data directory will have to be
10101            // restored if it was already existing
10102            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10103                // remove package from internal structures.  Note that we want deletePackageX to
10104                // delete the package data and cache directories that it created in
10105                // scanPackageLocked, unless those directories existed before we even tried to
10106                // install.
10107                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10108                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10109                                res.removedInfo, true);
10110            }
10111
10112        } catch (PackageManagerException e) {
10113            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10114        }
10115    }
10116
10117    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10118        // Upgrade keysets are being used.  Determine if new package has a superset of the
10119        // required keys.
10120        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10121        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10122        for (int i = 0; i < upgradeKeySets.length; i++) {
10123            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10124            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10125                return true;
10126            }
10127        }
10128        return false;
10129    }
10130
10131    private void replacePackageLI(PackageParser.Package pkg,
10132            int parseFlags, int scanFlags, UserHandle user,
10133            String installerPackageName, PackageInstalledInfo res) {
10134        PackageParser.Package oldPackage;
10135        String pkgName = pkg.packageName;
10136        int[] allUsers;
10137        boolean[] perUserInstalled;
10138
10139        // First find the old package info and check signatures
10140        synchronized(mPackages) {
10141            oldPackage = mPackages.get(pkgName);
10142            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10143            PackageSetting ps = mSettings.mPackages.get(pkgName);
10144            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10145                // default to original signature matching
10146                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10147                    != PackageManager.SIGNATURE_MATCH) {
10148                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10149                            "New package has a different signature: " + pkgName);
10150                    return;
10151                }
10152            } else {
10153                if(!checkUpgradeKeySetLP(ps, pkg)) {
10154                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10155                            "New package not signed by keys specified by upgrade-keysets: "
10156                            + pkgName);
10157                    return;
10158                }
10159            }
10160
10161            // In case of rollback, remember per-user/profile install state
10162            allUsers = sUserManager.getUserIds();
10163            perUserInstalled = new boolean[allUsers.length];
10164            for (int i = 0; i < allUsers.length; i++) {
10165                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10166            }
10167        }
10168
10169        boolean sysPkg = (isSystemApp(oldPackage));
10170        if (sysPkg) {
10171            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10172                    user, allUsers, perUserInstalled, installerPackageName, res);
10173        } else {
10174            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10175                    user, allUsers, perUserInstalled, installerPackageName, res);
10176        }
10177    }
10178
10179    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10180            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10181            int[] allUsers, boolean[] perUserInstalled,
10182            String installerPackageName, PackageInstalledInfo res) {
10183        String pkgName = deletedPackage.packageName;
10184        boolean deletedPkg = true;
10185        boolean updatedSettings = false;
10186
10187        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10188                + deletedPackage);
10189        long origUpdateTime;
10190        if (pkg.mExtras != null) {
10191            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10192        } else {
10193            origUpdateTime = 0;
10194        }
10195
10196        // First delete the existing package while retaining the data directory
10197        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10198                res.removedInfo, true)) {
10199            // If the existing package wasn't successfully deleted
10200            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10201            deletedPkg = false;
10202        } else {
10203            // Successfully deleted the old package; proceed with replace.
10204
10205            // If deleted package lived in a container, give users a chance to
10206            // relinquish resources before killing.
10207            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10208                if (DEBUG_INSTALL) {
10209                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10210                }
10211                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10212                final ArrayList<String> pkgList = new ArrayList<String>(1);
10213                pkgList.add(deletedPackage.applicationInfo.packageName);
10214                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10215            }
10216
10217            deleteCodeCacheDirsLI(pkgName);
10218            try {
10219                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10220                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10221                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res,
10222                        user);
10223                updatedSettings = true;
10224            } catch (PackageManagerException e) {
10225                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10226            }
10227        }
10228
10229        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10230            // remove package from internal structures.  Note that we want deletePackageX to
10231            // delete the package data and cache directories that it created in
10232            // scanPackageLocked, unless those directories existed before we even tried to
10233            // install.
10234            if(updatedSettings) {
10235                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10236                deletePackageLI(
10237                        pkgName, null, true, allUsers, perUserInstalled,
10238                        PackageManager.DELETE_KEEP_DATA,
10239                                res.removedInfo, true);
10240            }
10241            // Since we failed to install the new package we need to restore the old
10242            // package that we deleted.
10243            if (deletedPkg) {
10244                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10245                File restoreFile = new File(deletedPackage.codePath);
10246                // Parse old package
10247                boolean oldOnSd = isExternal(deletedPackage);
10248                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10249                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10250                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10251                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10252                try {
10253                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10254                } catch (PackageManagerException e) {
10255                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10256                            + e.getMessage());
10257                    return;
10258                }
10259                // Restore of old package succeeded. Update permissions.
10260                // writer
10261                synchronized (mPackages) {
10262                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10263                            UPDATE_PERMISSIONS_ALL);
10264                    // can downgrade to reader
10265                    mSettings.writeLPr();
10266                }
10267                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10268            }
10269        }
10270    }
10271
10272    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10273            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10274            int[] allUsers, boolean[] perUserInstalled,
10275            String installerPackageName, PackageInstalledInfo res) {
10276        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10277                + ", old=" + deletedPackage);
10278        boolean disabledSystem = false;
10279        boolean updatedSettings = false;
10280        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10281        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10282                != 0) {
10283            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10284        }
10285        String packageName = deletedPackage.packageName;
10286        if (packageName == null) {
10287            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10288                    "Attempt to delete null packageName.");
10289            return;
10290        }
10291        PackageParser.Package oldPkg;
10292        PackageSetting oldPkgSetting;
10293        // reader
10294        synchronized (mPackages) {
10295            oldPkg = mPackages.get(packageName);
10296            oldPkgSetting = mSettings.mPackages.get(packageName);
10297            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10298                    (oldPkgSetting == null)) {
10299                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10300                        "Couldn't find package:" + packageName + " information");
10301                return;
10302            }
10303        }
10304
10305        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10306
10307        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10308        res.removedInfo.removedPackage = packageName;
10309        // Remove existing system package
10310        removePackageLI(oldPkgSetting, true);
10311        // writer
10312        synchronized (mPackages) {
10313            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10314            if (!disabledSystem && deletedPackage != null) {
10315                // We didn't need to disable the .apk as a current system package,
10316                // which means we are replacing another update that is already
10317                // installed.  We need to make sure to delete the older one's .apk.
10318                res.removedInfo.args = createInstallArgsForExisting(0,
10319                        deletedPackage.applicationInfo.getCodePath(),
10320                        deletedPackage.applicationInfo.getResourcePath(),
10321                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10322                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10323            } else {
10324                res.removedInfo.args = null;
10325            }
10326        }
10327
10328        // Successfully disabled the old package. Now proceed with re-installation
10329        deleteCodeCacheDirsLI(packageName);
10330
10331        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10332        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10333
10334        PackageParser.Package newPackage = null;
10335        try {
10336            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10337            if (newPackage.mExtras != null) {
10338                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10339                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10340                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10341
10342                // is the update attempting to change shared user? that isn't going to work...
10343                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10344                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10345                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10346                            + " to " + newPkgSetting.sharedUser);
10347                    updatedSettings = true;
10348                }
10349            }
10350
10351            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10352                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res,
10353                        user);
10354                updatedSettings = true;
10355            }
10356
10357        } catch (PackageManagerException e) {
10358            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10359        }
10360
10361        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10362            // Re installation failed. Restore old information
10363            // Remove new pkg information
10364            if (newPackage != null) {
10365                removeInstalledPackageLI(newPackage, true);
10366            }
10367            // Add back the old system package
10368            try {
10369                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10370            } catch (PackageManagerException e) {
10371                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10372            }
10373            // Restore the old system information in Settings
10374            synchronized (mPackages) {
10375                if (disabledSystem) {
10376                    mSettings.enableSystemPackageLPw(packageName);
10377                }
10378                if (updatedSettings) {
10379                    mSettings.setInstallerPackageName(packageName,
10380                            oldPkgSetting.installerPackageName);
10381                }
10382                mSettings.writeLPr();
10383            }
10384        }
10385    }
10386
10387    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10388            int[] allUsers, boolean[] perUserInstalled,
10389            PackageInstalledInfo res, UserHandle user) {
10390        String pkgName = newPackage.packageName;
10391        synchronized (mPackages) {
10392            //write settings. the installStatus will be incomplete at this stage.
10393            //note that the new package setting would have already been
10394            //added to mPackages. It hasn't been persisted yet.
10395            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10396            mSettings.writeLPr();
10397        }
10398
10399        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10400
10401        synchronized (mPackages) {
10402            updatePermissionsLPw(newPackage.packageName, newPackage,
10403                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10404                            ? UPDATE_PERMISSIONS_ALL : 0));
10405            // For system-bundled packages, we assume that installing an upgraded version
10406            // of the package implies that the user actually wants to run that new code,
10407            // so we enable the package.
10408            PackageSetting ps = mSettings.mPackages.get(pkgName);
10409            if (ps != null) {
10410                if (isSystemApp(newPackage)) {
10411                    // NB: implicit assumption that system package upgrades apply to all users
10412                    if (DEBUG_INSTALL) {
10413                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10414                    }
10415                    if (res.origUsers != null) {
10416                        for (int userHandle : res.origUsers) {
10417                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10418                                    userHandle, installerPackageName);
10419                        }
10420                    }
10421                    // Also convey the prior install/uninstall state
10422                    if (allUsers != null && perUserInstalled != null) {
10423                        for (int i = 0; i < allUsers.length; i++) {
10424                            if (DEBUG_INSTALL) {
10425                                Slog.d(TAG, "    user " + allUsers[i]
10426                                        + " => " + perUserInstalled[i]);
10427                            }
10428                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10429                        }
10430                        // these install state changes will be persisted in the
10431                        // upcoming call to mSettings.writeLPr().
10432                    }
10433                }
10434                // It's implied that when a user requests installation, they want the app to be
10435                // installed and enabled.
10436                int userId = user.getIdentifier();
10437                if (userId != UserHandle.USER_ALL) {
10438                    ps.setInstalled(true, userId);
10439                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
10440                }
10441            }
10442            res.name = pkgName;
10443            res.uid = newPackage.applicationInfo.uid;
10444            res.pkg = newPackage;
10445            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10446            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10447            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10448            //to update install status
10449            mSettings.writeLPr();
10450        }
10451    }
10452
10453    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10454        final int installFlags = args.installFlags;
10455        String installerPackageName = args.installerPackageName;
10456        File tmpPackageFile = new File(args.getCodePath());
10457        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10458        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10459        boolean replace = false;
10460        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10461        // Result object to be returned
10462        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10463
10464        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10465        // Retrieve PackageSettings and parse package
10466        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10467                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10468                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10469        PackageParser pp = new PackageParser();
10470        pp.setSeparateProcesses(mSeparateProcesses);
10471        pp.setDisplayMetrics(mMetrics);
10472
10473        final PackageParser.Package pkg;
10474        try {
10475            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10476        } catch (PackageParserException e) {
10477            res.setError("Failed parse during installPackageLI", e);
10478            return;
10479        }
10480
10481        // Mark that we have an install time CPU ABI override.
10482        pkg.cpuAbiOverride = args.abiOverride;
10483
10484        String pkgName = res.name = pkg.packageName;
10485        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10486            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10487                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10488                return;
10489            }
10490        }
10491
10492        try {
10493            pp.collectCertificates(pkg, parseFlags);
10494            pp.collectManifestDigest(pkg);
10495        } catch (PackageParserException e) {
10496            res.setError("Failed collect during installPackageLI", e);
10497            return;
10498        }
10499
10500        /* If the installer passed in a manifest digest, compare it now. */
10501        if (args.manifestDigest != null) {
10502            if (DEBUG_INSTALL) {
10503                final String parsedManifest = pkg.manifestDigest == null ? "null"
10504                        : pkg.manifestDigest.toString();
10505                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10506                        + parsedManifest);
10507            }
10508
10509            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10510                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10511                return;
10512            }
10513        } else if (DEBUG_INSTALL) {
10514            final String parsedManifest = pkg.manifestDigest == null
10515                    ? "null" : pkg.manifestDigest.toString();
10516            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10517        }
10518
10519        // Get rid of all references to package scan path via parser.
10520        pp = null;
10521        String oldCodePath = null;
10522        boolean systemApp = false;
10523        synchronized (mPackages) {
10524            // Check if installing already existing package
10525            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10526                String oldName = mSettings.mRenamedPackages.get(pkgName);
10527                if (pkg.mOriginalPackages != null
10528                        && pkg.mOriginalPackages.contains(oldName)
10529                        && mPackages.containsKey(oldName)) {
10530                    // This package is derived from an original package,
10531                    // and this device has been updating from that original
10532                    // name.  We must continue using the original name, so
10533                    // rename the new package here.
10534                    pkg.setPackageName(oldName);
10535                    pkgName = pkg.packageName;
10536                    replace = true;
10537                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10538                            + oldName + " pkgName=" + pkgName);
10539                } else if (mPackages.containsKey(pkgName)) {
10540                    // This package, under its official name, already exists
10541                    // on the device; we should replace it.
10542                    replace = true;
10543                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10544                }
10545            }
10546
10547            PackageSetting ps = mSettings.mPackages.get(pkgName);
10548            if (ps != null) {
10549                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10550
10551                // Quick sanity check that we're signed correctly if updating;
10552                // we'll check this again later when scanning, but we want to
10553                // bail early here before tripping over redefined permissions.
10554                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10555                    try {
10556                        verifySignaturesLP(ps, pkg);
10557                    } catch (PackageManagerException e) {
10558                        res.setError(e.error, e.getMessage());
10559                        return;
10560                    }
10561                } else {
10562                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10563                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10564                                + pkg.packageName + " upgrade keys do not match the "
10565                                + "previously installed version");
10566                        return;
10567                    }
10568                }
10569
10570                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10571                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10572                    systemApp = (ps.pkg.applicationInfo.flags &
10573                            ApplicationInfo.FLAG_SYSTEM) != 0;
10574                }
10575                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10576            }
10577
10578            // Check whether the newly-scanned package wants to define an already-defined perm
10579            int N = pkg.permissions.size();
10580            for (int i = N-1; i >= 0; i--) {
10581                PackageParser.Permission perm = pkg.permissions.get(i);
10582                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10583                if (bp != null) {
10584                    // If the defining package is signed with our cert, it's okay.  This
10585                    // also includes the "updating the same package" case, of course.
10586                    // "updating same package" could also involve key-rotation.
10587                    final boolean sigsOk;
10588                    if (!bp.sourcePackage.equals(pkg.packageName)
10589                            || !(bp.packageSetting instanceof PackageSetting)
10590                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10591                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10592                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10593                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10594                    } else {
10595                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10596                    }
10597                    if (!sigsOk) {
10598                        // If the owning package is the system itself, we log but allow
10599                        // install to proceed; we fail the install on all other permission
10600                        // redefinitions.
10601                        if (!bp.sourcePackage.equals("android")) {
10602                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10603                                    + pkg.packageName + " attempting to redeclare permission "
10604                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10605                            res.origPermission = perm.info.name;
10606                            res.origPackage = bp.sourcePackage;
10607                            return;
10608                        } else {
10609                            Slog.w(TAG, "Package " + pkg.packageName
10610                                    + " attempting to redeclare system permission "
10611                                    + perm.info.name + "; ignoring new declaration");
10612                            pkg.permissions.remove(i);
10613                        }
10614                    }
10615                }
10616            }
10617
10618        }
10619
10620        if (systemApp && onSd) {
10621            // Disable updates to system apps on sdcard
10622            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10623                    "Cannot install updates to system apps on sdcard");
10624            return;
10625        }
10626
10627        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10628            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10629            return;
10630        }
10631
10632        if (replace) {
10633            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10634                    installerPackageName, res);
10635        } else {
10636            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10637                    args.user, installerPackageName, res);
10638        }
10639        synchronized (mPackages) {
10640            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10641            if (ps != null) {
10642                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10643            }
10644        }
10645    }
10646
10647    private static boolean isMultiArch(PackageSetting ps) {
10648        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10649    }
10650
10651    private static boolean isMultiArch(ApplicationInfo info) {
10652        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10653    }
10654
10655    private static boolean isExternal(PackageParser.Package pkg) {
10656        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10657    }
10658
10659    private static boolean isExternal(PackageSetting ps) {
10660        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10661    }
10662
10663    private static boolean isExternal(ApplicationInfo info) {
10664        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10665    }
10666
10667    private static boolean isSystemApp(PackageParser.Package pkg) {
10668        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10669    }
10670
10671    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10672        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
10673    }
10674
10675    private static boolean isSystemApp(ApplicationInfo info) {
10676        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10677    }
10678
10679    private static boolean isSystemApp(PackageSetting ps) {
10680        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10681    }
10682
10683    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10684        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10685    }
10686
10687    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10688        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10689    }
10690
10691    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10692        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10693    }
10694
10695    private int packageFlagsToInstallFlags(PackageSetting ps) {
10696        int installFlags = 0;
10697        if (isExternal(ps)) {
10698            installFlags |= PackageManager.INSTALL_EXTERNAL;
10699        }
10700        if (ps.isForwardLocked()) {
10701            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10702        }
10703        return installFlags;
10704    }
10705
10706    private void deleteTempPackageFiles() {
10707        final FilenameFilter filter = new FilenameFilter() {
10708            public boolean accept(File dir, String name) {
10709                return name.startsWith("vmdl") && name.endsWith(".tmp");
10710            }
10711        };
10712        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10713            file.delete();
10714        }
10715    }
10716
10717    @Override
10718    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10719            int flags) {
10720        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10721                flags);
10722    }
10723
10724    @Override
10725    public void deletePackage(final String packageName,
10726            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10727        mContext.enforceCallingOrSelfPermission(
10728                android.Manifest.permission.DELETE_PACKAGES, null);
10729        final int uid = Binder.getCallingUid();
10730        if (UserHandle.getUserId(uid) != userId) {
10731            mContext.enforceCallingPermission(
10732                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10733                    "deletePackage for user " + userId);
10734        }
10735        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10736            try {
10737                observer.onPackageDeleted(packageName,
10738                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10739            } catch (RemoteException re) {
10740            }
10741            return;
10742        }
10743
10744        boolean uninstallBlocked = false;
10745        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10746            int[] users = sUserManager.getUserIds();
10747            for (int i = 0; i < users.length; ++i) {
10748                if (getBlockUninstallForUser(packageName, users[i])) {
10749                    uninstallBlocked = true;
10750                    break;
10751                }
10752            }
10753        } else {
10754            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10755        }
10756        if (uninstallBlocked) {
10757            try {
10758                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10759                        null);
10760            } catch (RemoteException re) {
10761            }
10762            return;
10763        }
10764
10765        if (DEBUG_REMOVE) {
10766            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10767        }
10768        // Queue up an async operation since the package deletion may take a little while.
10769        mHandler.post(new Runnable() {
10770            public void run() {
10771                mHandler.removeCallbacks(this);
10772                final int returnCode = deletePackageX(packageName, userId, flags);
10773                if (observer != null) {
10774                    try {
10775                        observer.onPackageDeleted(packageName, returnCode, null);
10776                    } catch (RemoteException e) {
10777                        Log.i(TAG, "Observer no longer exists.");
10778                    } //end catch
10779                } //end if
10780            } //end run
10781        });
10782    }
10783
10784    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10785        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10786                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10787        try {
10788            if (dpm != null) {
10789                if (dpm.isDeviceOwner(packageName)) {
10790                    return true;
10791                }
10792                int[] users;
10793                if (userId == UserHandle.USER_ALL) {
10794                    users = sUserManager.getUserIds();
10795                } else {
10796                    users = new int[]{userId};
10797                }
10798                for (int i = 0; i < users.length; ++i) {
10799                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10800                        return true;
10801                    }
10802                }
10803            }
10804        } catch (RemoteException e) {
10805        }
10806        return false;
10807    }
10808
10809    /**
10810     *  This method is an internal method that could be get invoked either
10811     *  to delete an installed package or to clean up a failed installation.
10812     *  After deleting an installed package, a broadcast is sent to notify any
10813     *  listeners that the package has been installed. For cleaning up a failed
10814     *  installation, the broadcast is not necessary since the package's
10815     *  installation wouldn't have sent the initial broadcast either
10816     *  The key steps in deleting a package are
10817     *  deleting the package information in internal structures like mPackages,
10818     *  deleting the packages base directories through installd
10819     *  updating mSettings to reflect current status
10820     *  persisting settings for later use
10821     *  sending a broadcast if necessary
10822     */
10823    private int deletePackageX(String packageName, int userId, int flags) {
10824        final PackageRemovedInfo info = new PackageRemovedInfo();
10825        final boolean res;
10826
10827        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10828                ? UserHandle.ALL : new UserHandle(userId);
10829
10830        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10831            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10832            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10833        }
10834
10835        boolean removedForAllUsers = false;
10836        boolean systemUpdate = false;
10837
10838        // for the uninstall-updates case and restricted profiles, remember the per-
10839        // userhandle installed state
10840        int[] allUsers;
10841        boolean[] perUserInstalled;
10842        synchronized (mPackages) {
10843            PackageSetting ps = mSettings.mPackages.get(packageName);
10844            allUsers = sUserManager.getUserIds();
10845            perUserInstalled = new boolean[allUsers.length];
10846            for (int i = 0; i < allUsers.length; i++) {
10847                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10848            }
10849        }
10850
10851        synchronized (mInstallLock) {
10852            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10853            res = deletePackageLI(packageName, removeForUser,
10854                    true, allUsers, perUserInstalled,
10855                    flags | REMOVE_CHATTY, info, true);
10856            systemUpdate = info.isRemovedPackageSystemUpdate;
10857            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10858                removedForAllUsers = true;
10859            }
10860            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10861                    + " removedForAllUsers=" + removedForAllUsers);
10862        }
10863
10864        if (res) {
10865            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10866
10867            // If the removed package was a system update, the old system package
10868            // was re-enabled; we need to broadcast this information
10869            if (systemUpdate) {
10870                Bundle extras = new Bundle(1);
10871                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10872                        ? info.removedAppId : info.uid);
10873                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10874
10875                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10876                        extras, null, null, null);
10877                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10878                        extras, null, null, null);
10879                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10880                        null, packageName, null, null);
10881            }
10882        }
10883        // Force a gc here.
10884        Runtime.getRuntime().gc();
10885        // Delete the resources here after sending the broadcast to let
10886        // other processes clean up before deleting resources.
10887        if (info.args != null) {
10888            synchronized (mInstallLock) {
10889                info.args.doPostDeleteLI(true);
10890            }
10891        }
10892
10893        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10894    }
10895
10896    static class PackageRemovedInfo {
10897        String removedPackage;
10898        int uid = -1;
10899        int removedAppId = -1;
10900        int[] removedUsers = null;
10901        boolean isRemovedPackageSystemUpdate = false;
10902        // Clean up resources deleted packages.
10903        InstallArgs args = null;
10904
10905        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10906            Bundle extras = new Bundle(1);
10907            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10908            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10909            if (replacing) {
10910                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10911            }
10912            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10913            if (removedPackage != null) {
10914                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10915                        extras, null, null, removedUsers);
10916                if (fullRemove && !replacing) {
10917                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10918                            extras, null, null, removedUsers);
10919                }
10920            }
10921            if (removedAppId >= 0) {
10922                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10923                        removedUsers);
10924            }
10925        }
10926    }
10927
10928    /*
10929     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10930     * flag is not set, the data directory is removed as well.
10931     * make sure this flag is set for partially installed apps. If not its meaningless to
10932     * delete a partially installed application.
10933     */
10934    private void removePackageDataLI(PackageSetting ps,
10935            int[] allUserHandles, boolean[] perUserInstalled,
10936            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10937        String packageName = ps.name;
10938        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10939        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10940        // Retrieve object to delete permissions for shared user later on
10941        final PackageSetting deletedPs;
10942        // reader
10943        synchronized (mPackages) {
10944            deletedPs = mSettings.mPackages.get(packageName);
10945            if (outInfo != null) {
10946                outInfo.removedPackage = packageName;
10947                outInfo.removedUsers = deletedPs != null
10948                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10949                        : null;
10950            }
10951        }
10952        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10953            removeDataDirsLI(packageName);
10954            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10955        }
10956        // writer
10957        synchronized (mPackages) {
10958            if (deletedPs != null) {
10959                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10960                    if (outInfo != null) {
10961                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10962                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10963                    }
10964                    updatePermissionsLPw(deletedPs.name, null, 0);
10965                    if (deletedPs.sharedUser != null) {
10966                        // Remove permissions associated with package. Since runtime
10967                        // permissions are per user we have to kill the removed package
10968                        // or packages running under the shared user of the removed
10969                        // package if revoking the permissions requested only by the removed
10970                        // package is successful and this causes a change in gids.
10971                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10972                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
10973                                    userId);
10974                            if (userIdToKill == userId) {
10975                                // If gids changed for this user, kill all affected packages.
10976                                killSettingPackagesForUser(deletedPs, userIdToKill,
10977                                        KILL_APP_REASON_GIDS_CHANGED);
10978                            } else if (userIdToKill == UserHandle.USER_ALL) {
10979                                // If gids changed for all users, kill them all - done.
10980                                killSettingPackagesForUser(deletedPs, userIdToKill,
10981                                        KILL_APP_REASON_GIDS_CHANGED);
10982                                break;
10983                            }
10984                        }
10985                    }
10986                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10987                }
10988                // make sure to preserve per-user disabled state if this removal was just
10989                // a downgrade of a system app to the factory package
10990                if (allUserHandles != null && perUserInstalled != null) {
10991                    if (DEBUG_REMOVE) {
10992                        Slog.d(TAG, "Propagating install state across downgrade");
10993                    }
10994                    for (int i = 0; i < allUserHandles.length; i++) {
10995                        if (DEBUG_REMOVE) {
10996                            Slog.d(TAG, "    user " + allUserHandles[i]
10997                                    + " => " + perUserInstalled[i]);
10998                        }
10999                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11000                    }
11001                }
11002            }
11003            // can downgrade to reader
11004            if (writeSettings) {
11005                // Save settings now
11006                mSettings.writeLPr();
11007            }
11008        }
11009        if (outInfo != null) {
11010            // A user ID was deleted here. Go through all users and remove it
11011            // from KeyStore.
11012            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11013        }
11014    }
11015
11016    static boolean locationIsPrivileged(File path) {
11017        try {
11018            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11019                    .getCanonicalPath();
11020            return path.getCanonicalPath().startsWith(privilegedAppDir);
11021        } catch (IOException e) {
11022            Slog.e(TAG, "Unable to access code path " + path);
11023        }
11024        return false;
11025    }
11026
11027    /*
11028     * Tries to delete system package.
11029     */
11030    private boolean deleteSystemPackageLI(PackageSetting newPs,
11031            int[] allUserHandles, boolean[] perUserInstalled,
11032            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11033        final boolean applyUserRestrictions
11034                = (allUserHandles != null) && (perUserInstalled != null);
11035        PackageSetting disabledPs = null;
11036        // Confirm if the system package has been updated
11037        // An updated system app can be deleted. This will also have to restore
11038        // the system pkg from system partition
11039        // reader
11040        synchronized (mPackages) {
11041            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11042        }
11043        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11044                + " disabledPs=" + disabledPs);
11045        if (disabledPs == null) {
11046            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11047            return false;
11048        } else if (DEBUG_REMOVE) {
11049            Slog.d(TAG, "Deleting system pkg from data partition");
11050        }
11051        if (DEBUG_REMOVE) {
11052            if (applyUserRestrictions) {
11053                Slog.d(TAG, "Remembering install states:");
11054                for (int i = 0; i < allUserHandles.length; i++) {
11055                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11056                }
11057            }
11058        }
11059        // Delete the updated package
11060        outInfo.isRemovedPackageSystemUpdate = true;
11061        if (disabledPs.versionCode < newPs.versionCode) {
11062            // Delete data for downgrades
11063            flags &= ~PackageManager.DELETE_KEEP_DATA;
11064        } else {
11065            // Preserve data by setting flag
11066            flags |= PackageManager.DELETE_KEEP_DATA;
11067        }
11068        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11069                allUserHandles, perUserInstalled, outInfo, writeSettings);
11070        if (!ret) {
11071            return false;
11072        }
11073        // writer
11074        synchronized (mPackages) {
11075            // Reinstate the old system package
11076            mSettings.enableSystemPackageLPw(newPs.name);
11077            // Remove any native libraries from the upgraded package.
11078            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11079        }
11080        // Install the system package
11081        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11082        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11083        if (locationIsPrivileged(disabledPs.codePath)) {
11084            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11085        }
11086
11087        final PackageParser.Package newPkg;
11088        try {
11089            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11090        } catch (PackageManagerException e) {
11091            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11092            return false;
11093        }
11094
11095        // writer
11096        synchronized (mPackages) {
11097            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11098            updatePermissionsLPw(newPkg.packageName, newPkg,
11099                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11100            if (applyUserRestrictions) {
11101                if (DEBUG_REMOVE) {
11102                    Slog.d(TAG, "Propagating install state across reinstall");
11103                }
11104                for (int i = 0; i < allUserHandles.length; i++) {
11105                    if (DEBUG_REMOVE) {
11106                        Slog.d(TAG, "    user " + allUserHandles[i]
11107                                + " => " + perUserInstalled[i]);
11108                    }
11109                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11110                }
11111                // Regardless of writeSettings we need to ensure that this restriction
11112                // state propagation is persisted
11113                mSettings.writeAllUsersPackageRestrictionsLPr();
11114            }
11115            // can downgrade to reader here
11116            if (writeSettings) {
11117                mSettings.writeLPr();
11118            }
11119        }
11120        return true;
11121    }
11122
11123    private boolean deleteInstalledPackageLI(PackageSetting ps,
11124            boolean deleteCodeAndResources, int flags,
11125            int[] allUserHandles, boolean[] perUserInstalled,
11126            PackageRemovedInfo outInfo, boolean writeSettings) {
11127        if (outInfo != null) {
11128            outInfo.uid = ps.appId;
11129        }
11130
11131        // Delete package data from internal structures and also remove data if flag is set
11132        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11133
11134        // Delete application code and resources
11135        if (deleteCodeAndResources && (outInfo != null)) {
11136            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11137                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11138                    getAppDexInstructionSets(ps));
11139            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11140        }
11141        return true;
11142    }
11143
11144    @Override
11145    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11146            int userId) {
11147        mContext.enforceCallingOrSelfPermission(
11148                android.Manifest.permission.DELETE_PACKAGES, null);
11149        synchronized (mPackages) {
11150            PackageSetting ps = mSettings.mPackages.get(packageName);
11151            if (ps == null) {
11152                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11153                return false;
11154            }
11155            if (!ps.getInstalled(userId)) {
11156                // Can't block uninstall for an app that is not installed or enabled.
11157                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11158                return false;
11159            }
11160            ps.setBlockUninstall(blockUninstall, userId);
11161            mSettings.writePackageRestrictionsLPr(userId);
11162        }
11163        return true;
11164    }
11165
11166    @Override
11167    public boolean getBlockUninstallForUser(String packageName, int userId) {
11168        synchronized (mPackages) {
11169            PackageSetting ps = mSettings.mPackages.get(packageName);
11170            if (ps == null) {
11171                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11172                return false;
11173            }
11174            return ps.getBlockUninstall(userId);
11175        }
11176    }
11177
11178    /*
11179     * This method handles package deletion in general
11180     */
11181    private boolean deletePackageLI(String packageName, UserHandle user,
11182            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11183            int flags, PackageRemovedInfo outInfo,
11184            boolean writeSettings) {
11185        if (packageName == null) {
11186            Slog.w(TAG, "Attempt to delete null packageName.");
11187            return false;
11188        }
11189        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11190        PackageSetting ps;
11191        boolean dataOnly = false;
11192        int removeUser = -1;
11193        int appId = -1;
11194        synchronized (mPackages) {
11195            ps = mSettings.mPackages.get(packageName);
11196            if (ps == null) {
11197                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11198                return false;
11199            }
11200            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11201                    && user.getIdentifier() != UserHandle.USER_ALL) {
11202                // The caller is asking that the package only be deleted for a single
11203                // user.  To do this, we just mark its uninstalled state and delete
11204                // its data.  If this is a system app, we only allow this to happen if
11205                // they have set the special DELETE_SYSTEM_APP which requests different
11206                // semantics than normal for uninstalling system apps.
11207                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11208                ps.setUserState(user.getIdentifier(),
11209                        COMPONENT_ENABLED_STATE_DEFAULT,
11210                        false, //installed
11211                        true,  //stopped
11212                        true,  //notLaunched
11213                        false, //hidden
11214                        null, null, null,
11215                        false // blockUninstall
11216                        );
11217                if (!isSystemApp(ps)) {
11218                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11219                        // Other user still have this package installed, so all
11220                        // we need to do is clear this user's data and save that
11221                        // it is uninstalled.
11222                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11223                        removeUser = user.getIdentifier();
11224                        appId = ps.appId;
11225                        mSettings.writePackageRestrictionsLPr(removeUser);
11226                    } else {
11227                        // We need to set it back to 'installed' so the uninstall
11228                        // broadcasts will be sent correctly.
11229                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11230                        ps.setInstalled(true, user.getIdentifier());
11231                    }
11232                } else {
11233                    // This is a system app, so we assume that the
11234                    // other users still have this package installed, so all
11235                    // we need to do is clear this user's data and save that
11236                    // it is uninstalled.
11237                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11238                    removeUser = user.getIdentifier();
11239                    appId = ps.appId;
11240                    mSettings.writePackageRestrictionsLPr(removeUser);
11241                }
11242            }
11243        }
11244
11245        if (removeUser >= 0) {
11246            // From above, we determined that we are deleting this only
11247            // for a single user.  Continue the work here.
11248            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11249            if (outInfo != null) {
11250                outInfo.removedPackage = packageName;
11251                outInfo.removedAppId = appId;
11252                outInfo.removedUsers = new int[] {removeUser};
11253            }
11254            mInstaller.clearUserData(packageName, removeUser);
11255            removeKeystoreDataIfNeeded(removeUser, appId);
11256            schedulePackageCleaning(packageName, removeUser, false);
11257            return true;
11258        }
11259
11260        if (dataOnly) {
11261            // Delete application data first
11262            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11263            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11264            return true;
11265        }
11266
11267        boolean ret = false;
11268        if (isSystemApp(ps)) {
11269            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11270            // When an updated system application is deleted we delete the existing resources as well and
11271            // fall back to existing code in system partition
11272            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11273                    flags, outInfo, writeSettings);
11274        } else {
11275            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11276            // Kill application pre-emptively especially for apps on sd.
11277            killApplication(packageName, ps.appId, "uninstall pkg");
11278            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11279                    allUserHandles, perUserInstalled,
11280                    outInfo, writeSettings);
11281        }
11282
11283        return ret;
11284    }
11285
11286    private final class ClearStorageConnection implements ServiceConnection {
11287        IMediaContainerService mContainerService;
11288
11289        @Override
11290        public void onServiceConnected(ComponentName name, IBinder service) {
11291            synchronized (this) {
11292                mContainerService = IMediaContainerService.Stub.asInterface(service);
11293                notifyAll();
11294            }
11295        }
11296
11297        @Override
11298        public void onServiceDisconnected(ComponentName name) {
11299        }
11300    }
11301
11302    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11303        final boolean mounted;
11304        if (Environment.isExternalStorageEmulated()) {
11305            mounted = true;
11306        } else {
11307            final String status = Environment.getExternalStorageState();
11308
11309            mounted = status.equals(Environment.MEDIA_MOUNTED)
11310                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11311        }
11312
11313        if (!mounted) {
11314            return;
11315        }
11316
11317        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11318        int[] users;
11319        if (userId == UserHandle.USER_ALL) {
11320            users = sUserManager.getUserIds();
11321        } else {
11322            users = new int[] { userId };
11323        }
11324        final ClearStorageConnection conn = new ClearStorageConnection();
11325        if (mContext.bindServiceAsUser(
11326                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11327            try {
11328                for (int curUser : users) {
11329                    long timeout = SystemClock.uptimeMillis() + 5000;
11330                    synchronized (conn) {
11331                        long now = SystemClock.uptimeMillis();
11332                        while (conn.mContainerService == null && now < timeout) {
11333                            try {
11334                                conn.wait(timeout - now);
11335                            } catch (InterruptedException e) {
11336                            }
11337                        }
11338                    }
11339                    if (conn.mContainerService == null) {
11340                        return;
11341                    }
11342
11343                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11344                    clearDirectory(conn.mContainerService,
11345                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11346                    if (allData) {
11347                        clearDirectory(conn.mContainerService,
11348                                userEnv.buildExternalStorageAppDataDirs(packageName));
11349                        clearDirectory(conn.mContainerService,
11350                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11351                    }
11352                }
11353            } finally {
11354                mContext.unbindService(conn);
11355            }
11356        }
11357    }
11358
11359    @Override
11360    public void clearApplicationUserData(final String packageName,
11361            final IPackageDataObserver observer, final int userId) {
11362        mContext.enforceCallingOrSelfPermission(
11363                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11364        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11365        // Queue up an async operation since the package deletion may take a little while.
11366        mHandler.post(new Runnable() {
11367            public void run() {
11368                mHandler.removeCallbacks(this);
11369                final boolean succeeded;
11370                synchronized (mInstallLock) {
11371                    succeeded = clearApplicationUserDataLI(packageName, userId);
11372                }
11373                clearExternalStorageDataSync(packageName, userId, true);
11374                if (succeeded) {
11375                    // invoke DeviceStorageMonitor's update method to clear any notifications
11376                    DeviceStorageMonitorInternal
11377                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11378                    if (dsm != null) {
11379                        dsm.checkMemory();
11380                    }
11381                }
11382                if(observer != null) {
11383                    try {
11384                        observer.onRemoveCompleted(packageName, succeeded);
11385                    } catch (RemoteException e) {
11386                        Log.i(TAG, "Observer no longer exists.");
11387                    }
11388                } //end if observer
11389            } //end run
11390        });
11391    }
11392
11393    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11394        if (packageName == null) {
11395            Slog.w(TAG, "Attempt to delete null packageName.");
11396            return false;
11397        }
11398
11399        // Try finding details about the requested package
11400        PackageParser.Package pkg;
11401        synchronized (mPackages) {
11402            pkg = mPackages.get(packageName);
11403            if (pkg == null) {
11404                final PackageSetting ps = mSettings.mPackages.get(packageName);
11405                if (ps != null) {
11406                    pkg = ps.pkg;
11407                }
11408            }
11409        }
11410
11411        if (pkg == null) {
11412            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11413        }
11414
11415        // Always delete data directories for package, even if we found no other
11416        // record of app. This helps users recover from UID mismatches without
11417        // resorting to a full data wipe.
11418        int retCode = mInstaller.clearUserData(packageName, userId);
11419        if (retCode < 0) {
11420            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11421            return false;
11422        }
11423
11424        if (pkg == null) {
11425            return false;
11426        }
11427
11428        if (pkg != null && pkg.applicationInfo != null) {
11429            final int appId = pkg.applicationInfo.uid;
11430            removeKeystoreDataIfNeeded(userId, appId);
11431        }
11432
11433        // Create a native library symlink only if we have native libraries
11434        // and if the native libraries are 32 bit libraries. We do not provide
11435        // this symlink for 64 bit libraries.
11436        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11437                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11438            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11439            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11440                Slog.w(TAG, "Failed linking native library dir");
11441                return false;
11442            }
11443        }
11444
11445        return true;
11446    }
11447
11448    /**
11449     * Remove entries from the keystore daemon. Will only remove it if the
11450     * {@code appId} is valid.
11451     */
11452    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11453        if (appId < 0) {
11454            return;
11455        }
11456
11457        final KeyStore keyStore = KeyStore.getInstance();
11458        if (keyStore != null) {
11459            if (userId == UserHandle.USER_ALL) {
11460                for (final int individual : sUserManager.getUserIds()) {
11461                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11462                }
11463            } else {
11464                keyStore.clearUid(UserHandle.getUid(userId, appId));
11465            }
11466        } else {
11467            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11468        }
11469    }
11470
11471    @Override
11472    public void deleteApplicationCacheFiles(final String packageName,
11473            final IPackageDataObserver observer) {
11474        mContext.enforceCallingOrSelfPermission(
11475                android.Manifest.permission.DELETE_CACHE_FILES, null);
11476        // Queue up an async operation since the package deletion may take a little while.
11477        final int userId = UserHandle.getCallingUserId();
11478        mHandler.post(new Runnable() {
11479            public void run() {
11480                mHandler.removeCallbacks(this);
11481                final boolean succeded;
11482                synchronized (mInstallLock) {
11483                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11484                }
11485                clearExternalStorageDataSync(packageName, userId, false);
11486                if(observer != null) {
11487                    try {
11488                        observer.onRemoveCompleted(packageName, succeded);
11489                    } catch (RemoteException e) {
11490                        Log.i(TAG, "Observer no longer exists.");
11491                    }
11492                } //end if observer
11493            } //end run
11494        });
11495    }
11496
11497    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11498        if (packageName == null) {
11499            Slog.w(TAG, "Attempt to delete null packageName.");
11500            return false;
11501        }
11502        PackageParser.Package p;
11503        synchronized (mPackages) {
11504            p = mPackages.get(packageName);
11505        }
11506        if (p == null) {
11507            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11508            return false;
11509        }
11510        final ApplicationInfo applicationInfo = p.applicationInfo;
11511        if (applicationInfo == null) {
11512            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11513            return false;
11514        }
11515        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11516        if (retCode < 0) {
11517            Slog.w(TAG, "Couldn't remove cache files for package: "
11518                       + packageName + " u" + userId);
11519            return false;
11520        }
11521        return true;
11522    }
11523
11524    @Override
11525    public void getPackageSizeInfo(final String packageName, int userHandle,
11526            final IPackageStatsObserver observer) {
11527        mContext.enforceCallingOrSelfPermission(
11528                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11529        if (packageName == null) {
11530            throw new IllegalArgumentException("Attempt to get size of null packageName");
11531        }
11532
11533        PackageStats stats = new PackageStats(packageName, userHandle);
11534
11535        /*
11536         * Queue up an async operation since the package measurement may take a
11537         * little while.
11538         */
11539        Message msg = mHandler.obtainMessage(INIT_COPY);
11540        msg.obj = new MeasureParams(stats, observer);
11541        mHandler.sendMessage(msg);
11542    }
11543
11544    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11545            PackageStats pStats) {
11546        if (packageName == null) {
11547            Slog.w(TAG, "Attempt to get size of null packageName.");
11548            return false;
11549        }
11550        PackageParser.Package p;
11551        boolean dataOnly = false;
11552        String libDirRoot = null;
11553        String asecPath = null;
11554        PackageSetting ps = null;
11555        synchronized (mPackages) {
11556            p = mPackages.get(packageName);
11557            ps = mSettings.mPackages.get(packageName);
11558            if(p == null) {
11559                dataOnly = true;
11560                if((ps == null) || (ps.pkg == null)) {
11561                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11562                    return false;
11563                }
11564                p = ps.pkg;
11565            }
11566            if (ps != null) {
11567                libDirRoot = ps.legacyNativeLibraryPathString;
11568            }
11569            if (p != null && (isExternal(p) || p.isForwardLocked())) {
11570                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11571                if (secureContainerId != null) {
11572                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11573                }
11574            }
11575        }
11576        String publicSrcDir = null;
11577        if(!dataOnly) {
11578            final ApplicationInfo applicationInfo = p.applicationInfo;
11579            if (applicationInfo == null) {
11580                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11581                return false;
11582            }
11583            if (p.isForwardLocked()) {
11584                publicSrcDir = applicationInfo.getBaseResourcePath();
11585            }
11586        }
11587        // TODO: extend to measure size of split APKs
11588        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11589        // not just the first level.
11590        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11591        // just the primary.
11592        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11593        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11594                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11595        if (res < 0) {
11596            return false;
11597        }
11598
11599        // Fix-up for forward-locked applications in ASEC containers.
11600        if (!isExternal(p)) {
11601            pStats.codeSize += pStats.externalCodeSize;
11602            pStats.externalCodeSize = 0L;
11603        }
11604
11605        return true;
11606    }
11607
11608
11609    @Override
11610    public void addPackageToPreferred(String packageName) {
11611        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11612    }
11613
11614    @Override
11615    public void removePackageFromPreferred(String packageName) {
11616        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11617    }
11618
11619    @Override
11620    public List<PackageInfo> getPreferredPackages(int flags) {
11621        return new ArrayList<PackageInfo>();
11622    }
11623
11624    private int getUidTargetSdkVersionLockedLPr(int uid) {
11625        Object obj = mSettings.getUserIdLPr(uid);
11626        if (obj instanceof SharedUserSetting) {
11627            final SharedUserSetting sus = (SharedUserSetting) obj;
11628            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11629            final Iterator<PackageSetting> it = sus.packages.iterator();
11630            while (it.hasNext()) {
11631                final PackageSetting ps = it.next();
11632                if (ps.pkg != null) {
11633                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11634                    if (v < vers) vers = v;
11635                }
11636            }
11637            return vers;
11638        } else if (obj instanceof PackageSetting) {
11639            final PackageSetting ps = (PackageSetting) obj;
11640            if (ps.pkg != null) {
11641                return ps.pkg.applicationInfo.targetSdkVersion;
11642            }
11643        }
11644        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11645    }
11646
11647    @Override
11648    public void addPreferredActivity(IntentFilter filter, int match,
11649            ComponentName[] set, ComponentName activity, int userId) {
11650        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11651                "Adding preferred");
11652    }
11653
11654    private void addPreferredActivityInternal(IntentFilter filter, int match,
11655            ComponentName[] set, ComponentName activity, boolean always, int userId,
11656            String opname) {
11657        // writer
11658        int callingUid = Binder.getCallingUid();
11659        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11660        if (filter.countActions() == 0) {
11661            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11662            return;
11663        }
11664        synchronized (mPackages) {
11665            if (mContext.checkCallingOrSelfPermission(
11666                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11667                    != PackageManager.PERMISSION_GRANTED) {
11668                if (getUidTargetSdkVersionLockedLPr(callingUid)
11669                        < Build.VERSION_CODES.FROYO) {
11670                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11671                            + callingUid);
11672                    return;
11673                }
11674                mContext.enforceCallingOrSelfPermission(
11675                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11676            }
11677
11678            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11679            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11680                    + userId + ":");
11681            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11682            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11683            scheduleWritePackageRestrictionsLocked(userId);
11684        }
11685    }
11686
11687    @Override
11688    public void replacePreferredActivity(IntentFilter filter, int match,
11689            ComponentName[] set, ComponentName activity, int userId) {
11690        if (filter.countActions() != 1) {
11691            throw new IllegalArgumentException(
11692                    "replacePreferredActivity expects filter to have only 1 action.");
11693        }
11694        if (filter.countDataAuthorities() != 0
11695                || filter.countDataPaths() != 0
11696                || filter.countDataSchemes() > 1
11697                || filter.countDataTypes() != 0) {
11698            throw new IllegalArgumentException(
11699                    "replacePreferredActivity expects filter to have no data authorities, " +
11700                    "paths, or types; and at most one scheme.");
11701        }
11702
11703        final int callingUid = Binder.getCallingUid();
11704        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11705        synchronized (mPackages) {
11706            if (mContext.checkCallingOrSelfPermission(
11707                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11708                    != PackageManager.PERMISSION_GRANTED) {
11709                if (getUidTargetSdkVersionLockedLPr(callingUid)
11710                        < Build.VERSION_CODES.FROYO) {
11711                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11712                            + Binder.getCallingUid());
11713                    return;
11714                }
11715                mContext.enforceCallingOrSelfPermission(
11716                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11717            }
11718
11719            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11720            if (pir != null) {
11721                // Get all of the existing entries that exactly match this filter.
11722                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11723                if (existing != null && existing.size() == 1) {
11724                    PreferredActivity cur = existing.get(0);
11725                    if (DEBUG_PREFERRED) {
11726                        Slog.i(TAG, "Checking replace of preferred:");
11727                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11728                        if (!cur.mPref.mAlways) {
11729                            Slog.i(TAG, "  -- CUR; not mAlways!");
11730                        } else {
11731                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11732                            Slog.i(TAG, "  -- CUR: mSet="
11733                                    + Arrays.toString(cur.mPref.mSetComponents));
11734                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11735                            Slog.i(TAG, "  -- NEW: mMatch="
11736                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11737                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11738                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11739                        }
11740                    }
11741                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11742                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11743                            && cur.mPref.sameSet(set)) {
11744                        // Setting the preferred activity to what it happens to be already
11745                        if (DEBUG_PREFERRED) {
11746                            Slog.i(TAG, "Replacing with same preferred activity "
11747                                    + cur.mPref.mShortComponent + " for user "
11748                                    + userId + ":");
11749                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11750                        }
11751                        return;
11752                    }
11753                }
11754
11755                if (existing != null) {
11756                    if (DEBUG_PREFERRED) {
11757                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11758                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11759                    }
11760                    for (int i = 0; i < existing.size(); i++) {
11761                        PreferredActivity pa = existing.get(i);
11762                        if (DEBUG_PREFERRED) {
11763                            Slog.i(TAG, "Removing existing preferred activity "
11764                                    + pa.mPref.mComponent + ":");
11765                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11766                        }
11767                        pir.removeFilter(pa);
11768                    }
11769                }
11770            }
11771            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11772                    "Replacing preferred");
11773        }
11774    }
11775
11776    @Override
11777    public void clearPackagePreferredActivities(String packageName) {
11778        final int uid = Binder.getCallingUid();
11779        // writer
11780        synchronized (mPackages) {
11781            PackageParser.Package pkg = mPackages.get(packageName);
11782            if (pkg == null || pkg.applicationInfo.uid != uid) {
11783                if (mContext.checkCallingOrSelfPermission(
11784                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11785                        != PackageManager.PERMISSION_GRANTED) {
11786                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11787                            < Build.VERSION_CODES.FROYO) {
11788                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11789                                + Binder.getCallingUid());
11790                        return;
11791                    }
11792                    mContext.enforceCallingOrSelfPermission(
11793                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11794                }
11795            }
11796
11797            int user = UserHandle.getCallingUserId();
11798            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11799                scheduleWritePackageRestrictionsLocked(user);
11800            }
11801        }
11802    }
11803
11804    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11805    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11806        ArrayList<PreferredActivity> removed = null;
11807        boolean changed = false;
11808        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11809            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11810            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11811            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11812                continue;
11813            }
11814            Iterator<PreferredActivity> it = pir.filterIterator();
11815            while (it.hasNext()) {
11816                PreferredActivity pa = it.next();
11817                // Mark entry for removal only if it matches the package name
11818                // and the entry is of type "always".
11819                if (packageName == null ||
11820                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11821                                && pa.mPref.mAlways)) {
11822                    if (removed == null) {
11823                        removed = new ArrayList<PreferredActivity>();
11824                    }
11825                    removed.add(pa);
11826                }
11827            }
11828            if (removed != null) {
11829                for (int j=0; j<removed.size(); j++) {
11830                    PreferredActivity pa = removed.get(j);
11831                    pir.removeFilter(pa);
11832                }
11833                changed = true;
11834            }
11835        }
11836        return changed;
11837    }
11838
11839    @Override
11840    public void resetPreferredActivities(int userId) {
11841        /* TODO: Actually use userId. Why is it being passed in? */
11842        mContext.enforceCallingOrSelfPermission(
11843                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11844        // writer
11845        synchronized (mPackages) {
11846            int user = UserHandle.getCallingUserId();
11847            clearPackagePreferredActivitiesLPw(null, user);
11848            mSettings.readDefaultPreferredAppsLPw(this, user);
11849            scheduleWritePackageRestrictionsLocked(user);
11850        }
11851    }
11852
11853    @Override
11854    public int getPreferredActivities(List<IntentFilter> outFilters,
11855            List<ComponentName> outActivities, String packageName) {
11856
11857        int num = 0;
11858        final int userId = UserHandle.getCallingUserId();
11859        // reader
11860        synchronized (mPackages) {
11861            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11862            if (pir != null) {
11863                final Iterator<PreferredActivity> it = pir.filterIterator();
11864                while (it.hasNext()) {
11865                    final PreferredActivity pa = it.next();
11866                    if (packageName == null
11867                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11868                                    && pa.mPref.mAlways)) {
11869                        if (outFilters != null) {
11870                            outFilters.add(new IntentFilter(pa));
11871                        }
11872                        if (outActivities != null) {
11873                            outActivities.add(pa.mPref.mComponent);
11874                        }
11875                    }
11876                }
11877            }
11878        }
11879
11880        return num;
11881    }
11882
11883    @Override
11884    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11885            int userId) {
11886        int callingUid = Binder.getCallingUid();
11887        if (callingUid != Process.SYSTEM_UID) {
11888            throw new SecurityException(
11889                    "addPersistentPreferredActivity can only be run by the system");
11890        }
11891        if (filter.countActions() == 0) {
11892            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11893            return;
11894        }
11895        synchronized (mPackages) {
11896            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11897                    " :");
11898            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11899            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11900                    new PersistentPreferredActivity(filter, activity));
11901            scheduleWritePackageRestrictionsLocked(userId);
11902        }
11903    }
11904
11905    @Override
11906    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11907        int callingUid = Binder.getCallingUid();
11908        if (callingUid != Process.SYSTEM_UID) {
11909            throw new SecurityException(
11910                    "clearPackagePersistentPreferredActivities can only be run by the system");
11911        }
11912        ArrayList<PersistentPreferredActivity> removed = null;
11913        boolean changed = false;
11914        synchronized (mPackages) {
11915            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11916                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11917                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11918                        .valueAt(i);
11919                if (userId != thisUserId) {
11920                    continue;
11921                }
11922                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11923                while (it.hasNext()) {
11924                    PersistentPreferredActivity ppa = it.next();
11925                    // Mark entry for removal only if it matches the package name.
11926                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11927                        if (removed == null) {
11928                            removed = new ArrayList<PersistentPreferredActivity>();
11929                        }
11930                        removed.add(ppa);
11931                    }
11932                }
11933                if (removed != null) {
11934                    for (int j=0; j<removed.size(); j++) {
11935                        PersistentPreferredActivity ppa = removed.get(j);
11936                        ppir.removeFilter(ppa);
11937                    }
11938                    changed = true;
11939                }
11940            }
11941
11942            if (changed) {
11943                scheduleWritePackageRestrictionsLocked(userId);
11944            }
11945        }
11946    }
11947
11948    @Override
11949    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11950            int sourceUserId, int targetUserId, int flags) {
11951        mContext.enforceCallingOrSelfPermission(
11952                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11953        int callingUid = Binder.getCallingUid();
11954        enforceOwnerRights(ownerPackage, callingUid);
11955        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11956        if (intentFilter.countActions() == 0) {
11957            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11958            return;
11959        }
11960        synchronized (mPackages) {
11961            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
11962                    ownerPackage, targetUserId, flags);
11963            CrossProfileIntentResolver resolver =
11964                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11965            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
11966            // We have all those whose filter is equal. Now checking if the rest is equal as well.
11967            if (existing != null) {
11968                int size = existing.size();
11969                for (int i = 0; i < size; i++) {
11970                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
11971                        return;
11972                    }
11973                }
11974            }
11975            resolver.addFilter(newFilter);
11976            scheduleWritePackageRestrictionsLocked(sourceUserId);
11977        }
11978    }
11979
11980    @Override
11981    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
11982        mContext.enforceCallingOrSelfPermission(
11983                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11984        int callingUid = Binder.getCallingUid();
11985        enforceOwnerRights(ownerPackage, callingUid);
11986        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11987        synchronized (mPackages) {
11988            CrossProfileIntentResolver resolver =
11989                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11990            ArraySet<CrossProfileIntentFilter> set =
11991                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
11992            for (CrossProfileIntentFilter filter : set) {
11993                if (filter.getOwnerPackage().equals(ownerPackage)) {
11994                    resolver.removeFilter(filter);
11995                }
11996            }
11997            scheduleWritePackageRestrictionsLocked(sourceUserId);
11998        }
11999    }
12000
12001    // Enforcing that callingUid is owning pkg on userId
12002    private void enforceOwnerRights(String pkg, int callingUid) {
12003        // The system owns everything.
12004        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12005            return;
12006        }
12007        int callingUserId = UserHandle.getUserId(callingUid);
12008        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12009        if (pi == null) {
12010            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12011                    + callingUserId);
12012        }
12013        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12014            throw new SecurityException("Calling uid " + callingUid
12015                    + " does not own package " + pkg);
12016        }
12017    }
12018
12019    @Override
12020    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12021        Intent intent = new Intent(Intent.ACTION_MAIN);
12022        intent.addCategory(Intent.CATEGORY_HOME);
12023
12024        final int callingUserId = UserHandle.getCallingUserId();
12025        List<ResolveInfo> list = queryIntentActivities(intent, null,
12026                PackageManager.GET_META_DATA, callingUserId);
12027        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12028                true, false, false, callingUserId);
12029
12030        allHomeCandidates.clear();
12031        if (list != null) {
12032            for (ResolveInfo ri : list) {
12033                allHomeCandidates.add(ri);
12034            }
12035        }
12036        return (preferred == null || preferred.activityInfo == null)
12037                ? null
12038                : new ComponentName(preferred.activityInfo.packageName,
12039                        preferred.activityInfo.name);
12040    }
12041
12042    @Override
12043    public void setApplicationEnabledSetting(String appPackageName,
12044            int newState, int flags, int userId, String callingPackage) {
12045        if (!sUserManager.exists(userId)) return;
12046        if (callingPackage == null) {
12047            callingPackage = Integer.toString(Binder.getCallingUid());
12048        }
12049        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12050    }
12051
12052    @Override
12053    public void setComponentEnabledSetting(ComponentName componentName,
12054            int newState, int flags, int userId) {
12055        if (!sUserManager.exists(userId)) return;
12056        setEnabledSetting(componentName.getPackageName(),
12057                componentName.getClassName(), newState, flags, userId, null);
12058    }
12059
12060    private void setEnabledSetting(final String packageName, String className, int newState,
12061            final int flags, int userId, String callingPackage) {
12062        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12063              || newState == COMPONENT_ENABLED_STATE_ENABLED
12064              || newState == COMPONENT_ENABLED_STATE_DISABLED
12065              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12066              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12067            throw new IllegalArgumentException("Invalid new component state: "
12068                    + newState);
12069        }
12070        PackageSetting pkgSetting;
12071        final int uid = Binder.getCallingUid();
12072        final int permission = mContext.checkCallingOrSelfPermission(
12073                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12074        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12075        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12076        boolean sendNow = false;
12077        boolean isApp = (className == null);
12078        String componentName = isApp ? packageName : className;
12079        int packageUid = -1;
12080        ArrayList<String> components;
12081
12082        // writer
12083        synchronized (mPackages) {
12084            pkgSetting = mSettings.mPackages.get(packageName);
12085            if (pkgSetting == null) {
12086                if (className == null) {
12087                    throw new IllegalArgumentException(
12088                            "Unknown package: " + packageName);
12089                }
12090                throw new IllegalArgumentException(
12091                        "Unknown component: " + packageName
12092                        + "/" + className);
12093            }
12094            // Allow root and verify that userId is not being specified by a different user
12095            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12096                throw new SecurityException(
12097                        "Permission Denial: attempt to change component state from pid="
12098                        + Binder.getCallingPid()
12099                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12100            }
12101            if (className == null) {
12102                // We're dealing with an application/package level state change
12103                if (pkgSetting.getEnabled(userId) == newState) {
12104                    // Nothing to do
12105                    return;
12106                }
12107                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12108                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12109                    // Don't care about who enables an app.
12110                    callingPackage = null;
12111                }
12112                pkgSetting.setEnabled(newState, userId, callingPackage);
12113                // pkgSetting.pkg.mSetEnabled = newState;
12114            } else {
12115                // We're dealing with a component level state change
12116                // First, verify that this is a valid class name.
12117                PackageParser.Package pkg = pkgSetting.pkg;
12118                if (pkg == null || !pkg.hasComponentClassName(className)) {
12119                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12120                        throw new IllegalArgumentException("Component class " + className
12121                                + " does not exist in " + packageName);
12122                    } else {
12123                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12124                                + className + " does not exist in " + packageName);
12125                    }
12126                }
12127                switch (newState) {
12128                case COMPONENT_ENABLED_STATE_ENABLED:
12129                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12130                        return;
12131                    }
12132                    break;
12133                case COMPONENT_ENABLED_STATE_DISABLED:
12134                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12135                        return;
12136                    }
12137                    break;
12138                case COMPONENT_ENABLED_STATE_DEFAULT:
12139                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12140                        return;
12141                    }
12142                    break;
12143                default:
12144                    Slog.e(TAG, "Invalid new component state: " + newState);
12145                    return;
12146                }
12147            }
12148            scheduleWritePackageRestrictionsLocked(userId);
12149            components = mPendingBroadcasts.get(userId, packageName);
12150            final boolean newPackage = components == null;
12151            if (newPackage) {
12152                components = new ArrayList<String>();
12153            }
12154            if (!components.contains(componentName)) {
12155                components.add(componentName);
12156            }
12157            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12158                sendNow = true;
12159                // Purge entry from pending broadcast list if another one exists already
12160                // since we are sending one right away.
12161                mPendingBroadcasts.remove(userId, packageName);
12162            } else {
12163                if (newPackage) {
12164                    mPendingBroadcasts.put(userId, packageName, components);
12165                }
12166                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12167                    // Schedule a message
12168                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12169                }
12170            }
12171        }
12172
12173        long callingId = Binder.clearCallingIdentity();
12174        try {
12175            if (sendNow) {
12176                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12177                sendPackageChangedBroadcast(packageName,
12178                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12179            }
12180        } finally {
12181            Binder.restoreCallingIdentity(callingId);
12182        }
12183    }
12184
12185    private void sendPackageChangedBroadcast(String packageName,
12186            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12187        if (DEBUG_INSTALL)
12188            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12189                    + componentNames);
12190        Bundle extras = new Bundle(4);
12191        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12192        String nameList[] = new String[componentNames.size()];
12193        componentNames.toArray(nameList);
12194        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12195        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12196        extras.putInt(Intent.EXTRA_UID, packageUid);
12197        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12198                new int[] {UserHandle.getUserId(packageUid)});
12199    }
12200
12201    @Override
12202    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12203        if (!sUserManager.exists(userId)) return;
12204        final int uid = Binder.getCallingUid();
12205        final int permission = mContext.checkCallingOrSelfPermission(
12206                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12207        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12208        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12209        // writer
12210        synchronized (mPackages) {
12211            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12212                    uid, userId)) {
12213                scheduleWritePackageRestrictionsLocked(userId);
12214            }
12215        }
12216    }
12217
12218    @Override
12219    public String getInstallerPackageName(String packageName) {
12220        // reader
12221        synchronized (mPackages) {
12222            return mSettings.getInstallerPackageNameLPr(packageName);
12223        }
12224    }
12225
12226    @Override
12227    public int getApplicationEnabledSetting(String packageName, int userId) {
12228        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12229        int uid = Binder.getCallingUid();
12230        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12231        // reader
12232        synchronized (mPackages) {
12233            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12234        }
12235    }
12236
12237    @Override
12238    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12239        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12240        int uid = Binder.getCallingUid();
12241        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12242        // reader
12243        synchronized (mPackages) {
12244            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12245        }
12246    }
12247
12248    @Override
12249    public void enterSafeMode() {
12250        enforceSystemOrRoot("Only the system can request entering safe mode");
12251
12252        if (!mSystemReady) {
12253            mSafeMode = true;
12254        }
12255    }
12256
12257    @Override
12258    public void systemReady() {
12259        mSystemReady = true;
12260
12261        // Read the compatibilty setting when the system is ready.
12262        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12263                mContext.getContentResolver(),
12264                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12265        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12266        if (DEBUG_SETTINGS) {
12267            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12268        }
12269
12270        synchronized (mPackages) {
12271            // Verify that all of the preferred activity components actually
12272            // exist.  It is possible for applications to be updated and at
12273            // that point remove a previously declared activity component that
12274            // had been set as a preferred activity.  We try to clean this up
12275            // the next time we encounter that preferred activity, but it is
12276            // possible for the user flow to never be able to return to that
12277            // situation so here we do a sanity check to make sure we haven't
12278            // left any junk around.
12279            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12280            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12281                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12282                removed.clear();
12283                for (PreferredActivity pa : pir.filterSet()) {
12284                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12285                        removed.add(pa);
12286                    }
12287                }
12288                if (removed.size() > 0) {
12289                    for (int r=0; r<removed.size(); r++) {
12290                        PreferredActivity pa = removed.get(r);
12291                        Slog.w(TAG, "Removing dangling preferred activity: "
12292                                + pa.mPref.mComponent);
12293                        pir.removeFilter(pa);
12294                    }
12295                    mSettings.writePackageRestrictionsLPr(
12296                            mSettings.mPreferredActivities.keyAt(i));
12297                }
12298            }
12299        }
12300        sUserManager.systemReady();
12301
12302        // Kick off any messages waiting for system ready
12303        if (mPostSystemReadyMessages != null) {
12304            for (Message msg : mPostSystemReadyMessages) {
12305                msg.sendToTarget();
12306            }
12307            mPostSystemReadyMessages = null;
12308        }
12309    }
12310
12311    @Override
12312    public boolean isSafeMode() {
12313        return mSafeMode;
12314    }
12315
12316    @Override
12317    public boolean hasSystemUidErrors() {
12318        return mHasSystemUidErrors;
12319    }
12320
12321    static String arrayToString(int[] array) {
12322        StringBuffer buf = new StringBuffer(128);
12323        buf.append('[');
12324        if (array != null) {
12325            for (int i=0; i<array.length; i++) {
12326                if (i > 0) buf.append(", ");
12327                buf.append(array[i]);
12328            }
12329        }
12330        buf.append(']');
12331        return buf.toString();
12332    }
12333
12334    static class DumpState {
12335        public static final int DUMP_LIBS = 1 << 0;
12336        public static final int DUMP_FEATURES = 1 << 1;
12337        public static final int DUMP_RESOLVERS = 1 << 2;
12338        public static final int DUMP_PERMISSIONS = 1 << 3;
12339        public static final int DUMP_PACKAGES = 1 << 4;
12340        public static final int DUMP_SHARED_USERS = 1 << 5;
12341        public static final int DUMP_MESSAGES = 1 << 6;
12342        public static final int DUMP_PROVIDERS = 1 << 7;
12343        public static final int DUMP_VERIFIERS = 1 << 8;
12344        public static final int DUMP_PREFERRED = 1 << 9;
12345        public static final int DUMP_PREFERRED_XML = 1 << 10;
12346        public static final int DUMP_KEYSETS = 1 << 11;
12347        public static final int DUMP_VERSION = 1 << 12;
12348        public static final int DUMP_INSTALLS = 1 << 13;
12349
12350        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12351
12352        private int mTypes;
12353
12354        private int mOptions;
12355
12356        private boolean mTitlePrinted;
12357
12358        private SharedUserSetting mSharedUser;
12359
12360        public boolean isDumping(int type) {
12361            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12362                return true;
12363            }
12364
12365            return (mTypes & type) != 0;
12366        }
12367
12368        public void setDump(int type) {
12369            mTypes |= type;
12370        }
12371
12372        public boolean isOptionEnabled(int option) {
12373            return (mOptions & option) != 0;
12374        }
12375
12376        public void setOptionEnabled(int option) {
12377            mOptions |= option;
12378        }
12379
12380        public boolean onTitlePrinted() {
12381            final boolean printed = mTitlePrinted;
12382            mTitlePrinted = true;
12383            return printed;
12384        }
12385
12386        public boolean getTitlePrinted() {
12387            return mTitlePrinted;
12388        }
12389
12390        public void setTitlePrinted(boolean enabled) {
12391            mTitlePrinted = enabled;
12392        }
12393
12394        public SharedUserSetting getSharedUser() {
12395            return mSharedUser;
12396        }
12397
12398        public void setSharedUser(SharedUserSetting user) {
12399            mSharedUser = user;
12400        }
12401    }
12402
12403    @Override
12404    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12405        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12406                != PackageManager.PERMISSION_GRANTED) {
12407            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12408                    + Binder.getCallingPid()
12409                    + ", uid=" + Binder.getCallingUid()
12410                    + " without permission "
12411                    + android.Manifest.permission.DUMP);
12412            return;
12413        }
12414
12415        DumpState dumpState = new DumpState();
12416        boolean fullPreferred = false;
12417        boolean checkin = false;
12418
12419        String packageName = null;
12420
12421        int opti = 0;
12422        while (opti < args.length) {
12423            String opt = args[opti];
12424            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12425                break;
12426            }
12427            opti++;
12428
12429            if ("-a".equals(opt)) {
12430                // Right now we only know how to print all.
12431            } else if ("-h".equals(opt)) {
12432                pw.println("Package manager dump options:");
12433                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12434                pw.println("    --checkin: dump for a checkin");
12435                pw.println("    -f: print details of intent filters");
12436                pw.println("    -h: print this help");
12437                pw.println("  cmd may be one of:");
12438                pw.println("    l[ibraries]: list known shared libraries");
12439                pw.println("    f[ibraries]: list device features");
12440                pw.println("    k[eysets]: print known keysets");
12441                pw.println("    r[esolvers]: dump intent resolvers");
12442                pw.println("    perm[issions]: dump permissions");
12443                pw.println("    pref[erred]: print preferred package settings");
12444                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12445                pw.println("    prov[iders]: dump content providers");
12446                pw.println("    p[ackages]: dump installed packages");
12447                pw.println("    s[hared-users]: dump shared user IDs");
12448                pw.println("    m[essages]: print collected runtime messages");
12449                pw.println("    v[erifiers]: print package verifier info");
12450                pw.println("    version: print database version info");
12451                pw.println("    write: write current settings now");
12452                pw.println("    <package.name>: info about given package");
12453                pw.println("    installs: details about install sessions");
12454                return;
12455            } else if ("--checkin".equals(opt)) {
12456                checkin = true;
12457            } else if ("-f".equals(opt)) {
12458                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12459            } else {
12460                pw.println("Unknown argument: " + opt + "; use -h for help");
12461            }
12462        }
12463
12464        // Is the caller requesting to dump a particular piece of data?
12465        if (opti < args.length) {
12466            String cmd = args[opti];
12467            opti++;
12468            // Is this a package name?
12469            if ("android".equals(cmd) || cmd.contains(".")) {
12470                packageName = cmd;
12471                // When dumping a single package, we always dump all of its
12472                // filter information since the amount of data will be reasonable.
12473                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12474            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12475                dumpState.setDump(DumpState.DUMP_LIBS);
12476            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12477                dumpState.setDump(DumpState.DUMP_FEATURES);
12478            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12479                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12480            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12481                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12482            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12483                dumpState.setDump(DumpState.DUMP_PREFERRED);
12484            } else if ("preferred-xml".equals(cmd)) {
12485                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12486                if (opti < args.length && "--full".equals(args[opti])) {
12487                    fullPreferred = true;
12488                    opti++;
12489                }
12490            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12491                dumpState.setDump(DumpState.DUMP_PACKAGES);
12492            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12493                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12494            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12495                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12496            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12497                dumpState.setDump(DumpState.DUMP_MESSAGES);
12498            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12499                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12500            } else if ("version".equals(cmd)) {
12501                dumpState.setDump(DumpState.DUMP_VERSION);
12502            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12503                dumpState.setDump(DumpState.DUMP_KEYSETS);
12504            } else if ("installs".equals(cmd)) {
12505                dumpState.setDump(DumpState.DUMP_INSTALLS);
12506            } else if ("write".equals(cmd)) {
12507                synchronized (mPackages) {
12508                    mSettings.writeLPr();
12509                    pw.println("Settings written.");
12510                    return;
12511                }
12512            }
12513        }
12514
12515        if (checkin) {
12516            pw.println("vers,1");
12517        }
12518
12519        // reader
12520        synchronized (mPackages) {
12521            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12522                if (!checkin) {
12523                    if (dumpState.onTitlePrinted())
12524                        pw.println();
12525                    pw.println("Database versions:");
12526                    pw.print("  SDK Version:");
12527                    pw.print(" internal=");
12528                    pw.print(mSettings.mInternalSdkPlatform);
12529                    pw.print(" external=");
12530                    pw.println(mSettings.mExternalSdkPlatform);
12531                    pw.print("  DB Version:");
12532                    pw.print(" internal=");
12533                    pw.print(mSettings.mInternalDatabaseVersion);
12534                    pw.print(" external=");
12535                    pw.println(mSettings.mExternalDatabaseVersion);
12536                }
12537            }
12538
12539            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12540                if (!checkin) {
12541                    if (dumpState.onTitlePrinted())
12542                        pw.println();
12543                    pw.println("Verifiers:");
12544                    pw.print("  Required: ");
12545                    pw.print(mRequiredVerifierPackage);
12546                    pw.print(" (uid=");
12547                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12548                    pw.println(")");
12549                } else if (mRequiredVerifierPackage != null) {
12550                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12551                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12552                }
12553            }
12554
12555            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12556                boolean printedHeader = false;
12557                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12558                while (it.hasNext()) {
12559                    String name = it.next();
12560                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12561                    if (!checkin) {
12562                        if (!printedHeader) {
12563                            if (dumpState.onTitlePrinted())
12564                                pw.println();
12565                            pw.println("Libraries:");
12566                            printedHeader = true;
12567                        }
12568                        pw.print("  ");
12569                    } else {
12570                        pw.print("lib,");
12571                    }
12572                    pw.print(name);
12573                    if (!checkin) {
12574                        pw.print(" -> ");
12575                    }
12576                    if (ent.path != null) {
12577                        if (!checkin) {
12578                            pw.print("(jar) ");
12579                            pw.print(ent.path);
12580                        } else {
12581                            pw.print(",jar,");
12582                            pw.print(ent.path);
12583                        }
12584                    } else {
12585                        if (!checkin) {
12586                            pw.print("(apk) ");
12587                            pw.print(ent.apk);
12588                        } else {
12589                            pw.print(",apk,");
12590                            pw.print(ent.apk);
12591                        }
12592                    }
12593                    pw.println();
12594                }
12595            }
12596
12597            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12598                if (dumpState.onTitlePrinted())
12599                    pw.println();
12600                if (!checkin) {
12601                    pw.println("Features:");
12602                }
12603                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12604                while (it.hasNext()) {
12605                    String name = it.next();
12606                    if (!checkin) {
12607                        pw.print("  ");
12608                    } else {
12609                        pw.print("feat,");
12610                    }
12611                    pw.println(name);
12612                }
12613            }
12614
12615            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12616                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12617                        : "Activity Resolver Table:", "  ", packageName,
12618                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12619                    dumpState.setTitlePrinted(true);
12620                }
12621                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12622                        : "Receiver Resolver Table:", "  ", packageName,
12623                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12624                    dumpState.setTitlePrinted(true);
12625                }
12626                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12627                        : "Service Resolver Table:", "  ", packageName,
12628                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12629                    dumpState.setTitlePrinted(true);
12630                }
12631                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12632                        : "Provider Resolver Table:", "  ", packageName,
12633                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12634                    dumpState.setTitlePrinted(true);
12635                }
12636            }
12637
12638            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12639                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12640                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12641                    int user = mSettings.mPreferredActivities.keyAt(i);
12642                    if (pir.dump(pw,
12643                            dumpState.getTitlePrinted()
12644                                ? "\nPreferred Activities User " + user + ":"
12645                                : "Preferred Activities User " + user + ":", "  ",
12646                            packageName, true, false)) {
12647                        dumpState.setTitlePrinted(true);
12648                    }
12649                }
12650            }
12651
12652            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12653                pw.flush();
12654                FileOutputStream fout = new FileOutputStream(fd);
12655                BufferedOutputStream str = new BufferedOutputStream(fout);
12656                XmlSerializer serializer = new FastXmlSerializer();
12657                try {
12658                    serializer.setOutput(str, "utf-8");
12659                    serializer.startDocument(null, true);
12660                    serializer.setFeature(
12661                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12662                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12663                    serializer.endDocument();
12664                    serializer.flush();
12665                } catch (IllegalArgumentException e) {
12666                    pw.println("Failed writing: " + e);
12667                } catch (IllegalStateException e) {
12668                    pw.println("Failed writing: " + e);
12669                } catch (IOException e) {
12670                    pw.println("Failed writing: " + e);
12671                }
12672            }
12673
12674            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12675                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12676                if (packageName == null) {
12677                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12678                        if (iperm == 0) {
12679                            if (dumpState.onTitlePrinted())
12680                                pw.println();
12681                            pw.println("AppOp Permissions:");
12682                        }
12683                        pw.print("  AppOp Permission ");
12684                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12685                        pw.println(":");
12686                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12687                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12688                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12689                        }
12690                    }
12691                }
12692            }
12693
12694            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12695                boolean printedSomething = false;
12696                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12697                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12698                        continue;
12699                    }
12700                    if (!printedSomething) {
12701                        if (dumpState.onTitlePrinted())
12702                            pw.println();
12703                        pw.println("Registered ContentProviders:");
12704                        printedSomething = true;
12705                    }
12706                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12707                    pw.print("    "); pw.println(p.toString());
12708                }
12709                printedSomething = false;
12710                for (Map.Entry<String, PackageParser.Provider> entry :
12711                        mProvidersByAuthority.entrySet()) {
12712                    PackageParser.Provider p = entry.getValue();
12713                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12714                        continue;
12715                    }
12716                    if (!printedSomething) {
12717                        if (dumpState.onTitlePrinted())
12718                            pw.println();
12719                        pw.println("ContentProvider Authorities:");
12720                        printedSomething = true;
12721                    }
12722                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12723                    pw.print("    "); pw.println(p.toString());
12724                    if (p.info != null && p.info.applicationInfo != null) {
12725                        final String appInfo = p.info.applicationInfo.toString();
12726                        pw.print("      applicationInfo="); pw.println(appInfo);
12727                    }
12728                }
12729            }
12730
12731            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12732                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12733            }
12734
12735            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12736                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12737            }
12738
12739            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12740                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12741            }
12742
12743            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12744                // XXX should handle packageName != null by dumping only install data that
12745                // the given package is involved with.
12746                if (dumpState.onTitlePrinted()) pw.println();
12747                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12748            }
12749
12750            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12751                if (dumpState.onTitlePrinted()) pw.println();
12752                mSettings.dumpReadMessagesLPr(pw, dumpState);
12753
12754                pw.println();
12755                pw.println("Package warning messages:");
12756                BufferedReader in = null;
12757                String line = null;
12758                try {
12759                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12760                    while ((line = in.readLine()) != null) {
12761                        if (line.contains("ignored: updated version")) continue;
12762                        pw.println(line);
12763                    }
12764                } catch (IOException ignored) {
12765                } finally {
12766                    IoUtils.closeQuietly(in);
12767                }
12768            }
12769
12770            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12771                BufferedReader in = null;
12772                String line = null;
12773                try {
12774                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12775                    while ((line = in.readLine()) != null) {
12776                        if (line.contains("ignored: updated version")) continue;
12777                        pw.print("msg,");
12778                        pw.println(line);
12779                    }
12780                } catch (IOException ignored) {
12781                } finally {
12782                    IoUtils.closeQuietly(in);
12783                }
12784            }
12785        }
12786    }
12787
12788    // ------- apps on sdcard specific code -------
12789    static final boolean DEBUG_SD_INSTALL = false;
12790
12791    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12792
12793    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12794
12795    private boolean mMediaMounted = false;
12796
12797    static String getEncryptKey() {
12798        try {
12799            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12800                    SD_ENCRYPTION_KEYSTORE_NAME);
12801            if (sdEncKey == null) {
12802                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12803                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12804                if (sdEncKey == null) {
12805                    Slog.e(TAG, "Failed to create encryption keys");
12806                    return null;
12807                }
12808            }
12809            return sdEncKey;
12810        } catch (NoSuchAlgorithmException nsae) {
12811            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12812            return null;
12813        } catch (IOException ioe) {
12814            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12815            return null;
12816        }
12817    }
12818
12819    /*
12820     * Update media status on PackageManager.
12821     */
12822    @Override
12823    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12824        int callingUid = Binder.getCallingUid();
12825        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12826            throw new SecurityException("Media status can only be updated by the system");
12827        }
12828        // reader; this apparently protects mMediaMounted, but should probably
12829        // be a different lock in that case.
12830        synchronized (mPackages) {
12831            Log.i(TAG, "Updating external media status from "
12832                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12833                    + (mediaStatus ? "mounted" : "unmounted"));
12834            if (DEBUG_SD_INSTALL)
12835                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12836                        + ", mMediaMounted=" + mMediaMounted);
12837            if (mediaStatus == mMediaMounted) {
12838                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12839                        : 0, -1);
12840                mHandler.sendMessage(msg);
12841                return;
12842            }
12843            mMediaMounted = mediaStatus;
12844        }
12845        // Queue up an async operation since the package installation may take a
12846        // little while.
12847        mHandler.post(new Runnable() {
12848            public void run() {
12849                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12850            }
12851        });
12852    }
12853
12854    /**
12855     * Called by MountService when the initial ASECs to scan are available.
12856     * Should block until all the ASEC containers are finished being scanned.
12857     */
12858    public void scanAvailableAsecs() {
12859        updateExternalMediaStatusInner(true, false, false);
12860        if (mShouldRestoreconData) {
12861            SELinuxMMAC.setRestoreconDone();
12862            mShouldRestoreconData = false;
12863        }
12864    }
12865
12866    /*
12867     * Collect information of applications on external media, map them against
12868     * existing containers and update information based on current mount status.
12869     * Please note that we always have to report status if reportStatus has been
12870     * set to true especially when unloading packages.
12871     */
12872    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12873            boolean externalStorage) {
12874        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12875        int[] uidArr = EmptyArray.INT;
12876
12877        final String[] list = PackageHelper.getSecureContainerList();
12878        if (ArrayUtils.isEmpty(list)) {
12879            Log.i(TAG, "No secure containers found");
12880        } else {
12881            // Process list of secure containers and categorize them
12882            // as active or stale based on their package internal state.
12883
12884            // reader
12885            synchronized (mPackages) {
12886                for (String cid : list) {
12887                    // Leave stages untouched for now; installer service owns them
12888                    if (PackageInstallerService.isStageName(cid)) continue;
12889
12890                    if (DEBUG_SD_INSTALL)
12891                        Log.i(TAG, "Processing container " + cid);
12892                    String pkgName = getAsecPackageName(cid);
12893                    if (pkgName == null) {
12894                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12895                        continue;
12896                    }
12897                    if (DEBUG_SD_INSTALL)
12898                        Log.i(TAG, "Looking for pkg : " + pkgName);
12899
12900                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12901                    if (ps == null) {
12902                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12903                        continue;
12904                    }
12905
12906                    /*
12907                     * Skip packages that are not external if we're unmounting
12908                     * external storage.
12909                     */
12910                    if (externalStorage && !isMounted && !isExternal(ps)) {
12911                        continue;
12912                    }
12913
12914                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12915                            getAppDexInstructionSets(ps), ps.isForwardLocked());
12916                    // The package status is changed only if the code path
12917                    // matches between settings and the container id.
12918                    if (ps.codePathString != null
12919                            && ps.codePathString.startsWith(args.getCodePath())) {
12920                        if (DEBUG_SD_INSTALL) {
12921                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12922                                    + " at code path: " + ps.codePathString);
12923                        }
12924
12925                        // We do have a valid package installed on sdcard
12926                        processCids.put(args, ps.codePathString);
12927                        final int uid = ps.appId;
12928                        if (uid != -1) {
12929                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12930                        }
12931                    } else {
12932                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12933                                + ps.codePathString);
12934                    }
12935                }
12936            }
12937
12938            Arrays.sort(uidArr);
12939        }
12940
12941        // Process packages with valid entries.
12942        if (isMounted) {
12943            if (DEBUG_SD_INSTALL)
12944                Log.i(TAG, "Loading packages");
12945            loadMediaPackages(processCids, uidArr);
12946            startCleaningPackages();
12947            mInstallerService.onSecureContainersAvailable();
12948        } else {
12949            if (DEBUG_SD_INSTALL)
12950                Log.i(TAG, "Unloading packages");
12951            unloadMediaPackages(processCids, uidArr, reportStatus);
12952        }
12953    }
12954
12955    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12956            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12957        int size = pkgList.size();
12958        if (size > 0) {
12959            // Send broadcasts here
12960            Bundle extras = new Bundle();
12961            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12962                    .toArray(new String[size]));
12963            if (uidArr != null) {
12964                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12965            }
12966            if (replacing) {
12967                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12968            }
12969            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12970                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12971            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12972        }
12973    }
12974
12975   /*
12976     * Look at potentially valid container ids from processCids If package
12977     * information doesn't match the one on record or package scanning fails,
12978     * the cid is added to list of removeCids. We currently don't delete stale
12979     * containers.
12980     */
12981    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12982        ArrayList<String> pkgList = new ArrayList<String>();
12983        Set<AsecInstallArgs> keys = processCids.keySet();
12984
12985        for (AsecInstallArgs args : keys) {
12986            String codePath = processCids.get(args);
12987            if (DEBUG_SD_INSTALL)
12988                Log.i(TAG, "Loading container : " + args.cid);
12989            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12990            try {
12991                // Make sure there are no container errors first.
12992                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12993                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12994                            + " when installing from sdcard");
12995                    continue;
12996                }
12997                // Check code path here.
12998                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12999                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13000                            + " does not match one in settings " + codePath);
13001                    continue;
13002                }
13003                // Parse package
13004                int parseFlags = mDefParseFlags;
13005                if (args.isExternal()) {
13006                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
13007                }
13008                if (args.isFwdLocked()) {
13009                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13010                }
13011
13012                synchronized (mInstallLock) {
13013                    PackageParser.Package pkg = null;
13014                    try {
13015                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13016                    } catch (PackageManagerException e) {
13017                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13018                    }
13019                    // Scan the package
13020                    if (pkg != null) {
13021                        /*
13022                         * TODO why is the lock being held? doPostInstall is
13023                         * called in other places without the lock. This needs
13024                         * to be straightened out.
13025                         */
13026                        // writer
13027                        synchronized (mPackages) {
13028                            retCode = PackageManager.INSTALL_SUCCEEDED;
13029                            pkgList.add(pkg.packageName);
13030                            // Post process args
13031                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13032                                    pkg.applicationInfo.uid);
13033                        }
13034                    } else {
13035                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13036                    }
13037                }
13038
13039            } finally {
13040                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13041                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13042                }
13043            }
13044        }
13045        // writer
13046        synchronized (mPackages) {
13047            // If the platform SDK has changed since the last time we booted,
13048            // we need to re-grant app permission to catch any new ones that
13049            // appear. This is really a hack, and means that apps can in some
13050            // cases get permissions that the user didn't initially explicitly
13051            // allow... it would be nice to have some better way to handle
13052            // this situation.
13053            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13054            if (regrantPermissions)
13055                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13056                        + mSdkVersion + "; regranting permissions for external storage");
13057            mSettings.mExternalSdkPlatform = mSdkVersion;
13058
13059            // Make sure group IDs have been assigned, and any permission
13060            // changes in other apps are accounted for
13061            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13062                    | (regrantPermissions
13063                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13064                            : 0));
13065
13066            mSettings.updateExternalDatabaseVersion();
13067
13068            // can downgrade to reader
13069            // Persist settings
13070            mSettings.writeLPr();
13071        }
13072        // Send a broadcast to let everyone know we are done processing
13073        if (pkgList.size() > 0) {
13074            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13075        }
13076    }
13077
13078   /*
13079     * Utility method to unload a list of specified containers
13080     */
13081    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13082        // Just unmount all valid containers.
13083        for (AsecInstallArgs arg : cidArgs) {
13084            synchronized (mInstallLock) {
13085                arg.doPostDeleteLI(false);
13086           }
13087       }
13088   }
13089
13090    /*
13091     * Unload packages mounted on external media. This involves deleting package
13092     * data from internal structures, sending broadcasts about diabled packages,
13093     * gc'ing to free up references, unmounting all secure containers
13094     * corresponding to packages on external media, and posting a
13095     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13096     * that we always have to post this message if status has been requested no
13097     * matter what.
13098     */
13099    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13100            final boolean reportStatus) {
13101        if (DEBUG_SD_INSTALL)
13102            Log.i(TAG, "unloading media packages");
13103        ArrayList<String> pkgList = new ArrayList<String>();
13104        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13105        final Set<AsecInstallArgs> keys = processCids.keySet();
13106        for (AsecInstallArgs args : keys) {
13107            String pkgName = args.getPackageName();
13108            if (DEBUG_SD_INSTALL)
13109                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13110            // Delete package internally
13111            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13112            synchronized (mInstallLock) {
13113                boolean res = deletePackageLI(pkgName, null, false, null, null,
13114                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13115                if (res) {
13116                    pkgList.add(pkgName);
13117                } else {
13118                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13119                    failedList.add(args);
13120                }
13121            }
13122        }
13123
13124        // reader
13125        synchronized (mPackages) {
13126            // We didn't update the settings after removing each package;
13127            // write them now for all packages.
13128            mSettings.writeLPr();
13129        }
13130
13131        // We have to absolutely send UPDATED_MEDIA_STATUS only
13132        // after confirming that all the receivers processed the ordered
13133        // broadcast when packages get disabled, force a gc to clean things up.
13134        // and unload all the containers.
13135        if (pkgList.size() > 0) {
13136            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13137                    new IIntentReceiver.Stub() {
13138                public void performReceive(Intent intent, int resultCode, String data,
13139                        Bundle extras, boolean ordered, boolean sticky,
13140                        int sendingUser) throws RemoteException {
13141                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13142                            reportStatus ? 1 : 0, 1, keys);
13143                    mHandler.sendMessage(msg);
13144                }
13145            });
13146        } else {
13147            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13148                    keys);
13149            mHandler.sendMessage(msg);
13150        }
13151    }
13152
13153    /** Binder call */
13154    @Override
13155    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13156            final int flags) {
13157        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13158        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13159        int returnCode = PackageManager.MOVE_SUCCEEDED;
13160        int currInstallFlags = 0;
13161        int newInstallFlags = 0;
13162
13163        File codeFile = null;
13164        String installerPackageName = null;
13165        String packageAbiOverride = null;
13166
13167        // reader
13168        synchronized (mPackages) {
13169            final PackageParser.Package pkg = mPackages.get(packageName);
13170            final PackageSetting ps = mSettings.mPackages.get(packageName);
13171            if (pkg == null || ps == null) {
13172                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13173            } else {
13174                // Disable moving fwd locked apps and system packages
13175                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13176                    Slog.w(TAG, "Cannot move system application");
13177                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13178                } else if (pkg.mOperationPending) {
13179                    Slog.w(TAG, "Attempt to move package which has pending operations");
13180                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13181                } else {
13182                    // Find install location first
13183                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13184                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13185                        Slog.w(TAG, "Ambigous flags specified for move location.");
13186                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13187                    } else {
13188                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13189                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13190                        currInstallFlags = isExternal(pkg)
13191                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13192
13193                        if (newInstallFlags == currInstallFlags) {
13194                            Slog.w(TAG, "No move required. Trying to move to same location");
13195                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13196                        } else {
13197                            if (pkg.isForwardLocked()) {
13198                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13199                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13200                            }
13201                        }
13202                    }
13203                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13204                        pkg.mOperationPending = true;
13205                    }
13206                }
13207
13208                codeFile = new File(pkg.codePath);
13209                installerPackageName = ps.installerPackageName;
13210                packageAbiOverride = ps.cpuAbiOverrideString;
13211            }
13212        }
13213
13214        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13215            try {
13216                observer.packageMoved(packageName, returnCode);
13217            } catch (RemoteException ignored) {
13218            }
13219            return;
13220        }
13221
13222        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13223            @Override
13224            public void onUserActionRequired(Intent intent) throws RemoteException {
13225                throw new IllegalStateException();
13226            }
13227
13228            @Override
13229            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13230                    Bundle extras) throws RemoteException {
13231                Slog.d(TAG, "Install result for move: "
13232                        + PackageManager.installStatusToString(returnCode, msg));
13233
13234                // We usually have a new package now after the install, but if
13235                // we failed we need to clear the pending flag on the original
13236                // package object.
13237                synchronized (mPackages) {
13238                    final PackageParser.Package pkg = mPackages.get(packageName);
13239                    if (pkg != null) {
13240                        pkg.mOperationPending = false;
13241                    }
13242                }
13243
13244                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13245                switch (status) {
13246                    case PackageInstaller.STATUS_SUCCESS:
13247                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13248                        break;
13249                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13250                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13251                        break;
13252                    default:
13253                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13254                        break;
13255                }
13256            }
13257        };
13258
13259        // Treat a move like reinstalling an existing app, which ensures that we
13260        // process everythign uniformly, like unpacking native libraries.
13261        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13262
13263        final Message msg = mHandler.obtainMessage(INIT_COPY);
13264        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13265        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13266                installerPackageName, null, user, packageAbiOverride);
13267        mHandler.sendMessage(msg);
13268    }
13269
13270    @Override
13271    public boolean setInstallLocation(int loc) {
13272        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13273                null);
13274        if (getInstallLocation() == loc) {
13275            return true;
13276        }
13277        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13278                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13279            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13280                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13281            return true;
13282        }
13283        return false;
13284   }
13285
13286    @Override
13287    public int getInstallLocation() {
13288        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13289                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13290                PackageHelper.APP_INSTALL_AUTO);
13291    }
13292
13293    /** Called by UserManagerService */
13294    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13295        mDirtyUsers.remove(userHandle);
13296        mSettings.removeUserLPw(userHandle);
13297        mPendingBroadcasts.remove(userHandle);
13298        if (mInstaller != null) {
13299            // Technically, we shouldn't be doing this with the package lock
13300            // held.  However, this is very rare, and there is already so much
13301            // other disk I/O going on, that we'll let it slide for now.
13302            mInstaller.removeUserDataDirs(userHandle);
13303        }
13304        mUserNeedsBadging.delete(userHandle);
13305        removeUnusedPackagesLILPw(userManager, userHandle);
13306    }
13307
13308    /**
13309     * We're removing userHandle and would like to remove any downloaded packages
13310     * that are no longer in use by any other user.
13311     * @param userHandle the user being removed
13312     */
13313    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13314        final boolean DEBUG_CLEAN_APKS = false;
13315        int [] users = userManager.getUserIdsLPr();
13316        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13317        while (psit.hasNext()) {
13318            PackageSetting ps = psit.next();
13319            if (ps.pkg == null) {
13320                continue;
13321            }
13322            final String packageName = ps.pkg.packageName;
13323            // Skip over if system app
13324            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13325                continue;
13326            }
13327            if (DEBUG_CLEAN_APKS) {
13328                Slog.i(TAG, "Checking package " + packageName);
13329            }
13330            boolean keep = false;
13331            for (int i = 0; i < users.length; i++) {
13332                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13333                    keep = true;
13334                    if (DEBUG_CLEAN_APKS) {
13335                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13336                                + users[i]);
13337                    }
13338                    break;
13339                }
13340            }
13341            if (!keep) {
13342                if (DEBUG_CLEAN_APKS) {
13343                    Slog.i(TAG, "  Removing package " + packageName);
13344                }
13345                mHandler.post(new Runnable() {
13346                    public void run() {
13347                        deletePackageX(packageName, userHandle, 0);
13348                    } //end run
13349                });
13350            }
13351        }
13352    }
13353
13354    /** Called by UserManagerService */
13355    void createNewUserLILPw(int userHandle, File path) {
13356        if (mInstaller != null) {
13357            mInstaller.createUserConfig(userHandle);
13358            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13359        }
13360    }
13361
13362    @Override
13363    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13364        mContext.enforceCallingOrSelfPermission(
13365                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13366                "Only package verification agents can read the verifier device identity");
13367
13368        synchronized (mPackages) {
13369            return mSettings.getVerifierDeviceIdentityLPw();
13370        }
13371    }
13372
13373    @Override
13374    public void setPermissionEnforced(String permission, boolean enforced) {
13375        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13376        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13377            synchronized (mPackages) {
13378                if (mSettings.mReadExternalStorageEnforced == null
13379                        || mSettings.mReadExternalStorageEnforced != enforced) {
13380                    mSettings.mReadExternalStorageEnforced = enforced;
13381                    mSettings.writeLPr();
13382                }
13383            }
13384            // kill any non-foreground processes so we restart them and
13385            // grant/revoke the GID.
13386            final IActivityManager am = ActivityManagerNative.getDefault();
13387            if (am != null) {
13388                final long token = Binder.clearCallingIdentity();
13389                try {
13390                    am.killProcessesBelowForeground("setPermissionEnforcement");
13391                } catch (RemoteException e) {
13392                } finally {
13393                    Binder.restoreCallingIdentity(token);
13394                }
13395            }
13396        } else {
13397            throw new IllegalArgumentException("No selective enforcement for " + permission);
13398        }
13399    }
13400
13401    @Override
13402    @Deprecated
13403    public boolean isPermissionEnforced(String permission) {
13404        return true;
13405    }
13406
13407    @Override
13408    public boolean isStorageLow() {
13409        final long token = Binder.clearCallingIdentity();
13410        try {
13411            final DeviceStorageMonitorInternal
13412                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13413            if (dsm != null) {
13414                return dsm.isMemoryLow();
13415            } else {
13416                return false;
13417            }
13418        } finally {
13419            Binder.restoreCallingIdentity(token);
13420        }
13421    }
13422
13423    @Override
13424    public IPackageInstaller getPackageInstaller() {
13425        return mInstallerService;
13426    }
13427
13428    private boolean userNeedsBadging(int userId) {
13429        int index = mUserNeedsBadging.indexOfKey(userId);
13430        if (index < 0) {
13431            final UserInfo userInfo;
13432            final long token = Binder.clearCallingIdentity();
13433            try {
13434                userInfo = sUserManager.getUserInfo(userId);
13435            } finally {
13436                Binder.restoreCallingIdentity(token);
13437            }
13438            final boolean b;
13439            if (userInfo != null && userInfo.isManagedProfile()) {
13440                b = true;
13441            } else {
13442                b = false;
13443            }
13444            mUserNeedsBadging.put(userId, b);
13445            return b;
13446        }
13447        return mUserNeedsBadging.valueAt(index);
13448    }
13449
13450    @Override
13451    public KeySet getKeySetByAlias(String packageName, String alias) {
13452        if (packageName == null || alias == null) {
13453            return null;
13454        }
13455        synchronized(mPackages) {
13456            final PackageParser.Package pkg = mPackages.get(packageName);
13457            if (pkg == null) {
13458                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13459                throw new IllegalArgumentException("Unknown package: " + packageName);
13460            }
13461            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13462            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13463        }
13464    }
13465
13466    @Override
13467    public KeySet getSigningKeySet(String packageName) {
13468        if (packageName == null) {
13469            return null;
13470        }
13471        synchronized(mPackages) {
13472            final PackageParser.Package pkg = mPackages.get(packageName);
13473            if (pkg == null) {
13474                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13475                throw new IllegalArgumentException("Unknown package: " + packageName);
13476            }
13477            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13478                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13479                throw new SecurityException("May not access signing KeySet of other apps.");
13480            }
13481            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13482            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13483        }
13484    }
13485
13486    @Override
13487    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13488        if (packageName == null || ks == null) {
13489            return false;
13490        }
13491        synchronized(mPackages) {
13492            final PackageParser.Package pkg = mPackages.get(packageName);
13493            if (pkg == null) {
13494                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13495                throw new IllegalArgumentException("Unknown package: " + packageName);
13496            }
13497            IBinder ksh = ks.getToken();
13498            if (ksh instanceof KeySetHandle) {
13499                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13500                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13501            }
13502            return false;
13503        }
13504    }
13505
13506    @Override
13507    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13508        if (packageName == null || ks == null) {
13509            return false;
13510        }
13511        synchronized(mPackages) {
13512            final PackageParser.Package pkg = mPackages.get(packageName);
13513            if (pkg == null) {
13514                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13515                throw new IllegalArgumentException("Unknown package: " + packageName);
13516            }
13517            IBinder ksh = ks.getToken();
13518            if (ksh instanceof KeySetHandle) {
13519                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13520                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13521            }
13522            return false;
13523        }
13524    }
13525
13526    public void getUsageStatsIfNoPackageUsageInfo() {
13527        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13528            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13529            if (usm == null) {
13530                throw new IllegalStateException("UsageStatsManager must be initialized");
13531            }
13532            long now = System.currentTimeMillis();
13533            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13534            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13535                String packageName = entry.getKey();
13536                PackageParser.Package pkg = mPackages.get(packageName);
13537                if (pkg == null) {
13538                    continue;
13539                }
13540                UsageStats usage = entry.getValue();
13541                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13542                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13543            }
13544        }
13545    }
13546
13547    /**
13548     * Check and throw if the given before/after packages would be considered a
13549     * downgrade.
13550     */
13551    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13552            throws PackageManagerException {
13553        if (after.versionCode < before.mVersionCode) {
13554            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13555                    "Update version code " + after.versionCode + " is older than current "
13556                    + before.mVersionCode);
13557        } else if (after.versionCode == before.mVersionCode) {
13558            if (after.baseRevisionCode < before.baseRevisionCode) {
13559                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13560                        "Update base revision code " + after.baseRevisionCode
13561                        + " is older than current " + before.baseRevisionCode);
13562            }
13563
13564            if (!ArrayUtils.isEmpty(after.splitNames)) {
13565                for (int i = 0; i < after.splitNames.length; i++) {
13566                    final String splitName = after.splitNames[i];
13567                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13568                    if (j != -1) {
13569                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13570                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13571                                    "Update split " + splitName + " revision code "
13572                                    + after.splitRevisionCodes[i] + " is older than current "
13573                                    + before.splitRevisionCodes[j]);
13574                        }
13575                    }
13576                }
13577            }
13578        }
13579    }
13580}
13581