PackageManagerService.java revision 60b3be3ab5fba871311628dec0538214b4965027
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.permissions.enabled", 0) == 1;
253
254    private static final int RADIO_UID = Process.PHONE_UID;
255    private static final int LOG_UID = Process.LOG_UID;
256    private static final int NFC_UID = Process.NFC_UID;
257    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
258    private static final int SHELL_UID = Process.SHELL_UID;
259
260    // Cap the size of permission trees that 3rd party apps can define
261    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
262
263    // Suffix used during package installation when copying/moving
264    // package apks to install directory.
265    private static final String INSTALL_PACKAGE_SUFFIX = "-";
266
267    static final int SCAN_NO_DEX = 1<<1;
268    static final int SCAN_FORCE_DEX = 1<<2;
269    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
270    static final int SCAN_NEW_INSTALL = 1<<4;
271    static final int SCAN_NO_PATHS = 1<<5;
272    static final int SCAN_UPDATE_TIME = 1<<6;
273    static final int SCAN_DEFER_DEX = 1<<7;
274    static final int SCAN_BOOTING = 1<<8;
275    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
276    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
277    static final int SCAN_REPLACING = 1<<11;
278    static final int SCAN_REQUIRE_KNOWN = 1<<12;
279
280    static final int REMOVE_CHATTY = 1<<16;
281
282    /**
283     * Timeout (in milliseconds) after which the watchdog should declare that
284     * our handler thread is wedged.  The usual default for such things is one
285     * minute but we sometimes do very lengthy I/O operations on this thread,
286     * such as installing multi-gigabyte applications, so ours needs to be longer.
287     */
288    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
289
290    /**
291     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
292     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
293     * settings entry if available, otherwise we use the hardcoded default.  If it's been
294     * more than this long since the last fstrim, we force one during the boot sequence.
295     *
296     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
297     * one gets run at the next available charging+idle time.  This final mandatory
298     * no-fstrim check kicks in only of the other scheduling criteria is never met.
299     */
300    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
301
302    /**
303     * Whether verification is enabled by default.
304     */
305    private static final boolean DEFAULT_VERIFY_ENABLE = true;
306
307    /**
308     * The default maximum time to wait for the verification agent to return in
309     * milliseconds.
310     */
311    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
312
313    /**
314     * The default response for package verification timeout.
315     *
316     * This can be either PackageManager.VERIFICATION_ALLOW or
317     * PackageManager.VERIFICATION_REJECT.
318     */
319    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
320
321    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
322
323    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
324            DEFAULT_CONTAINER_PACKAGE,
325            "com.android.defcontainer.DefaultContainerService");
326
327    private static final String KILL_APP_REASON_GIDS_CHANGED =
328            "permission grant or revoke changed gids";
329
330    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
331            "permissions revoked";
332
333    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
334
335    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
336
337    /** Permission grant: not grant the permission. */
338    private static final int GRANT_DENIED = 1;
339
340    /** Permission grant: grant the permission as an install permission. */
341    private static final int GRANT_INSTALL = 2;
342
343    /** Permission grant: grant the permission as a runtime one. */
344    private static final int GRANT_RUNTIME = 3;
345
346    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
347    private static final int GRANT_UPGRADE = 4;
348
349    final ServiceThread mHandlerThread;
350
351    final PackageHandler mHandler;
352
353    /**
354     * Messages for {@link #mHandler} that need to wait for system ready before
355     * being dispatched.
356     */
357    private ArrayList<Message> mPostSystemReadyMessages;
358
359    final int mSdkVersion = Build.VERSION.SDK_INT;
360
361    final Context mContext;
362    final boolean mFactoryTest;
363    final boolean mOnlyCore;
364    final boolean mLazyDexOpt;
365    final long mDexOptLRUThresholdInMills;
366    final DisplayMetrics mMetrics;
367    final int mDefParseFlags;
368    final String[] mSeparateProcesses;
369    final boolean mIsUpgrade;
370
371    // This is where all application persistent data goes.
372    final File mAppDataDir;
373
374    // This is where all application persistent data goes for secondary users.
375    final File mUserAppDataDir;
376
377    /** The location for ASEC container files on internal storage. */
378    final String mAsecInternalPath;
379
380    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
381    // LOCK HELD.  Can be called with mInstallLock held.
382    final Installer mInstaller;
383
384    /** Directory where installed third-party apps stored */
385    final File mAppInstallDir;
386
387    /**
388     * Directory to which applications installed internally have their
389     * 32 bit native libraries copied.
390     */
391    private File mAppLib32InstallDir;
392
393    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
394    // apps.
395    final File mDrmAppPrivateInstallDir;
396
397    // ----------------------------------------------------------------
398
399    // Lock for state used when installing and doing other long running
400    // operations.  Methods that must be called with this lock held have
401    // the suffix "LI".
402    final Object mInstallLock = new Object();
403
404    // ----------------------------------------------------------------
405
406    // Keys are String (package name), values are Package.  This also serves
407    // as the lock for the global state.  Methods that must be called with
408    // this lock held have the prefix "LP".
409    final ArrayMap<String, PackageParser.Package> mPackages =
410            new ArrayMap<String, PackageParser.Package>();
411
412    // Tracks available target package names -> overlay package paths.
413    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
414        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
415
416    final Settings mSettings;
417    boolean mRestoredSettings;
418
419    // System configuration read by SystemConfig.
420    final int[] mGlobalGids;
421    final SparseArray<ArraySet<String>> mSystemPermissions;
422    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
423
424    // If mac_permissions.xml was found for seinfo labeling.
425    boolean mFoundPolicyFile;
426
427    // If a recursive restorecon of /data/data/<pkg> is needed.
428    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
429
430    public static final class SharedLibraryEntry {
431        public final String path;
432        public final String apk;
433
434        SharedLibraryEntry(String _path, String _apk) {
435            path = _path;
436            apk = _apk;
437        }
438    }
439
440    // Currently known shared libraries.
441    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
442            new ArrayMap<String, SharedLibraryEntry>();
443
444    // All available activities, for your resolving pleasure.
445    final ActivityIntentResolver mActivities =
446            new ActivityIntentResolver();
447
448    // All available receivers, for your resolving pleasure.
449    final ActivityIntentResolver mReceivers =
450            new ActivityIntentResolver();
451
452    // All available services, for your resolving pleasure.
453    final ServiceIntentResolver mServices = new ServiceIntentResolver();
454
455    // All available providers, for your resolving pleasure.
456    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
457
458    // Mapping from provider base names (first directory in content URI codePath)
459    // to the provider information.
460    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
461            new ArrayMap<String, PackageParser.Provider>();
462
463    // Mapping from instrumentation class names to info about them.
464    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
465            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
466
467    // Mapping from permission names to info about them.
468    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
469            new ArrayMap<String, PackageParser.PermissionGroup>();
470
471    // Packages whose data we have transfered into another package, thus
472    // should no longer exist.
473    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
474
475    // Broadcast actions that are only available to the system.
476    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
477
478    /** List of packages waiting for verification. */
479    final SparseArray<PackageVerificationState> mPendingVerification
480            = new SparseArray<PackageVerificationState>();
481
482    /** Set of packages associated with each app op permission. */
483    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
484
485    final PackageInstallerService mInstallerService;
486
487    private final PackageDexOptimizer mPackageDexOptimizer;
488    // Cache of users who need badging.
489    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
490
491    /** Token for keys in mPendingVerification. */
492    private int mPendingVerificationToken = 0;
493
494    volatile boolean mSystemReady;
495    volatile boolean mSafeMode;
496    volatile boolean mHasSystemUidErrors;
497
498    ApplicationInfo mAndroidApplication;
499    final ActivityInfo mResolveActivity = new ActivityInfo();
500    final ResolveInfo mResolveInfo = new ResolveInfo();
501    ComponentName mResolveComponentName;
502    PackageParser.Package mPlatformPackage;
503    ComponentName mCustomResolverComponentName;
504
505    boolean mResolverReplaced = false;
506
507    // Set of pending broadcasts for aggregating enable/disable of components.
508    static class PendingPackageBroadcasts {
509        // for each user id, a map of <package name -> components within that package>
510        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
511
512        public PendingPackageBroadcasts() {
513            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
514        }
515
516        public ArrayList<String> get(int userId, String packageName) {
517            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
518            return packages.get(packageName);
519        }
520
521        public void put(int userId, String packageName, ArrayList<String> components) {
522            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
523            packages.put(packageName, components);
524        }
525
526        public void remove(int userId, String packageName) {
527            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
528            if (packages != null) {
529                packages.remove(packageName);
530            }
531        }
532
533        public void remove(int userId) {
534            mUidMap.remove(userId);
535        }
536
537        public int userIdCount() {
538            return mUidMap.size();
539        }
540
541        public int userIdAt(int n) {
542            return mUidMap.keyAt(n);
543        }
544
545        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
546            return mUidMap.get(userId);
547        }
548
549        public int size() {
550            // total number of pending broadcast entries across all userIds
551            int num = 0;
552            for (int i = 0; i< mUidMap.size(); i++) {
553                num += mUidMap.valueAt(i).size();
554            }
555            return num;
556        }
557
558        public void clear() {
559            mUidMap.clear();
560        }
561
562        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
563            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
564            if (map == null) {
565                map = new ArrayMap<String, ArrayList<String>>();
566                mUidMap.put(userId, map);
567            }
568            return map;
569        }
570    }
571    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
572
573    // Service Connection to remote media container service to copy
574    // package uri's from external media onto secure containers
575    // or internal storage.
576    private IMediaContainerService mContainerService = null;
577
578    static final int SEND_PENDING_BROADCAST = 1;
579    static final int MCS_BOUND = 3;
580    static final int END_COPY = 4;
581    static final int INIT_COPY = 5;
582    static final int MCS_UNBIND = 6;
583    static final int START_CLEANING_PACKAGE = 7;
584    static final int FIND_INSTALL_LOC = 8;
585    static final int POST_INSTALL = 9;
586    static final int MCS_RECONNECT = 10;
587    static final int MCS_GIVE_UP = 11;
588    static final int UPDATED_MEDIA_STATUS = 12;
589    static final int WRITE_SETTINGS = 13;
590    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
591    static final int PACKAGE_VERIFIED = 15;
592    static final int CHECK_PENDING_VERIFICATION = 16;
593
594    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
595
596    // Delay time in millisecs
597    static final int BROADCAST_DELAY = 10 * 1000;
598
599    static UserManagerService sUserManager;
600
601    // Stores a list of users whose package restrictions file needs to be updated
602    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
603
604    final private DefaultContainerConnection mDefContainerConn =
605            new DefaultContainerConnection();
606    class DefaultContainerConnection implements ServiceConnection {
607        public void onServiceConnected(ComponentName name, IBinder service) {
608            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
609            IMediaContainerService imcs =
610                IMediaContainerService.Stub.asInterface(service);
611            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
612        }
613
614        public void onServiceDisconnected(ComponentName name) {
615            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
616        }
617    };
618
619    // Recordkeeping of restore-after-install operations that are currently in flight
620    // between the Package Manager and the Backup Manager
621    class PostInstallData {
622        public InstallArgs args;
623        public PackageInstalledInfo res;
624
625        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
626            args = _a;
627            res = _r;
628        }
629    };
630    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
631    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
632
633    private final String mRequiredVerifierPackage;
634
635    private final PackageUsage mPackageUsage = new PackageUsage();
636
637    private class PackageUsage {
638        private static final int WRITE_INTERVAL
639            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
640
641        private final Object mFileLock = new Object();
642        private final AtomicLong mLastWritten = new AtomicLong(0);
643        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
644
645        private boolean mIsHistoricalPackageUsageAvailable = true;
646
647        boolean isHistoricalPackageUsageAvailable() {
648            return mIsHistoricalPackageUsageAvailable;
649        }
650
651        void write(boolean force) {
652            if (force) {
653                writeInternal();
654                return;
655            }
656            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
657                && !DEBUG_DEXOPT) {
658                return;
659            }
660            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
661                new Thread("PackageUsage_DiskWriter") {
662                    @Override
663                    public void run() {
664                        try {
665                            writeInternal();
666                        } finally {
667                            mBackgroundWriteRunning.set(false);
668                        }
669                    }
670                }.start();
671            }
672        }
673
674        private void writeInternal() {
675            synchronized (mPackages) {
676                synchronized (mFileLock) {
677                    AtomicFile file = getFile();
678                    FileOutputStream f = null;
679                    try {
680                        f = file.startWrite();
681                        BufferedOutputStream out = new BufferedOutputStream(f);
682                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
683                        StringBuilder sb = new StringBuilder();
684                        for (PackageParser.Package pkg : mPackages.values()) {
685                            if (pkg.mLastPackageUsageTimeInMills == 0) {
686                                continue;
687                            }
688                            sb.setLength(0);
689                            sb.append(pkg.packageName);
690                            sb.append(' ');
691                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
692                            sb.append('\n');
693                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
694                        }
695                        out.flush();
696                        file.finishWrite(f);
697                    } catch (IOException e) {
698                        if (f != null) {
699                            file.failWrite(f);
700                        }
701                        Log.e(TAG, "Failed to write package usage times", e);
702                    }
703                }
704            }
705            mLastWritten.set(SystemClock.elapsedRealtime());
706        }
707
708        void readLP() {
709            synchronized (mFileLock) {
710                AtomicFile file = getFile();
711                BufferedInputStream in = null;
712                try {
713                    in = new BufferedInputStream(file.openRead());
714                    StringBuffer sb = new StringBuffer();
715                    while (true) {
716                        String packageName = readToken(in, sb, ' ');
717                        if (packageName == null) {
718                            break;
719                        }
720                        String timeInMillisString = readToken(in, sb, '\n');
721                        if (timeInMillisString == null) {
722                            throw new IOException("Failed to find last usage time for package "
723                                                  + packageName);
724                        }
725                        PackageParser.Package pkg = mPackages.get(packageName);
726                        if (pkg == null) {
727                            continue;
728                        }
729                        long timeInMillis;
730                        try {
731                            timeInMillis = Long.parseLong(timeInMillisString.toString());
732                        } catch (NumberFormatException e) {
733                            throw new IOException("Failed to parse " + timeInMillisString
734                                                  + " as a long.", e);
735                        }
736                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
737                    }
738                } catch (FileNotFoundException expected) {
739                    mIsHistoricalPackageUsageAvailable = false;
740                } catch (IOException e) {
741                    Log.w(TAG, "Failed to read package usage times", e);
742                } finally {
743                    IoUtils.closeQuietly(in);
744                }
745            }
746            mLastWritten.set(SystemClock.elapsedRealtime());
747        }
748
749        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
750                throws IOException {
751            sb.setLength(0);
752            while (true) {
753                int ch = in.read();
754                if (ch == -1) {
755                    if (sb.length() == 0) {
756                        return null;
757                    }
758                    throw new IOException("Unexpected EOF");
759                }
760                if (ch == endOfToken) {
761                    return sb.toString();
762                }
763                sb.append((char)ch);
764            }
765        }
766
767        private AtomicFile getFile() {
768            File dataDir = Environment.getDataDirectory();
769            File systemDir = new File(dataDir, "system");
770            File fname = new File(systemDir, "package-usage.list");
771            return new AtomicFile(fname);
772        }
773    }
774
775    class PackageHandler extends Handler {
776        private boolean mBound = false;
777        final ArrayList<HandlerParams> mPendingInstalls =
778            new ArrayList<HandlerParams>();
779
780        private boolean connectToService() {
781            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
782                    " DefaultContainerService");
783            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
784            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
785            if (mContext.bindServiceAsUser(service, mDefContainerConn,
786                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
787                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
788                mBound = true;
789                return true;
790            }
791            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
792            return false;
793        }
794
795        private void disconnectService() {
796            mContainerService = null;
797            mBound = false;
798            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
799            mContext.unbindService(mDefContainerConn);
800            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
801        }
802
803        PackageHandler(Looper looper) {
804            super(looper);
805        }
806
807        public void handleMessage(Message msg) {
808            try {
809                doHandleMessage(msg);
810            } finally {
811                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
812            }
813        }
814
815        void doHandleMessage(Message msg) {
816            switch (msg.what) {
817                case INIT_COPY: {
818                    HandlerParams params = (HandlerParams) msg.obj;
819                    int idx = mPendingInstalls.size();
820                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
821                    // If a bind was already initiated we dont really
822                    // need to do anything. The pending install
823                    // will be processed later on.
824                    if (!mBound) {
825                        // If this is the only one pending we might
826                        // have to bind to the service again.
827                        if (!connectToService()) {
828                            Slog.e(TAG, "Failed to bind to media container service");
829                            params.serviceError();
830                            return;
831                        } else {
832                            // Once we bind to the service, the first
833                            // pending request will be processed.
834                            mPendingInstalls.add(idx, params);
835                        }
836                    } else {
837                        mPendingInstalls.add(idx, params);
838                        // Already bound to the service. Just make
839                        // sure we trigger off processing the first request.
840                        if (idx == 0) {
841                            mHandler.sendEmptyMessage(MCS_BOUND);
842                        }
843                    }
844                    break;
845                }
846                case MCS_BOUND: {
847                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
848                    if (msg.obj != null) {
849                        mContainerService = (IMediaContainerService) msg.obj;
850                    }
851                    if (mContainerService == null) {
852                        // Something seriously wrong. Bail out
853                        Slog.e(TAG, "Cannot bind to media container service");
854                        for (HandlerParams params : mPendingInstalls) {
855                            // Indicate service bind error
856                            params.serviceError();
857                        }
858                        mPendingInstalls.clear();
859                    } else if (mPendingInstalls.size() > 0) {
860                        HandlerParams params = mPendingInstalls.get(0);
861                        if (params != null) {
862                            if (params.startCopy()) {
863                                // We are done...  look for more work or to
864                                // go idle.
865                                if (DEBUG_SD_INSTALL) Log.i(TAG,
866                                        "Checking for more work or unbind...");
867                                // Delete pending install
868                                if (mPendingInstalls.size() > 0) {
869                                    mPendingInstalls.remove(0);
870                                }
871                                if (mPendingInstalls.size() == 0) {
872                                    if (mBound) {
873                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
874                                                "Posting delayed MCS_UNBIND");
875                                        removeMessages(MCS_UNBIND);
876                                        Message ubmsg = obtainMessage(MCS_UNBIND);
877                                        // Unbind after a little delay, to avoid
878                                        // continual thrashing.
879                                        sendMessageDelayed(ubmsg, 10000);
880                                    }
881                                } else {
882                                    // There are more pending requests in queue.
883                                    // Just post MCS_BOUND message to trigger processing
884                                    // of next pending install.
885                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
886                                            "Posting MCS_BOUND for next work");
887                                    mHandler.sendEmptyMessage(MCS_BOUND);
888                                }
889                            }
890                        }
891                    } else {
892                        // Should never happen ideally.
893                        Slog.w(TAG, "Empty queue");
894                    }
895                    break;
896                }
897                case MCS_RECONNECT: {
898                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
899                    if (mPendingInstalls.size() > 0) {
900                        if (mBound) {
901                            disconnectService();
902                        }
903                        if (!connectToService()) {
904                            Slog.e(TAG, "Failed to bind to media container service");
905                            for (HandlerParams params : mPendingInstalls) {
906                                // Indicate service bind error
907                                params.serviceError();
908                            }
909                            mPendingInstalls.clear();
910                        }
911                    }
912                    break;
913                }
914                case MCS_UNBIND: {
915                    // If there is no actual work left, then time to unbind.
916                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
917
918                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
919                        if (mBound) {
920                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
921
922                            disconnectService();
923                        }
924                    } else if (mPendingInstalls.size() > 0) {
925                        // There are more pending requests in queue.
926                        // Just post MCS_BOUND message to trigger processing
927                        // of next pending install.
928                        mHandler.sendEmptyMessage(MCS_BOUND);
929                    }
930
931                    break;
932                }
933                case MCS_GIVE_UP: {
934                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
935                    mPendingInstalls.remove(0);
936                    break;
937                }
938                case SEND_PENDING_BROADCAST: {
939                    String packages[];
940                    ArrayList<String> components[];
941                    int size = 0;
942                    int uids[];
943                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
944                    synchronized (mPackages) {
945                        if (mPendingBroadcasts == null) {
946                            return;
947                        }
948                        size = mPendingBroadcasts.size();
949                        if (size <= 0) {
950                            // Nothing to be done. Just return
951                            return;
952                        }
953                        packages = new String[size];
954                        components = new ArrayList[size];
955                        uids = new int[size];
956                        int i = 0;  // filling out the above arrays
957
958                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
959                            int packageUserId = mPendingBroadcasts.userIdAt(n);
960                            Iterator<Map.Entry<String, ArrayList<String>>> it
961                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
962                                            .entrySet().iterator();
963                            while (it.hasNext() && i < size) {
964                                Map.Entry<String, ArrayList<String>> ent = it.next();
965                                packages[i] = ent.getKey();
966                                components[i] = ent.getValue();
967                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
968                                uids[i] = (ps != null)
969                                        ? UserHandle.getUid(packageUserId, ps.appId)
970                                        : -1;
971                                i++;
972                            }
973                        }
974                        size = i;
975                        mPendingBroadcasts.clear();
976                    }
977                    // Send broadcasts
978                    for (int i = 0; i < size; i++) {
979                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
980                    }
981                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
982                    break;
983                }
984                case START_CLEANING_PACKAGE: {
985                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
986                    final String packageName = (String)msg.obj;
987                    final int userId = msg.arg1;
988                    final boolean andCode = msg.arg2 != 0;
989                    synchronized (mPackages) {
990                        if (userId == UserHandle.USER_ALL) {
991                            int[] users = sUserManager.getUserIds();
992                            for (int user : users) {
993                                mSettings.addPackageToCleanLPw(
994                                        new PackageCleanItem(user, packageName, andCode));
995                            }
996                        } else {
997                            mSettings.addPackageToCleanLPw(
998                                    new PackageCleanItem(userId, packageName, andCode));
999                        }
1000                    }
1001                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1002                    startCleaningPackages();
1003                } break;
1004                case POST_INSTALL: {
1005                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1006                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1007                    mRunningInstalls.delete(msg.arg1);
1008                    boolean deleteOld = false;
1009
1010                    if (data != null) {
1011                        InstallArgs args = data.args;
1012                        PackageInstalledInfo res = data.res;
1013
1014                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1015                            res.removedInfo.sendBroadcast(false, true, false);
1016                            Bundle extras = new Bundle(1);
1017                            extras.putInt(Intent.EXTRA_UID, res.uid);
1018
1019                            // Now that we successfully installed the package, grant runtime
1020                            // permissions if requested before broadcasting the install.
1021                            if ((args.installFlags
1022                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1023                                grantRequestedRuntimePermissions(res.pkg,
1024                                        args.user.getIdentifier());
1025                            }
1026
1027                            // Determine the set of users who are adding this
1028                            // package for the first time vs. those who are seeing
1029                            // an update.
1030                            int[] firstUsers;
1031                            int[] updateUsers = new int[0];
1032                            if (res.origUsers == null || res.origUsers.length == 0) {
1033                                firstUsers = res.newUsers;
1034                            } else {
1035                                firstUsers = new int[0];
1036                                for (int i=0; i<res.newUsers.length; i++) {
1037                                    int user = res.newUsers[i];
1038                                    boolean isNew = true;
1039                                    for (int j=0; j<res.origUsers.length; j++) {
1040                                        if (res.origUsers[j] == user) {
1041                                            isNew = false;
1042                                            break;
1043                                        }
1044                                    }
1045                                    if (isNew) {
1046                                        int[] newFirst = new int[firstUsers.length+1];
1047                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1048                                                firstUsers.length);
1049                                        newFirst[firstUsers.length] = user;
1050                                        firstUsers = newFirst;
1051                                    } else {
1052                                        int[] newUpdate = new int[updateUsers.length+1];
1053                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1054                                                updateUsers.length);
1055                                        newUpdate[updateUsers.length] = user;
1056                                        updateUsers = newUpdate;
1057                                    }
1058                                }
1059                            }
1060                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1061                                    res.pkg.applicationInfo.packageName,
1062                                    extras, null, null, firstUsers);
1063                            final boolean update = res.removedInfo.removedPackage != null;
1064                            if (update) {
1065                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1066                            }
1067                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1068                                    res.pkg.applicationInfo.packageName,
1069                                    extras, null, null, updateUsers);
1070                            if (update) {
1071                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1072                                        res.pkg.applicationInfo.packageName,
1073                                        extras, null, null, updateUsers);
1074                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1075                                        null, null,
1076                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1077
1078                                // treat asec-hosted packages like removable media on upgrade
1079                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1080                                    if (DEBUG_INSTALL) {
1081                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1082                                                + " is ASEC-hosted -> AVAILABLE");
1083                                    }
1084                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1085                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1086                                    pkgList.add(res.pkg.applicationInfo.packageName);
1087                                    sendResourcesChangedBroadcast(true, true,
1088                                            pkgList,uidArray, null);
1089                                }
1090                            }
1091                            if (res.removedInfo.args != null) {
1092                                // Remove the replaced package's older resources safely now
1093                                deleteOld = true;
1094                            }
1095
1096                            // Log current value of "unknown sources" setting
1097                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1098                                getUnknownSourcesSettings());
1099                        }
1100                        // Force a gc to clear up things
1101                        Runtime.getRuntime().gc();
1102                        // We delete after a gc for applications  on sdcard.
1103                        if (deleteOld) {
1104                            synchronized (mInstallLock) {
1105                                res.removedInfo.args.doPostDeleteLI(true);
1106                            }
1107                        }
1108                        if (args.observer != null) {
1109                            try {
1110                                Bundle extras = extrasForInstallResult(res);
1111                                args.observer.onPackageInstalled(res.name, res.returnCode,
1112                                        res.returnMsg, extras);
1113                            } catch (RemoteException e) {
1114                                Slog.i(TAG, "Observer no longer exists.");
1115                            }
1116                        }
1117                    } else {
1118                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1119                    }
1120                } break;
1121                case UPDATED_MEDIA_STATUS: {
1122                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1123                    boolean reportStatus = msg.arg1 == 1;
1124                    boolean doGc = msg.arg2 == 1;
1125                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1126                    if (doGc) {
1127                        // Force a gc to clear up stale containers.
1128                        Runtime.getRuntime().gc();
1129                    }
1130                    if (msg.obj != null) {
1131                        @SuppressWarnings("unchecked")
1132                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1133                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1134                        // Unload containers
1135                        unloadAllContainers(args);
1136                    }
1137                    if (reportStatus) {
1138                        try {
1139                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1140                            PackageHelper.getMountService().finishMediaUpdate();
1141                        } catch (RemoteException e) {
1142                            Log.e(TAG, "MountService not running?");
1143                        }
1144                    }
1145                } break;
1146                case WRITE_SETTINGS: {
1147                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1148                    synchronized (mPackages) {
1149                        removeMessages(WRITE_SETTINGS);
1150                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1151                        mSettings.writeLPr();
1152                        mDirtyUsers.clear();
1153                    }
1154                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1155                } break;
1156                case WRITE_PACKAGE_RESTRICTIONS: {
1157                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1158                    synchronized (mPackages) {
1159                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1160                        for (int userId : mDirtyUsers) {
1161                            mSettings.writePackageRestrictionsLPr(userId);
1162                        }
1163                        mDirtyUsers.clear();
1164                    }
1165                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1166                } break;
1167                case CHECK_PENDING_VERIFICATION: {
1168                    final int verificationId = msg.arg1;
1169                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1170
1171                    if ((state != null) && !state.timeoutExtended()) {
1172                        final InstallArgs args = state.getInstallArgs();
1173                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1174
1175                        Slog.i(TAG, "Verification timed out for " + originUri);
1176                        mPendingVerification.remove(verificationId);
1177
1178                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1179
1180                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1181                            Slog.i(TAG, "Continuing with installation of " + originUri);
1182                            state.setVerifierResponse(Binder.getCallingUid(),
1183                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1184                            broadcastPackageVerified(verificationId, originUri,
1185                                    PackageManager.VERIFICATION_ALLOW,
1186                                    state.getInstallArgs().getUser());
1187                            try {
1188                                ret = args.copyApk(mContainerService, true);
1189                            } catch (RemoteException e) {
1190                                Slog.e(TAG, "Could not contact the ContainerService");
1191                            }
1192                        } else {
1193                            broadcastPackageVerified(verificationId, originUri,
1194                                    PackageManager.VERIFICATION_REJECT,
1195                                    state.getInstallArgs().getUser());
1196                        }
1197
1198                        processPendingInstall(args, ret);
1199                        mHandler.sendEmptyMessage(MCS_UNBIND);
1200                    }
1201                    break;
1202                }
1203                case PACKAGE_VERIFIED: {
1204                    final int verificationId = msg.arg1;
1205
1206                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1207                    if (state == null) {
1208                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1209                        break;
1210                    }
1211
1212                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1213
1214                    state.setVerifierResponse(response.callerUid, response.code);
1215
1216                    if (state.isVerificationComplete()) {
1217                        mPendingVerification.remove(verificationId);
1218
1219                        final InstallArgs args = state.getInstallArgs();
1220                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1221
1222                        int ret;
1223                        if (state.isInstallAllowed()) {
1224                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1225                            broadcastPackageVerified(verificationId, originUri,
1226                                    response.code, state.getInstallArgs().getUser());
1227                            try {
1228                                ret = args.copyApk(mContainerService, true);
1229                            } catch (RemoteException e) {
1230                                Slog.e(TAG, "Could not contact the ContainerService");
1231                            }
1232                        } else {
1233                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1234                        }
1235
1236                        processPendingInstall(args, ret);
1237
1238                        mHandler.sendEmptyMessage(MCS_UNBIND);
1239                    }
1240
1241                    break;
1242                }
1243            }
1244        }
1245    }
1246
1247    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1248        if (userId >= UserHandle.USER_OWNER) {
1249            grantRequestedRuntimePermissionsForUser(pkg, userId);
1250        } else if (userId == UserHandle.USER_ALL) {
1251            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1252                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1253            }
1254        }
1255    }
1256
1257    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1258        SettingBase sb = (SettingBase) pkg.mExtras;
1259        if (sb == null) {
1260            return;
1261        }
1262
1263        PermissionsState permissionsState = sb.getPermissionsState();
1264
1265        for (String permission : pkg.requestedPermissions) {
1266            BasePermission bp = mSettings.mPermissions.get(permission);
1267            if (bp != null && bp.isRuntime()) {
1268                permissionsState.grantRuntimePermission(bp, userId);
1269            }
1270        }
1271    }
1272
1273    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1274        Bundle extras = null;
1275        switch (res.returnCode) {
1276            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1277                extras = new Bundle();
1278                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1279                        res.origPermission);
1280                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1281                        res.origPackage);
1282                break;
1283            }
1284        }
1285        return extras;
1286    }
1287
1288    void scheduleWriteSettingsLocked() {
1289        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1290            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1291        }
1292    }
1293
1294    void scheduleWritePackageRestrictionsLocked(int userId) {
1295        if (!sUserManager.exists(userId)) return;
1296        mDirtyUsers.add(userId);
1297        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1298            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1299        }
1300    }
1301
1302    public static PackageManagerService main(Context context, Installer installer,
1303            boolean factoryTest, boolean onlyCore) {
1304        PackageManagerService m = new PackageManagerService(context, installer,
1305                factoryTest, onlyCore);
1306        ServiceManager.addService("package", m);
1307        return m;
1308    }
1309
1310    static String[] splitString(String str, char sep) {
1311        int count = 1;
1312        int i = 0;
1313        while ((i=str.indexOf(sep, i)) >= 0) {
1314            count++;
1315            i++;
1316        }
1317
1318        String[] res = new String[count];
1319        i=0;
1320        count = 0;
1321        int lastI=0;
1322        while ((i=str.indexOf(sep, i)) >= 0) {
1323            res[count] = str.substring(lastI, i);
1324            count++;
1325            i++;
1326            lastI = i;
1327        }
1328        res[count] = str.substring(lastI, str.length());
1329        return res;
1330    }
1331
1332    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1333        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1334                Context.DISPLAY_SERVICE);
1335        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1336    }
1337
1338    public PackageManagerService(Context context, Installer installer,
1339            boolean factoryTest, boolean onlyCore) {
1340        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1341                SystemClock.uptimeMillis());
1342
1343        if (mSdkVersion <= 0) {
1344            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1345        }
1346
1347        mContext = context;
1348        mFactoryTest = factoryTest;
1349        mOnlyCore = onlyCore;
1350        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1351        mMetrics = new DisplayMetrics();
1352        mSettings = new Settings(mContext, mPackages);
1353        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1354                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1355        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1356                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1357        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1358                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1359        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1360                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1361        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1362                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1363        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1364                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1365
1366        // TODO: add a property to control this?
1367        long dexOptLRUThresholdInMinutes;
1368        if (mLazyDexOpt) {
1369            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1370        } else {
1371            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1372        }
1373        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1374
1375        String separateProcesses = SystemProperties.get("debug.separate_processes");
1376        if (separateProcesses != null && separateProcesses.length() > 0) {
1377            if ("*".equals(separateProcesses)) {
1378                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1379                mSeparateProcesses = null;
1380                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1381            } else {
1382                mDefParseFlags = 0;
1383                mSeparateProcesses = separateProcesses.split(",");
1384                Slog.w(TAG, "Running with debug.separate_processes: "
1385                        + separateProcesses);
1386            }
1387        } else {
1388            mDefParseFlags = 0;
1389            mSeparateProcesses = null;
1390        }
1391
1392        mInstaller = installer;
1393        mPackageDexOptimizer = new PackageDexOptimizer(this);
1394
1395        getDefaultDisplayMetrics(context, mMetrics);
1396
1397        SystemConfig systemConfig = SystemConfig.getInstance();
1398        mGlobalGids = systemConfig.getGlobalGids();
1399        mSystemPermissions = systemConfig.getSystemPermissions();
1400        mAvailableFeatures = systemConfig.getAvailableFeatures();
1401
1402        synchronized (mInstallLock) {
1403        // writer
1404        synchronized (mPackages) {
1405            mHandlerThread = new ServiceThread(TAG,
1406                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1407            mHandlerThread.start();
1408            mHandler = new PackageHandler(mHandlerThread.getLooper());
1409            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1410
1411            File dataDir = Environment.getDataDirectory();
1412            mAppDataDir = new File(dataDir, "data");
1413            mAppInstallDir = new File(dataDir, "app");
1414            mAppLib32InstallDir = new File(dataDir, "app-lib");
1415            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1416            mUserAppDataDir = new File(dataDir, "user");
1417            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1418
1419            sUserManager = new UserManagerService(context, this,
1420                    mInstallLock, mPackages);
1421
1422            // Propagate permission configuration in to package manager.
1423            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1424                    = systemConfig.getPermissions();
1425            for (int i=0; i<permConfig.size(); i++) {
1426                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1427                BasePermission bp = mSettings.mPermissions.get(perm.name);
1428                if (bp == null) {
1429                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1430                    mSettings.mPermissions.put(perm.name, bp);
1431                }
1432                if (perm.gids != null) {
1433                    bp.setGids(perm.gids, perm.perUser);
1434                }
1435            }
1436
1437            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1438            for (int i=0; i<libConfig.size(); i++) {
1439                mSharedLibraries.put(libConfig.keyAt(i),
1440                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1441            }
1442
1443            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1444
1445            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1446                    mSdkVersion, mOnlyCore);
1447
1448            String customResolverActivity = Resources.getSystem().getString(
1449                    R.string.config_customResolverActivity);
1450            if (TextUtils.isEmpty(customResolverActivity)) {
1451                customResolverActivity = null;
1452            } else {
1453                mCustomResolverComponentName = ComponentName.unflattenFromString(
1454                        customResolverActivity);
1455            }
1456
1457            long startTime = SystemClock.uptimeMillis();
1458
1459            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1460                    startTime);
1461
1462            // Set flag to monitor and not change apk file paths when
1463            // scanning install directories.
1464            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1465
1466            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1467
1468            /**
1469             * Add everything in the in the boot class path to the
1470             * list of process files because dexopt will have been run
1471             * if necessary during zygote startup.
1472             */
1473            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1474            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1475
1476            if (bootClassPath != null) {
1477                String[] bootClassPathElements = splitString(bootClassPath, ':');
1478                for (String element : bootClassPathElements) {
1479                    alreadyDexOpted.add(element);
1480                }
1481            } else {
1482                Slog.w(TAG, "No BOOTCLASSPATH found!");
1483            }
1484
1485            if (systemServerClassPath != null) {
1486                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1487                for (String element : systemServerClassPathElements) {
1488                    alreadyDexOpted.add(element);
1489                }
1490            } else {
1491                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1492            }
1493
1494            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1495            final String[] dexCodeInstructionSets =
1496                    getDexCodeInstructionSets(
1497                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1498
1499            /**
1500             * Ensure all external libraries have had dexopt run on them.
1501             */
1502            if (mSharedLibraries.size() > 0) {
1503                // NOTE: For now, we're compiling these system "shared libraries"
1504                // (and framework jars) into all available architectures. It's possible
1505                // to compile them only when we come across an app that uses them (there's
1506                // already logic for that in scanPackageLI) but that adds some complexity.
1507                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1508                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1509                        final String lib = libEntry.path;
1510                        if (lib == null) {
1511                            continue;
1512                        }
1513
1514                        try {
1515                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1516                                                                                 dexCodeInstructionSet,
1517                                                                                 false);
1518                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1519                                alreadyDexOpted.add(lib);
1520
1521                                // The list of "shared libraries" we have at this point is
1522                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1523                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1524                                } else {
1525                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1526                                }
1527                            }
1528                        } catch (FileNotFoundException e) {
1529                            Slog.w(TAG, "Library not found: " + lib);
1530                        } catch (IOException e) {
1531                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1532                                    + e.getMessage());
1533                        }
1534                    }
1535                }
1536            }
1537
1538            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1539
1540            // Gross hack for now: we know this file doesn't contain any
1541            // code, so don't dexopt it to avoid the resulting log spew.
1542            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1543
1544            // Gross hack for now: we know this file is only part of
1545            // the boot class path for art, so don't dexopt it to
1546            // avoid the resulting log spew.
1547            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1548
1549            /**
1550             * And there are a number of commands implemented in Java, which
1551             * we currently need to do the dexopt on so that they can be
1552             * run from a non-root shell.
1553             */
1554            String[] frameworkFiles = frameworkDir.list();
1555            if (frameworkFiles != null) {
1556                // TODO: We could compile these only for the most preferred ABI. We should
1557                // first double check that the dex files for these commands are not referenced
1558                // by other system apps.
1559                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1560                    for (int i=0; i<frameworkFiles.length; i++) {
1561                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1562                        String path = libPath.getPath();
1563                        // Skip the file if we already did it.
1564                        if (alreadyDexOpted.contains(path)) {
1565                            continue;
1566                        }
1567                        // Skip the file if it is not a type we want to dexopt.
1568                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1569                            continue;
1570                        }
1571                        try {
1572                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1573                                                                                 dexCodeInstructionSet,
1574                                                                                 false);
1575                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1576                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1577                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1578                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1579                            }
1580                        } catch (FileNotFoundException e) {
1581                            Slog.w(TAG, "Jar not found: " + path);
1582                        } catch (IOException e) {
1583                            Slog.w(TAG, "Exception reading jar: " + path, e);
1584                        }
1585                    }
1586                }
1587            }
1588
1589            // Collect vendor overlay packages.
1590            // (Do this before scanning any apps.)
1591            // For security and version matching reason, only consider
1592            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1593            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1594            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1595                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1596
1597            // Find base frameworks (resource packages without code).
1598            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1599                    | PackageParser.PARSE_IS_SYSTEM_DIR
1600                    | PackageParser.PARSE_IS_PRIVILEGED,
1601                    scanFlags | SCAN_NO_DEX, 0);
1602
1603            // Collected privileged system packages.
1604            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1605            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1606                    | PackageParser.PARSE_IS_SYSTEM_DIR
1607                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1608
1609            // Collect ordinary system packages.
1610            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1611            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1612                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1613
1614            // Collect all vendor packages.
1615            File vendorAppDir = new File("/vendor/app");
1616            try {
1617                vendorAppDir = vendorAppDir.getCanonicalFile();
1618            } catch (IOException e) {
1619                // failed to look up canonical path, continue with original one
1620            }
1621            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1622                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1623
1624            // Collect all OEM packages.
1625            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1626            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1627                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1628
1629            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1630            mInstaller.moveFiles();
1631
1632            // Prune any system packages that no longer exist.
1633            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1634            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1635            if (!mOnlyCore) {
1636                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1637                while (psit.hasNext()) {
1638                    PackageSetting ps = psit.next();
1639
1640                    /*
1641                     * If this is not a system app, it can't be a
1642                     * disable system app.
1643                     */
1644                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1645                        continue;
1646                    }
1647
1648                    /*
1649                     * If the package is scanned, it's not erased.
1650                     */
1651                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1652                    if (scannedPkg != null) {
1653                        /*
1654                         * If the system app is both scanned and in the
1655                         * disabled packages list, then it must have been
1656                         * added via OTA. Remove it from the currently
1657                         * scanned package so the previously user-installed
1658                         * application can be scanned.
1659                         */
1660                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1661                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1662                                    + ps.name + "; removing system app.  Last known codePath="
1663                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1664                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1665                                    + scannedPkg.mVersionCode);
1666                            removePackageLI(ps, true);
1667                            expectingBetter.put(ps.name, ps.codePath);
1668                        }
1669
1670                        continue;
1671                    }
1672
1673                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1674                        psit.remove();
1675                        logCriticalInfo(Log.WARN, "System package " + ps.name
1676                                + " no longer exists; wiping its data");
1677                        removeDataDirsLI(ps.name);
1678                    } else {
1679                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1680                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1681                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1682                        }
1683                    }
1684                }
1685            }
1686
1687            //look for any incomplete package installations
1688            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1689            //clean up list
1690            for(int i = 0; i < deletePkgsList.size(); i++) {
1691                //clean up here
1692                cleanupInstallFailedPackage(deletePkgsList.get(i));
1693            }
1694            //delete tmp files
1695            deleteTempPackageFiles();
1696
1697            // Remove any shared userIDs that have no associated packages
1698            mSettings.pruneSharedUsersLPw();
1699
1700            if (!mOnlyCore) {
1701                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1702                        SystemClock.uptimeMillis());
1703                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
1704
1705                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1706                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
1707
1708                /**
1709                 * Remove disable package settings for any updated system
1710                 * apps that were removed via an OTA. If they're not a
1711                 * previously-updated app, remove them completely.
1712                 * Otherwise, just revoke their system-level permissions.
1713                 */
1714                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1715                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1716                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1717
1718                    String msg;
1719                    if (deletedPkg == null) {
1720                        msg = "Updated system package " + deletedAppName
1721                                + " no longer exists; wiping its data";
1722                        removeDataDirsLI(deletedAppName);
1723                    } else {
1724                        msg = "Updated system app + " + deletedAppName
1725                                + " no longer present; removing system privileges for "
1726                                + deletedAppName;
1727
1728                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1729
1730                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1731                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1732                    }
1733                    logCriticalInfo(Log.WARN, msg);
1734                }
1735
1736                /**
1737                 * Make sure all system apps that we expected to appear on
1738                 * the userdata partition actually showed up. If they never
1739                 * appeared, crawl back and revive the system version.
1740                 */
1741                for (int i = 0; i < expectingBetter.size(); i++) {
1742                    final String packageName = expectingBetter.keyAt(i);
1743                    if (!mPackages.containsKey(packageName)) {
1744                        final File scanFile = expectingBetter.valueAt(i);
1745
1746                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1747                                + " but never showed up; reverting to system");
1748
1749                        final int reparseFlags;
1750                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1751                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1752                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1753                                    | PackageParser.PARSE_IS_PRIVILEGED;
1754                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1755                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1756                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1757                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1758                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1759                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1760                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1761                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1762                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1763                        } else {
1764                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1765                            continue;
1766                        }
1767
1768                        mSettings.enableSystemPackageLPw(packageName);
1769
1770                        try {
1771                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1772                        } catch (PackageManagerException e) {
1773                            Slog.e(TAG, "Failed to parse original system package: "
1774                                    + e.getMessage());
1775                        }
1776                    }
1777                }
1778            }
1779
1780            // Now that we know all of the shared libraries, update all clients to have
1781            // the correct library paths.
1782            updateAllSharedLibrariesLPw();
1783
1784            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1785                // NOTE: We ignore potential failures here during a system scan (like
1786                // the rest of the commands above) because there's precious little we
1787                // can do about it. A settings error is reported, though.
1788                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1789                        false /* force dexopt */, false /* defer dexopt */);
1790            }
1791
1792            // Now that we know all the packages we are keeping,
1793            // read and update their last usage times.
1794            mPackageUsage.readLP();
1795
1796            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1797                    SystemClock.uptimeMillis());
1798            Slog.i(TAG, "Time to scan packages: "
1799                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1800                    + " seconds");
1801
1802            // If the platform SDK has changed since the last time we booted,
1803            // we need to re-grant app permission to catch any new ones that
1804            // appear.  This is really a hack, and means that apps can in some
1805            // cases get permissions that the user didn't initially explicitly
1806            // allow...  it would be nice to have some better way to handle
1807            // this situation.
1808            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1809                    != mSdkVersion;
1810            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1811                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1812                    + "; regranting permissions for internal storage");
1813            mSettings.mInternalSdkPlatform = mSdkVersion;
1814
1815            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1816                    | (regrantPermissions
1817                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1818                            : 0));
1819
1820            // If this is the first boot, and it is a normal boot, then
1821            // we need to initialize the default preferred apps.
1822            if (!mRestoredSettings && !onlyCore) {
1823                mSettings.readDefaultPreferredAppsLPw(this, 0);
1824            }
1825
1826            // If this is first boot after an OTA, and a normal boot, then
1827            // we need to clear code cache directories.
1828            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1829            if (mIsUpgrade && !onlyCore) {
1830                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1831                for (String pkgName : mSettings.mPackages.keySet()) {
1832                    deleteCodeCacheDirsLI(pkgName);
1833                }
1834                mSettings.mFingerprint = Build.FINGERPRINT;
1835            }
1836
1837            // All the changes are done during package scanning.
1838            mSettings.updateInternalDatabaseVersion();
1839
1840            // can downgrade to reader
1841            mSettings.writeLPr();
1842
1843            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1844                    SystemClock.uptimeMillis());
1845
1846
1847            mRequiredVerifierPackage = getRequiredVerifierLPr();
1848        } // synchronized (mPackages)
1849        } // synchronized (mInstallLock)
1850
1851        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1852
1853        // Now after opening every single application zip, make sure they
1854        // are all flushed.  Not really needed, but keeps things nice and
1855        // tidy.
1856        Runtime.getRuntime().gc();
1857    }
1858
1859    @Override
1860    public boolean isFirstBoot() {
1861        return !mRestoredSettings;
1862    }
1863
1864    @Override
1865    public boolean isOnlyCoreApps() {
1866        return mOnlyCore;
1867    }
1868
1869    @Override
1870    public boolean isUpgrade() {
1871        return mIsUpgrade;
1872    }
1873
1874    private String getRequiredVerifierLPr() {
1875        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1876        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1877                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1878
1879        String requiredVerifier = null;
1880
1881        final int N = receivers.size();
1882        for (int i = 0; i < N; i++) {
1883            final ResolveInfo info = receivers.get(i);
1884
1885            if (info.activityInfo == null) {
1886                continue;
1887            }
1888
1889            final String packageName = info.activityInfo.packageName;
1890
1891            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
1892                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
1893                continue;
1894            }
1895
1896            if (requiredVerifier != null) {
1897                throw new RuntimeException("There can be only one required verifier");
1898            }
1899
1900            requiredVerifier = packageName;
1901        }
1902
1903        return requiredVerifier;
1904    }
1905
1906    @Override
1907    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1908            throws RemoteException {
1909        try {
1910            return super.onTransact(code, data, reply, flags);
1911        } catch (RuntimeException e) {
1912            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1913                Slog.wtf(TAG, "Package Manager Crash", e);
1914            }
1915            throw e;
1916        }
1917    }
1918
1919    void cleanupInstallFailedPackage(PackageSetting ps) {
1920        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1921
1922        removeDataDirsLI(ps.name);
1923        if (ps.codePath != null) {
1924            if (ps.codePath.isDirectory()) {
1925                FileUtils.deleteContents(ps.codePath);
1926            }
1927            ps.codePath.delete();
1928        }
1929        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1930            if (ps.resourcePath.isDirectory()) {
1931                FileUtils.deleteContents(ps.resourcePath);
1932            }
1933            ps.resourcePath.delete();
1934        }
1935        mSettings.removePackageLPw(ps.name);
1936    }
1937
1938    static int[] appendInts(int[] cur, int[] add) {
1939        if (add == null) return cur;
1940        if (cur == null) return add;
1941        final int N = add.length;
1942        for (int i=0; i<N; i++) {
1943            cur = appendInt(cur, add[i]);
1944        }
1945        return cur;
1946    }
1947
1948    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1949        if (!sUserManager.exists(userId)) return null;
1950        final PackageSetting ps = (PackageSetting) p.mExtras;
1951        if (ps == null) {
1952            return null;
1953        }
1954
1955        final PermissionsState permissionsState = ps.getPermissionsState();
1956
1957        final int[] gids = permissionsState.computeGids(userId);
1958        final Set<String> permissions = permissionsState.getPermissions(userId);
1959        final PackageUserState state = ps.readUserState(userId);
1960
1961        return PackageParser.generatePackageInfo(p, gids, flags,
1962                ps.firstInstallTime, ps.lastUpdateTime, permissions, 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        // If we're only installing presumed-existing packages, require that the
5264        // scanned APK is both already known and at the path previously established
5265        // for it.  Previously unknown packages we pick up normally, but if we have an
5266        // a priori expectation about this package's install presence, enforce it.
5267        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5268            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5269            if (known != null) {
5270                if (DEBUG_PACKAGE_SCANNING) {
5271                    Log.d(TAG, "Examining " + pkg.codePath
5272                            + " and requiring known paths " + known.codePathString
5273                            + " & " + known.resourcePathString);
5274                }
5275                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5276                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5277                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5278                            "Application package " + pkg.packageName
5279                            + " found at " + pkg.applicationInfo.getCodePath()
5280                            + " but expected at " + known.codePathString + "; ignoring.");
5281                }
5282            }
5283        }
5284
5285        // Initialize package source and resource directories
5286        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5287        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5288
5289        SharedUserSetting suid = null;
5290        PackageSetting pkgSetting = null;
5291
5292        if (!isSystemApp(pkg)) {
5293            // Only system apps can use these features.
5294            pkg.mOriginalPackages = null;
5295            pkg.mRealPackage = null;
5296            pkg.mAdoptPermissions = null;
5297        }
5298
5299        // writer
5300        synchronized (mPackages) {
5301            if (pkg.mSharedUserId != null) {
5302                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5303                if (suid == null) {
5304                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5305                            "Creating application package " + pkg.packageName
5306                            + " for shared user failed");
5307                }
5308                if (DEBUG_PACKAGE_SCANNING) {
5309                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5310                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5311                                + "): packages=" + suid.packages);
5312                }
5313            }
5314
5315            // Check if we are renaming from an original package name.
5316            PackageSetting origPackage = null;
5317            String realName = null;
5318            if (pkg.mOriginalPackages != null) {
5319                // This package may need to be renamed to a previously
5320                // installed name.  Let's check on that...
5321                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5322                if (pkg.mOriginalPackages.contains(renamed)) {
5323                    // This package had originally been installed as the
5324                    // original name, and we have already taken care of
5325                    // transitioning to the new one.  Just update the new
5326                    // one to continue using the old name.
5327                    realName = pkg.mRealPackage;
5328                    if (!pkg.packageName.equals(renamed)) {
5329                        // Callers into this function may have already taken
5330                        // care of renaming the package; only do it here if
5331                        // it is not already done.
5332                        pkg.setPackageName(renamed);
5333                    }
5334
5335                } else {
5336                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5337                        if ((origPackage = mSettings.peekPackageLPr(
5338                                pkg.mOriginalPackages.get(i))) != null) {
5339                            // We do have the package already installed under its
5340                            // original name...  should we use it?
5341                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5342                                // New package is not compatible with original.
5343                                origPackage = null;
5344                                continue;
5345                            } else if (origPackage.sharedUser != null) {
5346                                // Make sure uid is compatible between packages.
5347                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5348                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5349                                            + " to " + pkg.packageName + ": old uid "
5350                                            + origPackage.sharedUser.name
5351                                            + " differs from " + pkg.mSharedUserId);
5352                                    origPackage = null;
5353                                    continue;
5354                                }
5355                            } else {
5356                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5357                                        + pkg.packageName + " to old name " + origPackage.name);
5358                            }
5359                            break;
5360                        }
5361                    }
5362                }
5363            }
5364
5365            if (mTransferedPackages.contains(pkg.packageName)) {
5366                Slog.w(TAG, "Package " + pkg.packageName
5367                        + " was transferred to another, but its .apk remains");
5368            }
5369
5370            // Just create the setting, don't add it yet. For already existing packages
5371            // the PkgSetting exists already and doesn't have to be created.
5372            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5373                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5374                    pkg.applicationInfo.primaryCpuAbi,
5375                    pkg.applicationInfo.secondaryCpuAbi,
5376                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5377                    user, false);
5378            if (pkgSetting == null) {
5379                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5380                        "Creating application package " + pkg.packageName + " failed");
5381            }
5382
5383            if (pkgSetting.origPackage != null) {
5384                // If we are first transitioning from an original package,
5385                // fix up the new package's name now.  We need to do this after
5386                // looking up the package under its new name, so getPackageLP
5387                // can take care of fiddling things correctly.
5388                pkg.setPackageName(origPackage.name);
5389
5390                // File a report about this.
5391                String msg = "New package " + pkgSetting.realName
5392                        + " renamed to replace old package " + pkgSetting.name;
5393                reportSettingsProblem(Log.WARN, msg);
5394
5395                // Make a note of it.
5396                mTransferedPackages.add(origPackage.name);
5397
5398                // No longer need to retain this.
5399                pkgSetting.origPackage = null;
5400            }
5401
5402            if (realName != null) {
5403                // Make a note of it.
5404                mTransferedPackages.add(pkg.packageName);
5405            }
5406
5407            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5408                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5409            }
5410
5411            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5412                // Check all shared libraries and map to their actual file path.
5413                // We only do this here for apps not on a system dir, because those
5414                // are the only ones that can fail an install due to this.  We
5415                // will take care of the system apps by updating all of their
5416                // library paths after the scan is done.
5417                updateSharedLibrariesLPw(pkg, null);
5418            }
5419
5420            if (mFoundPolicyFile) {
5421                SELinuxMMAC.assignSeinfoValue(pkg);
5422            }
5423
5424            pkg.applicationInfo.uid = pkgSetting.appId;
5425            pkg.mExtras = pkgSetting;
5426            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5427                try {
5428                    verifySignaturesLP(pkgSetting, pkg);
5429                    // We just determined the app is signed correctly, so bring
5430                    // over the latest parsed certs.
5431                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5432                } catch (PackageManagerException e) {
5433                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5434                        throw e;
5435                    }
5436                    // The signature has changed, but this package is in the system
5437                    // image...  let's recover!
5438                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5439                    // However...  if this package is part of a shared user, but it
5440                    // doesn't match the signature of the shared user, let's fail.
5441                    // What this means is that you can't change the signatures
5442                    // associated with an overall shared user, which doesn't seem all
5443                    // that unreasonable.
5444                    if (pkgSetting.sharedUser != null) {
5445                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5446                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5447                            throw new PackageManagerException(
5448                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5449                                            "Signature mismatch for shared user : "
5450                                            + pkgSetting.sharedUser);
5451                        }
5452                    }
5453                    // File a report about this.
5454                    String msg = "System package " + pkg.packageName
5455                        + " signature changed; retaining data.";
5456                    reportSettingsProblem(Log.WARN, msg);
5457                }
5458            } else {
5459                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5460                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5461                            + pkg.packageName + " upgrade keys do not match the "
5462                            + "previously installed version");
5463                } else {
5464                    // We just determined the app is signed correctly, so bring
5465                    // over the latest parsed certs.
5466                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5467                }
5468            }
5469            // Verify that this new package doesn't have any content providers
5470            // that conflict with existing packages.  Only do this if the
5471            // package isn't already installed, since we don't want to break
5472            // things that are installed.
5473            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5474                final int N = pkg.providers.size();
5475                int i;
5476                for (i=0; i<N; i++) {
5477                    PackageParser.Provider p = pkg.providers.get(i);
5478                    if (p.info.authority != null) {
5479                        String names[] = p.info.authority.split(";");
5480                        for (int j = 0; j < names.length; j++) {
5481                            if (mProvidersByAuthority.containsKey(names[j])) {
5482                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5483                                final String otherPackageName =
5484                                        ((other != null && other.getComponentName() != null) ?
5485                                                other.getComponentName().getPackageName() : "?");
5486                                throw new PackageManagerException(
5487                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5488                                                "Can't install because provider name " + names[j]
5489                                                + " (in package " + pkg.applicationInfo.packageName
5490                                                + ") is already used by " + otherPackageName);
5491                            }
5492                        }
5493                    }
5494                }
5495            }
5496
5497            if (pkg.mAdoptPermissions != null) {
5498                // This package wants to adopt ownership of permissions from
5499                // another package.
5500                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5501                    final String origName = pkg.mAdoptPermissions.get(i);
5502                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5503                    if (orig != null) {
5504                        if (verifyPackageUpdateLPr(orig, pkg)) {
5505                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5506                                    + pkg.packageName);
5507                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5508                        }
5509                    }
5510                }
5511            }
5512        }
5513
5514        final String pkgName = pkg.packageName;
5515
5516        final long scanFileTime = scanFile.lastModified();
5517        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5518        pkg.applicationInfo.processName = fixProcessName(
5519                pkg.applicationInfo.packageName,
5520                pkg.applicationInfo.processName,
5521                pkg.applicationInfo.uid);
5522
5523        File dataPath;
5524        if (mPlatformPackage == pkg) {
5525            // The system package is special.
5526            dataPath = new File(Environment.getDataDirectory(), "system");
5527
5528            pkg.applicationInfo.dataDir = dataPath.getPath();
5529
5530        } else {
5531            // This is a normal package, need to make its data directory.
5532            dataPath = getDataPathForPackage(pkg.packageName, 0);
5533
5534            boolean uidError = false;
5535            if (dataPath.exists()) {
5536                int currentUid = 0;
5537                try {
5538                    StructStat stat = Os.stat(dataPath.getPath());
5539                    currentUid = stat.st_uid;
5540                } catch (ErrnoException e) {
5541                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5542                }
5543
5544                // If we have mismatched owners for the data path, we have a problem.
5545                if (currentUid != pkg.applicationInfo.uid) {
5546                    boolean recovered = false;
5547                    if (currentUid == 0) {
5548                        // The directory somehow became owned by root.  Wow.
5549                        // This is probably because the system was stopped while
5550                        // installd was in the middle of messing with its libs
5551                        // directory.  Ask installd to fix that.
5552                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5553                                pkg.applicationInfo.uid);
5554                        if (ret >= 0) {
5555                            recovered = true;
5556                            String msg = "Package " + pkg.packageName
5557                                    + " unexpectedly changed to uid 0; recovered to " +
5558                                    + pkg.applicationInfo.uid;
5559                            reportSettingsProblem(Log.WARN, msg);
5560                        }
5561                    }
5562                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5563                            || (scanFlags&SCAN_BOOTING) != 0)) {
5564                        // If this is a system app, we can at least delete its
5565                        // current data so the application will still work.
5566                        int ret = removeDataDirsLI(pkgName);
5567                        if (ret >= 0) {
5568                            // TODO: Kill the processes first
5569                            // Old data gone!
5570                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5571                                    ? "System package " : "Third party package ";
5572                            String msg = prefix + pkg.packageName
5573                                    + " has changed from uid: "
5574                                    + currentUid + " to "
5575                                    + pkg.applicationInfo.uid + "; old data erased";
5576                            reportSettingsProblem(Log.WARN, msg);
5577                            recovered = true;
5578
5579                            // And now re-install the app.
5580                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5581                                                   pkg.applicationInfo.seinfo);
5582                            if (ret == -1) {
5583                                // Ack should not happen!
5584                                msg = prefix + pkg.packageName
5585                                        + " could not have data directory re-created after delete.";
5586                                reportSettingsProblem(Log.WARN, msg);
5587                                throw new PackageManagerException(
5588                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5589                            }
5590                        }
5591                        if (!recovered) {
5592                            mHasSystemUidErrors = true;
5593                        }
5594                    } else if (!recovered) {
5595                        // If we allow this install to proceed, we will be broken.
5596                        // Abort, abort!
5597                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5598                                "scanPackageLI");
5599                    }
5600                    if (!recovered) {
5601                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5602                            + pkg.applicationInfo.uid + "/fs_"
5603                            + currentUid;
5604                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5605                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5606                        String msg = "Package " + pkg.packageName
5607                                + " has mismatched uid: "
5608                                + currentUid + " on disk, "
5609                                + pkg.applicationInfo.uid + " in settings";
5610                        // writer
5611                        synchronized (mPackages) {
5612                            mSettings.mReadMessages.append(msg);
5613                            mSettings.mReadMessages.append('\n');
5614                            uidError = true;
5615                            if (!pkgSetting.uidError) {
5616                                reportSettingsProblem(Log.ERROR, msg);
5617                            }
5618                        }
5619                    }
5620                }
5621                pkg.applicationInfo.dataDir = dataPath.getPath();
5622                if (mShouldRestoreconData) {
5623                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5624                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5625                                pkg.applicationInfo.uid);
5626                }
5627            } else {
5628                if (DEBUG_PACKAGE_SCANNING) {
5629                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5630                        Log.v(TAG, "Want this data dir: " + dataPath);
5631                }
5632                //invoke installer to do the actual installation
5633                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5634                                           pkg.applicationInfo.seinfo);
5635                if (ret < 0) {
5636                    // Error from installer
5637                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5638                            "Unable to create data dirs [errorCode=" + ret + "]");
5639                }
5640
5641                if (dataPath.exists()) {
5642                    pkg.applicationInfo.dataDir = dataPath.getPath();
5643                } else {
5644                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5645                    pkg.applicationInfo.dataDir = null;
5646                }
5647            }
5648
5649            pkgSetting.uidError = uidError;
5650        }
5651
5652        final String path = scanFile.getPath();
5653        final String codePath = pkg.applicationInfo.getCodePath();
5654        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5655        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5656            setBundledAppAbisAndRoots(pkg, pkgSetting);
5657
5658            // If we haven't found any native libraries for the app, check if it has
5659            // renderscript code. We'll need to force the app to 32 bit if it has
5660            // renderscript bitcode.
5661            if (pkg.applicationInfo.primaryCpuAbi == null
5662                    && pkg.applicationInfo.secondaryCpuAbi == null
5663                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5664                NativeLibraryHelper.Handle handle = null;
5665                try {
5666                    handle = NativeLibraryHelper.Handle.create(scanFile);
5667                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5668                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5669                    }
5670                } catch (IOException ioe) {
5671                    Slog.w(TAG, "Error scanning system app : " + ioe);
5672                } finally {
5673                    IoUtils.closeQuietly(handle);
5674                }
5675            }
5676
5677            setNativeLibraryPaths(pkg);
5678        } else {
5679            // TODO: We can probably be smarter about this stuff. For installed apps,
5680            // we can calculate this information at install time once and for all. For
5681            // system apps, we can probably assume that this information doesn't change
5682            // after the first boot scan. As things stand, we do lots of unnecessary work.
5683
5684            // Give ourselves some initial paths; we'll come back for another
5685            // pass once we've determined ABI below.
5686            setNativeLibraryPaths(pkg);
5687
5688            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
5689            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5690            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5691
5692            NativeLibraryHelper.Handle handle = null;
5693            try {
5694                handle = NativeLibraryHelper.Handle.create(scanFile);
5695                // TODO(multiArch): This can be null for apps that didn't go through the
5696                // usual installation process. We can calculate it again, like we
5697                // do during install time.
5698                //
5699                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5700                // unnecessary.
5701                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5702
5703                // Null out the abis so that they can be recalculated.
5704                pkg.applicationInfo.primaryCpuAbi = null;
5705                pkg.applicationInfo.secondaryCpuAbi = null;
5706                if (isMultiArch(pkg.applicationInfo)) {
5707                    // Warn if we've set an abiOverride for multi-lib packages..
5708                    // By definition, we need to copy both 32 and 64 bit libraries for
5709                    // such packages.
5710                    if (pkg.cpuAbiOverride != null
5711                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5712                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5713                    }
5714
5715                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5716                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5717                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5718                        if (isAsec) {
5719                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5720                        } else {
5721                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5722                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5723                                    useIsaSpecificSubdirs);
5724                        }
5725                    }
5726
5727                    maybeThrowExceptionForMultiArchCopy(
5728                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5729
5730                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5731                        if (isAsec) {
5732                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5733                        } else {
5734                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5735                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5736                                    useIsaSpecificSubdirs);
5737                        }
5738                    }
5739
5740                    maybeThrowExceptionForMultiArchCopy(
5741                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5742
5743                    if (abi64 >= 0) {
5744                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5745                    }
5746
5747                    if (abi32 >= 0) {
5748                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5749                        if (abi64 >= 0) {
5750                            pkg.applicationInfo.secondaryCpuAbi = abi;
5751                        } else {
5752                            pkg.applicationInfo.primaryCpuAbi = abi;
5753                        }
5754                    }
5755                } else {
5756                    String[] abiList = (cpuAbiOverride != null) ?
5757                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5758
5759                    // Enable gross and lame hacks for apps that are built with old
5760                    // SDK tools. We must scan their APKs for renderscript bitcode and
5761                    // not launch them if it's present. Don't bother checking on devices
5762                    // that don't have 64 bit support.
5763                    boolean needsRenderScriptOverride = false;
5764                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5765                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5766                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5767                        needsRenderScriptOverride = true;
5768                    }
5769
5770                    final int copyRet;
5771                    if (isAsec) {
5772                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5773                    } else {
5774                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5775                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5776                    }
5777
5778                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5779                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5780                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5781                    }
5782
5783                    if (copyRet >= 0) {
5784                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5785                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5786                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5787                    } else if (needsRenderScriptOverride) {
5788                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5789                    }
5790                }
5791            } catch (IOException ioe) {
5792                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5793            } finally {
5794                IoUtils.closeQuietly(handle);
5795            }
5796
5797            // Now that we've calculated the ABIs and determined if it's an internal app,
5798            // we will go ahead and populate the nativeLibraryPath.
5799            setNativeLibraryPaths(pkg);
5800
5801            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5802            final int[] userIds = sUserManager.getUserIds();
5803            synchronized (mInstallLock) {
5804                // Create a native library symlink only if we have native libraries
5805                // and if the native libraries are 32 bit libraries. We do not provide
5806                // this symlink for 64 bit libraries.
5807                if (pkg.applicationInfo.primaryCpuAbi != null &&
5808                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5809                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5810                    for (int userId : userIds) {
5811                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5812                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5813                                    "Failed linking native library dir (user=" + userId + ")");
5814                        }
5815                    }
5816                }
5817            }
5818        }
5819
5820        // This is a special case for the "system" package, where the ABI is
5821        // dictated by the zygote configuration (and init.rc). We should keep track
5822        // of this ABI so that we can deal with "normal" applications that run under
5823        // the same UID correctly.
5824        if (mPlatformPackage == pkg) {
5825            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5826                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5827        }
5828
5829        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5830        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5831        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5832        // Copy the derived override back to the parsed package, so that we can
5833        // update the package settings accordingly.
5834        pkg.cpuAbiOverride = cpuAbiOverride;
5835
5836        if (DEBUG_ABI_SELECTION) {
5837            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5838                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5839                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5840        }
5841
5842        // Push the derived path down into PackageSettings so we know what to
5843        // clean up at uninstall time.
5844        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5845
5846        if (DEBUG_ABI_SELECTION) {
5847            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5848                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5849                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5850        }
5851
5852        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5853            // We don't do this here during boot because we can do it all
5854            // at once after scanning all existing packages.
5855            //
5856            // We also do this *before* we perform dexopt on this package, so that
5857            // we can avoid redundant dexopts, and also to make sure we've got the
5858            // code and package path correct.
5859            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5860                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5861        }
5862
5863        if ((scanFlags & SCAN_NO_DEX) == 0) {
5864            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
5865                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
5866            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5867                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5868            }
5869        }
5870
5871        if (mFactoryTest && pkg.requestedPermissions.contains(
5872                android.Manifest.permission.FACTORY_TEST)) {
5873            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5874        }
5875
5876        ArrayList<PackageParser.Package> clientLibPkgs = null;
5877
5878        // writer
5879        synchronized (mPackages) {
5880            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5881                // Only system apps can add new shared libraries.
5882                if (pkg.libraryNames != null) {
5883                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5884                        String name = pkg.libraryNames.get(i);
5885                        boolean allowed = false;
5886                        if (isUpdatedSystemApp(pkg)) {
5887                            // New library entries can only be added through the
5888                            // system image.  This is important to get rid of a lot
5889                            // of nasty edge cases: for example if we allowed a non-
5890                            // system update of the app to add a library, then uninstalling
5891                            // the update would make the library go away, and assumptions
5892                            // we made such as through app install filtering would now
5893                            // have allowed apps on the device which aren't compatible
5894                            // with it.  Better to just have the restriction here, be
5895                            // conservative, and create many fewer cases that can negatively
5896                            // impact the user experience.
5897                            final PackageSetting sysPs = mSettings
5898                                    .getDisabledSystemPkgLPr(pkg.packageName);
5899                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5900                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5901                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5902                                        allowed = true;
5903                                        allowed = true;
5904                                        break;
5905                                    }
5906                                }
5907                            }
5908                        } else {
5909                            allowed = true;
5910                        }
5911                        if (allowed) {
5912                            if (!mSharedLibraries.containsKey(name)) {
5913                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5914                            } else if (!name.equals(pkg.packageName)) {
5915                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5916                                        + name + " already exists; skipping");
5917                            }
5918                        } else {
5919                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5920                                    + name + " that is not declared on system image; skipping");
5921                        }
5922                    }
5923                    if ((scanFlags&SCAN_BOOTING) == 0) {
5924                        // If we are not booting, we need to update any applications
5925                        // that are clients of our shared library.  If we are booting,
5926                        // this will all be done once the scan is complete.
5927                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5928                    }
5929                }
5930            }
5931        }
5932
5933        // We also need to dexopt any apps that are dependent on this library.  Note that
5934        // if these fail, we should abort the install since installing the library will
5935        // result in some apps being broken.
5936        if (clientLibPkgs != null) {
5937            if ((scanFlags & SCAN_NO_DEX) == 0) {
5938                for (int i = 0; i < clientLibPkgs.size(); i++) {
5939                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5940                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
5941                            null /* instruction sets */, forceDex,
5942                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
5943                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5944                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5945                                "scanPackageLI failed to dexopt clientLibPkgs");
5946                    }
5947                }
5948            }
5949        }
5950
5951        // Request the ActivityManager to kill the process(only for existing packages)
5952        // so that we do not end up in a confused state while the user is still using the older
5953        // version of the application while the new one gets installed.
5954        if ((scanFlags & SCAN_REPLACING) != 0) {
5955            killApplication(pkg.applicationInfo.packageName,
5956                        pkg.applicationInfo.uid, "update pkg");
5957        }
5958
5959        // Also need to kill any apps that are dependent on the library.
5960        if (clientLibPkgs != null) {
5961            for (int i=0; i<clientLibPkgs.size(); i++) {
5962                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5963                killApplication(clientPkg.applicationInfo.packageName,
5964                        clientPkg.applicationInfo.uid, "update lib");
5965            }
5966        }
5967
5968        // writer
5969        synchronized (mPackages) {
5970            // We don't expect installation to fail beyond this point
5971
5972            // Add the new setting to mSettings
5973            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5974            // Add the new setting to mPackages
5975            mPackages.put(pkg.applicationInfo.packageName, pkg);
5976            // Make sure we don't accidentally delete its data.
5977            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5978            while (iter.hasNext()) {
5979                PackageCleanItem item = iter.next();
5980                if (pkgName.equals(item.packageName)) {
5981                    iter.remove();
5982                }
5983            }
5984
5985            // Take care of first install / last update times.
5986            if (currentTime != 0) {
5987                if (pkgSetting.firstInstallTime == 0) {
5988                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5989                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5990                    pkgSetting.lastUpdateTime = currentTime;
5991                }
5992            } else if (pkgSetting.firstInstallTime == 0) {
5993                // We need *something*.  Take time time stamp of the file.
5994                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5995            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5996                if (scanFileTime != pkgSetting.timeStamp) {
5997                    // A package on the system image has changed; consider this
5998                    // to be an update.
5999                    pkgSetting.lastUpdateTime = scanFileTime;
6000                }
6001            }
6002
6003            // Add the package's KeySets to the global KeySetManagerService
6004            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6005            try {
6006                // Old KeySetData no longer valid.
6007                ksms.removeAppKeySetDataLPw(pkg.packageName);
6008                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6009                if (pkg.mKeySetMapping != null) {
6010                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
6011                            pkg.mKeySetMapping.entrySet()) {
6012                        if (entry.getValue() != null) {
6013                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
6014                                                          entry.getValue(), entry.getKey());
6015                        }
6016                    }
6017                    if (pkg.mUpgradeKeySets != null) {
6018                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
6019                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
6020                        }
6021                    }
6022                }
6023            } catch (NullPointerException e) {
6024                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6025            } catch (IllegalArgumentException e) {
6026                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6027            }
6028
6029            int N = pkg.providers.size();
6030            StringBuilder r = null;
6031            int i;
6032            for (i=0; i<N; i++) {
6033                PackageParser.Provider p = pkg.providers.get(i);
6034                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6035                        p.info.processName, pkg.applicationInfo.uid);
6036                mProviders.addProvider(p);
6037                p.syncable = p.info.isSyncable;
6038                if (p.info.authority != null) {
6039                    String names[] = p.info.authority.split(";");
6040                    p.info.authority = null;
6041                    for (int j = 0; j < names.length; j++) {
6042                        if (j == 1 && p.syncable) {
6043                            // We only want the first authority for a provider to possibly be
6044                            // syncable, so if we already added this provider using a different
6045                            // authority clear the syncable flag. We copy the provider before
6046                            // changing it because the mProviders object contains a reference
6047                            // to a provider that we don't want to change.
6048                            // Only do this for the second authority since the resulting provider
6049                            // object can be the same for all future authorities for this provider.
6050                            p = new PackageParser.Provider(p);
6051                            p.syncable = false;
6052                        }
6053                        if (!mProvidersByAuthority.containsKey(names[j])) {
6054                            mProvidersByAuthority.put(names[j], p);
6055                            if (p.info.authority == null) {
6056                                p.info.authority = names[j];
6057                            } else {
6058                                p.info.authority = p.info.authority + ";" + names[j];
6059                            }
6060                            if (DEBUG_PACKAGE_SCANNING) {
6061                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6062                                    Log.d(TAG, "Registered content provider: " + names[j]
6063                                            + ", className = " + p.info.name + ", isSyncable = "
6064                                            + p.info.isSyncable);
6065                            }
6066                        } else {
6067                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6068                            Slog.w(TAG, "Skipping provider name " + names[j] +
6069                                    " (in package " + pkg.applicationInfo.packageName +
6070                                    "): name already used by "
6071                                    + ((other != null && other.getComponentName() != null)
6072                                            ? other.getComponentName().getPackageName() : "?"));
6073                        }
6074                    }
6075                }
6076                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6077                    if (r == null) {
6078                        r = new StringBuilder(256);
6079                    } else {
6080                        r.append(' ');
6081                    }
6082                    r.append(p.info.name);
6083                }
6084            }
6085            if (r != null) {
6086                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6087            }
6088
6089            N = pkg.services.size();
6090            r = null;
6091            for (i=0; i<N; i++) {
6092                PackageParser.Service s = pkg.services.get(i);
6093                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6094                        s.info.processName, pkg.applicationInfo.uid);
6095                mServices.addService(s);
6096                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6097                    if (r == null) {
6098                        r = new StringBuilder(256);
6099                    } else {
6100                        r.append(' ');
6101                    }
6102                    r.append(s.info.name);
6103                }
6104            }
6105            if (r != null) {
6106                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6107            }
6108
6109            N = pkg.receivers.size();
6110            r = null;
6111            for (i=0; i<N; i++) {
6112                PackageParser.Activity a = pkg.receivers.get(i);
6113                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6114                        a.info.processName, pkg.applicationInfo.uid);
6115                mReceivers.addActivity(a, "receiver");
6116                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6117                    if (r == null) {
6118                        r = new StringBuilder(256);
6119                    } else {
6120                        r.append(' ');
6121                    }
6122                    r.append(a.info.name);
6123                }
6124            }
6125            if (r != null) {
6126                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6127            }
6128
6129            N = pkg.activities.size();
6130            r = null;
6131            for (i=0; i<N; i++) {
6132                PackageParser.Activity a = pkg.activities.get(i);
6133                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6134                        a.info.processName, pkg.applicationInfo.uid);
6135                mActivities.addActivity(a, "activity");
6136                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6137                    if (r == null) {
6138                        r = new StringBuilder(256);
6139                    } else {
6140                        r.append(' ');
6141                    }
6142                    r.append(a.info.name);
6143                }
6144            }
6145            if (r != null) {
6146                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6147            }
6148
6149            N = pkg.permissionGroups.size();
6150            r = null;
6151            for (i=0; i<N; i++) {
6152                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6153                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6154                if (cur == null) {
6155                    mPermissionGroups.put(pg.info.name, pg);
6156                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6157                        if (r == null) {
6158                            r = new StringBuilder(256);
6159                        } else {
6160                            r.append(' ');
6161                        }
6162                        r.append(pg.info.name);
6163                    }
6164                } else {
6165                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6166                            + pg.info.packageName + " ignored: original from "
6167                            + cur.info.packageName);
6168                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6169                        if (r == null) {
6170                            r = new StringBuilder(256);
6171                        } else {
6172                            r.append(' ');
6173                        }
6174                        r.append("DUP:");
6175                        r.append(pg.info.name);
6176                    }
6177                }
6178            }
6179            if (r != null) {
6180                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6181            }
6182
6183            N = pkg.permissions.size();
6184            r = null;
6185            for (i=0; i<N; i++) {
6186                PackageParser.Permission p = pkg.permissions.get(i);
6187                ArrayMap<String, BasePermission> permissionMap =
6188                        p.tree ? mSettings.mPermissionTrees
6189                        : mSettings.mPermissions;
6190                p.group = mPermissionGroups.get(p.info.group);
6191                if (p.info.group == null || p.group != null) {
6192                    BasePermission bp = permissionMap.get(p.info.name);
6193
6194                    // Allow system apps to redefine non-system permissions
6195                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6196                        final boolean currentOwnerIsSystem = (bp.perm != null
6197                                && isSystemApp(bp.perm.owner));
6198                        if (isSystemApp(p.owner)) {
6199                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6200                                // It's a built-in permission and no owner, take ownership now
6201                                bp.packageSetting = pkgSetting;
6202                                bp.perm = p;
6203                                bp.uid = pkg.applicationInfo.uid;
6204                                bp.sourcePackage = p.info.packageName;
6205                            } else if (!currentOwnerIsSystem) {
6206                                String msg = "New decl " + p.owner + " of permission  "
6207                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6208                                reportSettingsProblem(Log.WARN, msg);
6209                                bp = null;
6210                            }
6211                        }
6212                    }
6213
6214                    if (bp == null) {
6215                        bp = new BasePermission(p.info.name, p.info.packageName,
6216                                BasePermission.TYPE_NORMAL);
6217                        permissionMap.put(p.info.name, bp);
6218                    }
6219
6220                    if (bp.perm == null) {
6221                        if (bp.sourcePackage == null
6222                                || bp.sourcePackage.equals(p.info.packageName)) {
6223                            BasePermission tree = findPermissionTreeLP(p.info.name);
6224                            if (tree == null
6225                                    || tree.sourcePackage.equals(p.info.packageName)) {
6226                                bp.packageSetting = pkgSetting;
6227                                bp.perm = p;
6228                                bp.uid = pkg.applicationInfo.uid;
6229                                bp.sourcePackage = p.info.packageName;
6230                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6231                                    if (r == null) {
6232                                        r = new StringBuilder(256);
6233                                    } else {
6234                                        r.append(' ');
6235                                    }
6236                                    r.append(p.info.name);
6237                                }
6238                            } else {
6239                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6240                                        + p.info.packageName + " ignored: base tree "
6241                                        + tree.name + " is from package "
6242                                        + tree.sourcePackage);
6243                            }
6244                        } else {
6245                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6246                                    + p.info.packageName + " ignored: original from "
6247                                    + bp.sourcePackage);
6248                        }
6249                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6250                        if (r == null) {
6251                            r = new StringBuilder(256);
6252                        } else {
6253                            r.append(' ');
6254                        }
6255                        r.append("DUP:");
6256                        r.append(p.info.name);
6257                    }
6258                    if (bp.perm == p) {
6259                        bp.protectionLevel = p.info.protectionLevel;
6260                    }
6261                } else {
6262                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6263                            + p.info.packageName + " ignored: no group "
6264                            + p.group);
6265                }
6266            }
6267            if (r != null) {
6268                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6269            }
6270
6271            N = pkg.instrumentation.size();
6272            r = null;
6273            for (i=0; i<N; i++) {
6274                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6275                a.info.packageName = pkg.applicationInfo.packageName;
6276                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6277                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6278                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6279                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6280                a.info.dataDir = pkg.applicationInfo.dataDir;
6281
6282                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6283                // need other information about the application, like the ABI and what not ?
6284                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6285                mInstrumentation.put(a.getComponentName(), a);
6286                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6287                    if (r == null) {
6288                        r = new StringBuilder(256);
6289                    } else {
6290                        r.append(' ');
6291                    }
6292                    r.append(a.info.name);
6293                }
6294            }
6295            if (r != null) {
6296                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6297            }
6298
6299            if (pkg.protectedBroadcasts != null) {
6300                N = pkg.protectedBroadcasts.size();
6301                for (i=0; i<N; i++) {
6302                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6303                }
6304            }
6305
6306            pkgSetting.setTimeStamp(scanFileTime);
6307
6308            // Create idmap files for pairs of (packages, overlay packages).
6309            // Note: "android", ie framework-res.apk, is handled by native layers.
6310            if (pkg.mOverlayTarget != null) {
6311                // This is an overlay package.
6312                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6313                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6314                        mOverlays.put(pkg.mOverlayTarget,
6315                                new ArrayMap<String, PackageParser.Package>());
6316                    }
6317                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6318                    map.put(pkg.packageName, pkg);
6319                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6320                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6321                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6322                                "scanPackageLI failed to createIdmap");
6323                    }
6324                }
6325            } else if (mOverlays.containsKey(pkg.packageName) &&
6326                    !pkg.packageName.equals("android")) {
6327                // This is a regular package, with one or more known overlay packages.
6328                createIdmapsForPackageLI(pkg);
6329            }
6330        }
6331
6332        return pkg;
6333    }
6334
6335    /**
6336     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6337     * i.e, so that all packages can be run inside a single process if required.
6338     *
6339     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6340     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6341     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6342     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6343     * updating a package that belongs to a shared user.
6344     *
6345     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6346     * adds unnecessary complexity.
6347     */
6348    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6349            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6350        String requiredInstructionSet = null;
6351        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6352            requiredInstructionSet = VMRuntime.getInstructionSet(
6353                     scannedPackage.applicationInfo.primaryCpuAbi);
6354        }
6355
6356        PackageSetting requirer = null;
6357        for (PackageSetting ps : packagesForUser) {
6358            // If packagesForUser contains scannedPackage, we skip it. This will happen
6359            // when scannedPackage is an update of an existing package. Without this check,
6360            // we will never be able to change the ABI of any package belonging to a shared
6361            // user, even if it's compatible with other packages.
6362            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6363                if (ps.primaryCpuAbiString == null) {
6364                    continue;
6365                }
6366
6367                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6368                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6369                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6370                    // this but there's not much we can do.
6371                    String errorMessage = "Instruction set mismatch, "
6372                            + ((requirer == null) ? "[caller]" : requirer)
6373                            + " requires " + requiredInstructionSet + " whereas " + ps
6374                            + " requires " + instructionSet;
6375                    Slog.w(TAG, errorMessage);
6376                }
6377
6378                if (requiredInstructionSet == null) {
6379                    requiredInstructionSet = instructionSet;
6380                    requirer = ps;
6381                }
6382            }
6383        }
6384
6385        if (requiredInstructionSet != null) {
6386            String adjustedAbi;
6387            if (requirer != null) {
6388                // requirer != null implies that either scannedPackage was null or that scannedPackage
6389                // did not require an ABI, in which case we have to adjust scannedPackage to match
6390                // the ABI of the set (which is the same as requirer's ABI)
6391                adjustedAbi = requirer.primaryCpuAbiString;
6392                if (scannedPackage != null) {
6393                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6394                }
6395            } else {
6396                // requirer == null implies that we're updating all ABIs in the set to
6397                // match scannedPackage.
6398                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6399            }
6400
6401            for (PackageSetting ps : packagesForUser) {
6402                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6403                    if (ps.primaryCpuAbiString != null) {
6404                        continue;
6405                    }
6406
6407                    ps.primaryCpuAbiString = adjustedAbi;
6408                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6409                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6410                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6411
6412                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6413                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6414                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6415                            ps.primaryCpuAbiString = null;
6416                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6417                            return;
6418                        } else {
6419                            mInstaller.rmdex(ps.codePathString,
6420                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6421                        }
6422                    }
6423                }
6424            }
6425        }
6426    }
6427
6428    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6429        synchronized (mPackages) {
6430            mResolverReplaced = true;
6431            // Set up information for custom user intent resolution activity.
6432            mResolveActivity.applicationInfo = pkg.applicationInfo;
6433            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6434            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6435            mResolveActivity.processName = pkg.applicationInfo.packageName;
6436            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6437            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6438                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6439            mResolveActivity.theme = 0;
6440            mResolveActivity.exported = true;
6441            mResolveActivity.enabled = true;
6442            mResolveInfo.activityInfo = mResolveActivity;
6443            mResolveInfo.priority = 0;
6444            mResolveInfo.preferredOrder = 0;
6445            mResolveInfo.match = 0;
6446            mResolveComponentName = mCustomResolverComponentName;
6447            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6448                    mResolveComponentName);
6449        }
6450    }
6451
6452    private static String calculateBundledApkRoot(final String codePathString) {
6453        final File codePath = new File(codePathString);
6454        final File codeRoot;
6455        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6456            codeRoot = Environment.getRootDirectory();
6457        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6458            codeRoot = Environment.getOemDirectory();
6459        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6460            codeRoot = Environment.getVendorDirectory();
6461        } else {
6462            // Unrecognized code path; take its top real segment as the apk root:
6463            // e.g. /something/app/blah.apk => /something
6464            try {
6465                File f = codePath.getCanonicalFile();
6466                File parent = f.getParentFile();    // non-null because codePath is a file
6467                File tmp;
6468                while ((tmp = parent.getParentFile()) != null) {
6469                    f = parent;
6470                    parent = tmp;
6471                }
6472                codeRoot = f;
6473                Slog.w(TAG, "Unrecognized code path "
6474                        + codePath + " - using " + codeRoot);
6475            } catch (IOException e) {
6476                // Can't canonicalize the code path -- shenanigans?
6477                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6478                return Environment.getRootDirectory().getPath();
6479            }
6480        }
6481        return codeRoot.getPath();
6482    }
6483
6484    /**
6485     * Derive and set the location of native libraries for the given package,
6486     * which varies depending on where and how the package was installed.
6487     */
6488    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6489        final ApplicationInfo info = pkg.applicationInfo;
6490        final String codePath = pkg.codePath;
6491        final File codeFile = new File(codePath);
6492        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6493        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6494
6495        info.nativeLibraryRootDir = null;
6496        info.nativeLibraryRootRequiresIsa = false;
6497        info.nativeLibraryDir = null;
6498        info.secondaryNativeLibraryDir = null;
6499
6500        if (isApkFile(codeFile)) {
6501            // Monolithic install
6502            if (bundledApp) {
6503                // If "/system/lib64/apkname" exists, assume that is the per-package
6504                // native library directory to use; otherwise use "/system/lib/apkname".
6505                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6506                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6507                        getPrimaryInstructionSet(info));
6508
6509                // This is a bundled system app so choose the path based on the ABI.
6510                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6511                // is just the default path.
6512                final String apkName = deriveCodePathName(codePath);
6513                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6514                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6515                        apkName).getAbsolutePath();
6516
6517                if (info.secondaryCpuAbi != null) {
6518                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6519                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6520                            secondaryLibDir, apkName).getAbsolutePath();
6521                }
6522            } else if (asecApp) {
6523                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6524                        .getAbsolutePath();
6525            } else {
6526                final String apkName = deriveCodePathName(codePath);
6527                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6528                        .getAbsolutePath();
6529            }
6530
6531            info.nativeLibraryRootRequiresIsa = false;
6532            info.nativeLibraryDir = info.nativeLibraryRootDir;
6533        } else {
6534            // Cluster install
6535            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6536            info.nativeLibraryRootRequiresIsa = true;
6537
6538            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6539                    getPrimaryInstructionSet(info)).getAbsolutePath();
6540
6541            if (info.secondaryCpuAbi != null) {
6542                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6543                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6544            }
6545        }
6546    }
6547
6548    /**
6549     * Calculate the abis and roots for a bundled app. These can uniquely
6550     * be determined from the contents of the system partition, i.e whether
6551     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6552     * of this information, and instead assume that the system was built
6553     * sensibly.
6554     */
6555    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6556                                           PackageSetting pkgSetting) {
6557        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6558
6559        // If "/system/lib64/apkname" exists, assume that is the per-package
6560        // native library directory to use; otherwise use "/system/lib/apkname".
6561        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6562        setBundledAppAbi(pkg, apkRoot, apkName);
6563        // pkgSetting might be null during rescan following uninstall of updates
6564        // to a bundled app, so accommodate that possibility.  The settings in
6565        // that case will be established later from the parsed package.
6566        //
6567        // If the settings aren't null, sync them up with what we've just derived.
6568        // note that apkRoot isn't stored in the package settings.
6569        if (pkgSetting != null) {
6570            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6571            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6572        }
6573    }
6574
6575    /**
6576     * Deduces the ABI of a bundled app and sets the relevant fields on the
6577     * parsed pkg object.
6578     *
6579     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6580     *        under which system libraries are installed.
6581     * @param apkName the name of the installed package.
6582     */
6583    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6584        final File codeFile = new File(pkg.codePath);
6585
6586        final boolean has64BitLibs;
6587        final boolean has32BitLibs;
6588        if (isApkFile(codeFile)) {
6589            // Monolithic install
6590            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6591            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6592        } else {
6593            // Cluster install
6594            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6595            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6596                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6597                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6598                has64BitLibs = (new File(rootDir, isa)).exists();
6599            } else {
6600                has64BitLibs = false;
6601            }
6602            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6603                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6604                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6605                has32BitLibs = (new File(rootDir, isa)).exists();
6606            } else {
6607                has32BitLibs = false;
6608            }
6609        }
6610
6611        if (has64BitLibs && !has32BitLibs) {
6612            // The package has 64 bit libs, but not 32 bit libs. Its primary
6613            // ABI should be 64 bit. We can safely assume here that the bundled
6614            // native libraries correspond to the most preferred ABI in the list.
6615
6616            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6617            pkg.applicationInfo.secondaryCpuAbi = null;
6618        } else if (has32BitLibs && !has64BitLibs) {
6619            // The package has 32 bit libs but not 64 bit libs. Its primary
6620            // ABI should be 32 bit.
6621
6622            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6623            pkg.applicationInfo.secondaryCpuAbi = null;
6624        } else if (has32BitLibs && has64BitLibs) {
6625            // The application has both 64 and 32 bit bundled libraries. We check
6626            // here that the app declares multiArch support, and warn if it doesn't.
6627            //
6628            // We will be lenient here and record both ABIs. The primary will be the
6629            // ABI that's higher on the list, i.e, a device that's configured to prefer
6630            // 64 bit apps will see a 64 bit primary ABI,
6631
6632            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6633                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6634            }
6635
6636            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6637                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6638                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6639            } else {
6640                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6641                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6642            }
6643        } else {
6644            pkg.applicationInfo.primaryCpuAbi = null;
6645            pkg.applicationInfo.secondaryCpuAbi = null;
6646        }
6647    }
6648
6649    private void killApplication(String pkgName, int appId, String reason) {
6650        // Request the ActivityManager to kill the process(only for existing packages)
6651        // so that we do not end up in a confused state while the user is still using the older
6652        // version of the application while the new one gets installed.
6653        IActivityManager am = ActivityManagerNative.getDefault();
6654        if (am != null) {
6655            try {
6656                am.killApplicationWithAppId(pkgName, appId, reason);
6657            } catch (RemoteException e) {
6658            }
6659        }
6660    }
6661
6662    void removePackageLI(PackageSetting ps, boolean chatty) {
6663        if (DEBUG_INSTALL) {
6664            if (chatty)
6665                Log.d(TAG, "Removing package " + ps.name);
6666        }
6667
6668        // writer
6669        synchronized (mPackages) {
6670            mPackages.remove(ps.name);
6671            final PackageParser.Package pkg = ps.pkg;
6672            if (pkg != null) {
6673                cleanPackageDataStructuresLILPw(pkg, chatty);
6674            }
6675        }
6676    }
6677
6678    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6679        if (DEBUG_INSTALL) {
6680            if (chatty)
6681                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6682        }
6683
6684        // writer
6685        synchronized (mPackages) {
6686            mPackages.remove(pkg.applicationInfo.packageName);
6687            cleanPackageDataStructuresLILPw(pkg, chatty);
6688        }
6689    }
6690
6691    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6692        int N = pkg.providers.size();
6693        StringBuilder r = null;
6694        int i;
6695        for (i=0; i<N; i++) {
6696            PackageParser.Provider p = pkg.providers.get(i);
6697            mProviders.removeProvider(p);
6698            if (p.info.authority == null) {
6699
6700                /* There was another ContentProvider with this authority when
6701                 * this app was installed so this authority is null,
6702                 * Ignore it as we don't have to unregister the provider.
6703                 */
6704                continue;
6705            }
6706            String names[] = p.info.authority.split(";");
6707            for (int j = 0; j < names.length; j++) {
6708                if (mProvidersByAuthority.get(names[j]) == p) {
6709                    mProvidersByAuthority.remove(names[j]);
6710                    if (DEBUG_REMOVE) {
6711                        if (chatty)
6712                            Log.d(TAG, "Unregistered content provider: " + names[j]
6713                                    + ", className = " + p.info.name + ", isSyncable = "
6714                                    + p.info.isSyncable);
6715                    }
6716                }
6717            }
6718            if (DEBUG_REMOVE && chatty) {
6719                if (r == null) {
6720                    r = new StringBuilder(256);
6721                } else {
6722                    r.append(' ');
6723                }
6724                r.append(p.info.name);
6725            }
6726        }
6727        if (r != null) {
6728            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6729        }
6730
6731        N = pkg.services.size();
6732        r = null;
6733        for (i=0; i<N; i++) {
6734            PackageParser.Service s = pkg.services.get(i);
6735            mServices.removeService(s);
6736            if (chatty) {
6737                if (r == null) {
6738                    r = new StringBuilder(256);
6739                } else {
6740                    r.append(' ');
6741                }
6742                r.append(s.info.name);
6743            }
6744        }
6745        if (r != null) {
6746            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6747        }
6748
6749        N = pkg.receivers.size();
6750        r = null;
6751        for (i=0; i<N; i++) {
6752            PackageParser.Activity a = pkg.receivers.get(i);
6753            mReceivers.removeActivity(a, "receiver");
6754            if (DEBUG_REMOVE && chatty) {
6755                if (r == null) {
6756                    r = new StringBuilder(256);
6757                } else {
6758                    r.append(' ');
6759                }
6760                r.append(a.info.name);
6761            }
6762        }
6763        if (r != null) {
6764            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6765        }
6766
6767        N = pkg.activities.size();
6768        r = null;
6769        for (i=0; i<N; i++) {
6770            PackageParser.Activity a = pkg.activities.get(i);
6771            mActivities.removeActivity(a, "activity");
6772            if (DEBUG_REMOVE && chatty) {
6773                if (r == null) {
6774                    r = new StringBuilder(256);
6775                } else {
6776                    r.append(' ');
6777                }
6778                r.append(a.info.name);
6779            }
6780        }
6781        if (r != null) {
6782            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6783        }
6784
6785        N = pkg.permissions.size();
6786        r = null;
6787        for (i=0; i<N; i++) {
6788            PackageParser.Permission p = pkg.permissions.get(i);
6789            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6790            if (bp == null) {
6791                bp = mSettings.mPermissionTrees.get(p.info.name);
6792            }
6793            if (bp != null && bp.perm == p) {
6794                bp.perm = null;
6795                if (DEBUG_REMOVE && chatty) {
6796                    if (r == null) {
6797                        r = new StringBuilder(256);
6798                    } else {
6799                        r.append(' ');
6800                    }
6801                    r.append(p.info.name);
6802                }
6803            }
6804            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6805                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6806                if (appOpPerms != null) {
6807                    appOpPerms.remove(pkg.packageName);
6808                }
6809            }
6810        }
6811        if (r != null) {
6812            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6813        }
6814
6815        N = pkg.requestedPermissions.size();
6816        r = null;
6817        for (i=0; i<N; i++) {
6818            String perm = pkg.requestedPermissions.get(i);
6819            BasePermission bp = mSettings.mPermissions.get(perm);
6820            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6821                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6822                if (appOpPerms != null) {
6823                    appOpPerms.remove(pkg.packageName);
6824                    if (appOpPerms.isEmpty()) {
6825                        mAppOpPermissionPackages.remove(perm);
6826                    }
6827                }
6828            }
6829        }
6830        if (r != null) {
6831            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6832        }
6833
6834        N = pkg.instrumentation.size();
6835        r = null;
6836        for (i=0; i<N; i++) {
6837            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6838            mInstrumentation.remove(a.getComponentName());
6839            if (DEBUG_REMOVE && chatty) {
6840                if (r == null) {
6841                    r = new StringBuilder(256);
6842                } else {
6843                    r.append(' ');
6844                }
6845                r.append(a.info.name);
6846            }
6847        }
6848        if (r != null) {
6849            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6850        }
6851
6852        r = null;
6853        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6854            // Only system apps can hold shared libraries.
6855            if (pkg.libraryNames != null) {
6856                for (i=0; i<pkg.libraryNames.size(); i++) {
6857                    String name = pkg.libraryNames.get(i);
6858                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6859                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6860                        mSharedLibraries.remove(name);
6861                        if (DEBUG_REMOVE && chatty) {
6862                            if (r == null) {
6863                                r = new StringBuilder(256);
6864                            } else {
6865                                r.append(' ');
6866                            }
6867                            r.append(name);
6868                        }
6869                    }
6870                }
6871            }
6872        }
6873        if (r != null) {
6874            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6875        }
6876    }
6877
6878    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6879        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6880            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6881                return true;
6882            }
6883        }
6884        return false;
6885    }
6886
6887    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6888    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6889    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6890
6891    private void updatePermissionsLPw(String changingPkg,
6892            PackageParser.Package pkgInfo, int flags) {
6893        // Make sure there are no dangling permission trees.
6894        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6895        while (it.hasNext()) {
6896            final BasePermission bp = it.next();
6897            if (bp.packageSetting == null) {
6898                // We may not yet have parsed the package, so just see if
6899                // we still know about its settings.
6900                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6901            }
6902            if (bp.packageSetting == null) {
6903                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6904                        + " from package " + bp.sourcePackage);
6905                it.remove();
6906            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6907                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6908                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6909                            + " from package " + bp.sourcePackage);
6910                    flags |= UPDATE_PERMISSIONS_ALL;
6911                    it.remove();
6912                }
6913            }
6914        }
6915
6916        // Make sure all dynamic permissions have been assigned to a package,
6917        // and make sure there are no dangling permissions.
6918        it = mSettings.mPermissions.values().iterator();
6919        while (it.hasNext()) {
6920            final BasePermission bp = it.next();
6921            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6922                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6923                        + bp.name + " pkg=" + bp.sourcePackage
6924                        + " info=" + bp.pendingInfo);
6925                if (bp.packageSetting == null && bp.pendingInfo != null) {
6926                    final BasePermission tree = findPermissionTreeLP(bp.name);
6927                    if (tree != null && tree.perm != null) {
6928                        bp.packageSetting = tree.packageSetting;
6929                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6930                                new PermissionInfo(bp.pendingInfo));
6931                        bp.perm.info.packageName = tree.perm.info.packageName;
6932                        bp.perm.info.name = bp.name;
6933                        bp.uid = tree.uid;
6934                    }
6935                }
6936            }
6937            if (bp.packageSetting == null) {
6938                // We may not yet have parsed the package, so just see if
6939                // we still know about its settings.
6940                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6941            }
6942            if (bp.packageSetting == null) {
6943                Slog.w(TAG, "Removing dangling permission: " + bp.name
6944                        + " from package " + bp.sourcePackage);
6945                it.remove();
6946            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6947                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6948                    Slog.i(TAG, "Removing old permission: " + bp.name
6949                            + " from package " + bp.sourcePackage);
6950                    flags |= UPDATE_PERMISSIONS_ALL;
6951                    it.remove();
6952                }
6953            }
6954        }
6955
6956        // Now update the permissions for all packages, in particular
6957        // replace the granted permissions of the system packages.
6958        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6959            for (PackageParser.Package pkg : mPackages.values()) {
6960                if (pkg != pkgInfo) {
6961                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6962                            changingPkg);
6963                }
6964            }
6965        }
6966
6967        if (pkgInfo != null) {
6968            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6969        }
6970    }
6971
6972    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6973            String packageOfInterest) {
6974        // IMPORTANT: There are two types of permissions: install and runtime.
6975        // Install time permissions are granted when the app is installed to
6976        // all device users and users added in the future. Runtime permissions
6977        // are granted at runtime explicitly to specific users. Normal and signature
6978        // protected permissions are install time permissions. Dangerous permissions
6979        // are install permissions if the app's target SDK is Lollipop MR1 or older,
6980        // otherwise they are runtime permissions. This function does not manage
6981        // runtime permissions except for the case an app targeting Lollipop MR1
6982        // being upgraded to target a newer SDK, in which case dangerous permissions
6983        // are transformed from install time to runtime ones.
6984
6985        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6986        if (ps == null) {
6987            return;
6988        }
6989
6990        PermissionsState permissionsState = ps.getPermissionsState();
6991        PermissionsState origPermissions = permissionsState;
6992
6993        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
6994
6995        int[] upgradeUserIds = PermissionsState.USERS_NONE;
6996
6997        boolean changedPermission = false;
6998
6999        if (replace) {
7000            ps.permissionsFixed = false;
7001            origPermissions = new PermissionsState(permissionsState);
7002            permissionsState.reset();
7003        }
7004
7005        permissionsState.setGlobalGids(mGlobalGids);
7006
7007        final int N = pkg.requestedPermissions.size();
7008        for (int i=0; i<N; i++) {
7009            final String name = pkg.requestedPermissions.get(i);
7010            final BasePermission bp = mSettings.mPermissions.get(name);
7011
7012            if (DEBUG_INSTALL) {
7013                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7014            }
7015
7016            if (bp == null || bp.packageSetting == null) {
7017                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7018                    Slog.w(TAG, "Unknown permission " + name
7019                            + " in package " + pkg.packageName);
7020                }
7021                continue;
7022            }
7023
7024            final String perm = bp.name;
7025            boolean allowedSig = false;
7026            int grant = GRANT_DENIED;
7027
7028            // Keep track of app op permissions.
7029            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7030                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7031                if (pkgs == null) {
7032                    pkgs = new ArraySet<>();
7033                    mAppOpPermissionPackages.put(bp.name, pkgs);
7034                }
7035                pkgs.add(pkg.packageName);
7036            }
7037
7038            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7039            switch (level) {
7040                case PermissionInfo.PROTECTION_NORMAL: {
7041                    // For all apps normal permissions are install time ones.
7042                    grant = GRANT_INSTALL;
7043                } break;
7044
7045                case PermissionInfo.PROTECTION_DANGEROUS: {
7046                    if (!RUNTIME_PERMISSIONS_ENABLED
7047                            || pkg.applicationInfo.targetSdkVersion
7048                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7049                        // For legacy apps dangerous permissions are install time ones.
7050                        grant = GRANT_INSTALL;
7051                    } else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7052                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7053                        if (origPermissions.hasInstallPermission(bp.name)) {
7054                            // If a system app had an install permission, then the app was
7055                            // upgraded and we grant the permissions as runtime to all users.
7056                            grant = GRANT_UPGRADE;
7057                            upgradeUserIds = currentUserIds;
7058                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7059                            // If users changed since the last permissions update for a
7060                            // system app, we grant the permission as runtime to the new users.
7061                            grant = GRANT_UPGRADE;
7062                            upgradeUserIds = currentUserIds;
7063                            for (int userId : updatedUserIds) {
7064                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7065                            }
7066                        } else {
7067                            // Otherwise, we grant the permission as runtime if the app
7068                            // already had it, i.e. we preserve runtime permissions.
7069                            grant = GRANT_RUNTIME;
7070                        }
7071                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7072                        // For legacy apps that became modern, install becomes runtime.
7073                        grant = GRANT_UPGRADE;
7074                        upgradeUserIds = currentUserIds;
7075                    } else if (replace) {
7076                        // For upgraded modern apps keep runtime permissions unchanged.
7077                        grant = GRANT_RUNTIME;
7078                    }
7079                } break;
7080
7081                case PermissionInfo.PROTECTION_SIGNATURE: {
7082                    // For all apps signature permissions are install time ones.
7083                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7084                    if (allowedSig) {
7085                        grant = GRANT_INSTALL;
7086                    }
7087                } break;
7088            }
7089
7090            if (DEBUG_INSTALL) {
7091                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7092            }
7093
7094            if (grant != GRANT_DENIED) {
7095                if (!isSystemApp(ps) && ps.permissionsFixed) {
7096                    // If this is an existing, non-system package, then
7097                    // we can't add any new permissions to it.
7098                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7099                        // Except...  if this is a permission that was added
7100                        // to the platform (note: need to only do this when
7101                        // updating the platform).
7102                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7103                            grant = GRANT_DENIED;
7104                        }
7105                    }
7106                }
7107
7108                switch (grant) {
7109                    case GRANT_INSTALL: {
7110                        // Grant an install permission.
7111                        if (permissionsState.grantInstallPermission(bp) !=
7112                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7113                            changedPermission = true;
7114                        }
7115                    } break;
7116
7117                    case GRANT_RUNTIME: {
7118                        // Grant previously granted runtime permissions.
7119                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7120                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7121                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7122                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7123                                    changedPermission = true;
7124                                }
7125                            }
7126                        }
7127                    } break;
7128
7129                    case GRANT_UPGRADE: {
7130                        // Grant runtime permissions for a previously held install permission.
7131                        permissionsState.revokeInstallPermission(bp);
7132                        for (int userId : upgradeUserIds) {
7133                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7134                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7135                                changedPermission = true;
7136                            }
7137                        }
7138                    } break;
7139
7140                    default: {
7141                        if (packageOfInterest == null
7142                                || packageOfInterest.equals(pkg.packageName)) {
7143                            Slog.w(TAG, "Not granting permission " + perm
7144                                    + " to package " + pkg.packageName
7145                                    + " because it was previously installed without");
7146                        }
7147                    } break;
7148                }
7149            } else {
7150                if (permissionsState.revokeInstallPermission(bp) !=
7151                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7152                    changedPermission = true;
7153                    Slog.i(TAG, "Un-granting permission " + perm
7154                            + " from package " + pkg.packageName
7155                            + " (protectionLevel=" + bp.protectionLevel
7156                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7157                            + ")");
7158                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7159                    // Don't print warning for app op permissions, since it is fine for them
7160                    // not to be granted, there is a UI for the user to decide.
7161                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7162                        Slog.w(TAG, "Not granting permission " + perm
7163                                + " to package " + pkg.packageName
7164                                + " (protectionLevel=" + bp.protectionLevel
7165                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7166                                + ")");
7167                    }
7168                }
7169            }
7170        }
7171
7172        if ((changedPermission || replace) && !ps.permissionsFixed &&
7173                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7174            // This is the first that we have heard about this package, so the
7175            // permissions we have now selected are fixed until explicitly
7176            // changed.
7177            ps.permissionsFixed = true;
7178        }
7179
7180        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7181    }
7182
7183    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7184        boolean allowed = false;
7185        final int NP = PackageParser.NEW_PERMISSIONS.length;
7186        for (int ip=0; ip<NP; ip++) {
7187            final PackageParser.NewPermissionInfo npi
7188                    = PackageParser.NEW_PERMISSIONS[ip];
7189            if (npi.name.equals(perm)
7190                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7191                allowed = true;
7192                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7193                        + pkg.packageName);
7194                break;
7195            }
7196        }
7197        return allowed;
7198    }
7199
7200    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7201            BasePermission bp, PermissionsState origPermissions) {
7202        boolean allowed;
7203        allowed = (compareSignatures(
7204                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7205                        == PackageManager.SIGNATURE_MATCH)
7206                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7207                        == PackageManager.SIGNATURE_MATCH);
7208        if (!allowed && (bp.protectionLevel
7209                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7210            if (isSystemApp(pkg)) {
7211                // For updated system applications, a system permission
7212                // is granted only if it had been defined by the original application.
7213                if (isUpdatedSystemApp(pkg)) {
7214                    final PackageSetting sysPs = mSettings
7215                            .getDisabledSystemPkgLPr(pkg.packageName);
7216                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7217                        // If the original was granted this permission, we take
7218                        // that grant decision as read and propagate it to the
7219                        // update.
7220                        if (sysPs.isPrivileged()) {
7221                            allowed = true;
7222                        }
7223                    } else {
7224                        // The system apk may have been updated with an older
7225                        // version of the one on the data partition, but which
7226                        // granted a new system permission that it didn't have
7227                        // before.  In this case we do want to allow the app to
7228                        // now get the new permission if the ancestral apk is
7229                        // privileged to get it.
7230                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7231                            for (int j=0;
7232                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7233                                if (perm.equals(
7234                                        sysPs.pkg.requestedPermissions.get(j))) {
7235                                    allowed = true;
7236                                    break;
7237                                }
7238                            }
7239                        }
7240                    }
7241                } else {
7242                    allowed = isPrivilegedApp(pkg);
7243                }
7244            }
7245        }
7246        if (!allowed && (bp.protectionLevel
7247                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7248            // For development permissions, a development permission
7249            // is granted only if it was already granted.
7250            allowed = origPermissions.hasInstallPermission(perm);
7251        }
7252        return allowed;
7253    }
7254
7255    final class ActivityIntentResolver
7256            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7257        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7258                boolean defaultOnly, int userId) {
7259            if (!sUserManager.exists(userId)) return null;
7260            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7261            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7262        }
7263
7264        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7265                int userId) {
7266            if (!sUserManager.exists(userId)) return null;
7267            mFlags = flags;
7268            return super.queryIntent(intent, resolvedType,
7269                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7270        }
7271
7272        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7273                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7274            if (!sUserManager.exists(userId)) return null;
7275            if (packageActivities == null) {
7276                return null;
7277            }
7278            mFlags = flags;
7279            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7280            final int N = packageActivities.size();
7281            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7282                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7283
7284            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7285            for (int i = 0; i < N; ++i) {
7286                intentFilters = packageActivities.get(i).intents;
7287                if (intentFilters != null && intentFilters.size() > 0) {
7288                    PackageParser.ActivityIntentInfo[] array =
7289                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7290                    intentFilters.toArray(array);
7291                    listCut.add(array);
7292                }
7293            }
7294            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7295        }
7296
7297        public final void addActivity(PackageParser.Activity a, String type) {
7298            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7299            mActivities.put(a.getComponentName(), a);
7300            if (DEBUG_SHOW_INFO)
7301                Log.v(
7302                TAG, "  " + type + " " +
7303                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7304            if (DEBUG_SHOW_INFO)
7305                Log.v(TAG, "    Class=" + a.info.name);
7306            final int NI = a.intents.size();
7307            for (int j=0; j<NI; j++) {
7308                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7309                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7310                    intent.setPriority(0);
7311                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7312                            + a.className + " with priority > 0, forcing to 0");
7313                }
7314                if (DEBUG_SHOW_INFO) {
7315                    Log.v(TAG, "    IntentFilter:");
7316                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7317                }
7318                if (!intent.debugCheck()) {
7319                    Log.w(TAG, "==> For Activity " + a.info.name);
7320                }
7321                addFilter(intent);
7322            }
7323        }
7324
7325        public final void removeActivity(PackageParser.Activity a, String type) {
7326            mActivities.remove(a.getComponentName());
7327            if (DEBUG_SHOW_INFO) {
7328                Log.v(TAG, "  " + type + " "
7329                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7330                                : a.info.name) + ":");
7331                Log.v(TAG, "    Class=" + a.info.name);
7332            }
7333            final int NI = a.intents.size();
7334            for (int j=0; j<NI; j++) {
7335                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7336                if (DEBUG_SHOW_INFO) {
7337                    Log.v(TAG, "    IntentFilter:");
7338                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7339                }
7340                removeFilter(intent);
7341            }
7342        }
7343
7344        @Override
7345        protected boolean allowFilterResult(
7346                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7347            ActivityInfo filterAi = filter.activity.info;
7348            for (int i=dest.size()-1; i>=0; i--) {
7349                ActivityInfo destAi = dest.get(i).activityInfo;
7350                if (destAi.name == filterAi.name
7351                        && destAi.packageName == filterAi.packageName) {
7352                    return false;
7353                }
7354            }
7355            return true;
7356        }
7357
7358        @Override
7359        protected ActivityIntentInfo[] newArray(int size) {
7360            return new ActivityIntentInfo[size];
7361        }
7362
7363        @Override
7364        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7365            if (!sUserManager.exists(userId)) return true;
7366            PackageParser.Package p = filter.activity.owner;
7367            if (p != null) {
7368                PackageSetting ps = (PackageSetting)p.mExtras;
7369                if (ps != null) {
7370                    // System apps are never considered stopped for purposes of
7371                    // filtering, because there may be no way for the user to
7372                    // actually re-launch them.
7373                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7374                            && ps.getStopped(userId);
7375                }
7376            }
7377            return false;
7378        }
7379
7380        @Override
7381        protected boolean isPackageForFilter(String packageName,
7382                PackageParser.ActivityIntentInfo info) {
7383            return packageName.equals(info.activity.owner.packageName);
7384        }
7385
7386        @Override
7387        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7388                int match, int userId) {
7389            if (!sUserManager.exists(userId)) return null;
7390            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7391                return null;
7392            }
7393            final PackageParser.Activity activity = info.activity;
7394            if (mSafeMode && (activity.info.applicationInfo.flags
7395                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7396                return null;
7397            }
7398            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7399            if (ps == null) {
7400                return null;
7401            }
7402            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7403                    ps.readUserState(userId), userId);
7404            if (ai == null) {
7405                return null;
7406            }
7407            final ResolveInfo res = new ResolveInfo();
7408            res.activityInfo = ai;
7409            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7410                res.filter = info;
7411            }
7412            res.priority = info.getPriority();
7413            res.preferredOrder = activity.owner.mPreferredOrder;
7414            //System.out.println("Result: " + res.activityInfo.className +
7415            //                   " = " + res.priority);
7416            res.match = match;
7417            res.isDefault = info.hasDefault;
7418            res.labelRes = info.labelRes;
7419            res.nonLocalizedLabel = info.nonLocalizedLabel;
7420            if (userNeedsBadging(userId)) {
7421                res.noResourceId = true;
7422            } else {
7423                res.icon = info.icon;
7424            }
7425            res.system = isSystemApp(res.activityInfo.applicationInfo);
7426            return res;
7427        }
7428
7429        @Override
7430        protected void sortResults(List<ResolveInfo> results) {
7431            Collections.sort(results, mResolvePrioritySorter);
7432        }
7433
7434        @Override
7435        protected void dumpFilter(PrintWriter out, String prefix,
7436                PackageParser.ActivityIntentInfo filter) {
7437            out.print(prefix); out.print(
7438                    Integer.toHexString(System.identityHashCode(filter.activity)));
7439                    out.print(' ');
7440                    filter.activity.printComponentShortName(out);
7441                    out.print(" filter ");
7442                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7443        }
7444
7445        @Override
7446        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7447            return filter.activity;
7448        }
7449
7450        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7451            PackageParser.Activity activity = (PackageParser.Activity)label;
7452            out.print(prefix); out.print(
7453                    Integer.toHexString(System.identityHashCode(activity)));
7454                    out.print(' ');
7455                    activity.printComponentShortName(out);
7456            if (count > 1) {
7457                out.print(" ("); out.print(count); out.print(" filters)");
7458            }
7459            out.println();
7460        }
7461
7462//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7463//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7464//            final List<ResolveInfo> retList = Lists.newArrayList();
7465//            while (i.hasNext()) {
7466//                final ResolveInfo resolveInfo = i.next();
7467//                if (isEnabledLP(resolveInfo.activityInfo)) {
7468//                    retList.add(resolveInfo);
7469//                }
7470//            }
7471//            return retList;
7472//        }
7473
7474        // Keys are String (activity class name), values are Activity.
7475        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7476                = new ArrayMap<ComponentName, PackageParser.Activity>();
7477        private int mFlags;
7478    }
7479
7480    private final class ServiceIntentResolver
7481            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7482        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7483                boolean defaultOnly, int userId) {
7484            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7485            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7486        }
7487
7488        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7489                int userId) {
7490            if (!sUserManager.exists(userId)) return null;
7491            mFlags = flags;
7492            return super.queryIntent(intent, resolvedType,
7493                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7494        }
7495
7496        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7497                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7498            if (!sUserManager.exists(userId)) return null;
7499            if (packageServices == null) {
7500                return null;
7501            }
7502            mFlags = flags;
7503            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7504            final int N = packageServices.size();
7505            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7506                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7507
7508            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7509            for (int i = 0; i < N; ++i) {
7510                intentFilters = packageServices.get(i).intents;
7511                if (intentFilters != null && intentFilters.size() > 0) {
7512                    PackageParser.ServiceIntentInfo[] array =
7513                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7514                    intentFilters.toArray(array);
7515                    listCut.add(array);
7516                }
7517            }
7518            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7519        }
7520
7521        public final void addService(PackageParser.Service s) {
7522            mServices.put(s.getComponentName(), s);
7523            if (DEBUG_SHOW_INFO) {
7524                Log.v(TAG, "  "
7525                        + (s.info.nonLocalizedLabel != null
7526                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7527                Log.v(TAG, "    Class=" + s.info.name);
7528            }
7529            final int NI = s.intents.size();
7530            int j;
7531            for (j=0; j<NI; j++) {
7532                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7533                if (DEBUG_SHOW_INFO) {
7534                    Log.v(TAG, "    IntentFilter:");
7535                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7536                }
7537                if (!intent.debugCheck()) {
7538                    Log.w(TAG, "==> For Service " + s.info.name);
7539                }
7540                addFilter(intent);
7541            }
7542        }
7543
7544        public final void removeService(PackageParser.Service s) {
7545            mServices.remove(s.getComponentName());
7546            if (DEBUG_SHOW_INFO) {
7547                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7548                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7549                Log.v(TAG, "    Class=" + s.info.name);
7550            }
7551            final int NI = s.intents.size();
7552            int j;
7553            for (j=0; j<NI; j++) {
7554                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7555                if (DEBUG_SHOW_INFO) {
7556                    Log.v(TAG, "    IntentFilter:");
7557                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7558                }
7559                removeFilter(intent);
7560            }
7561        }
7562
7563        @Override
7564        protected boolean allowFilterResult(
7565                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7566            ServiceInfo filterSi = filter.service.info;
7567            for (int i=dest.size()-1; i>=0; i--) {
7568                ServiceInfo destAi = dest.get(i).serviceInfo;
7569                if (destAi.name == filterSi.name
7570                        && destAi.packageName == filterSi.packageName) {
7571                    return false;
7572                }
7573            }
7574            return true;
7575        }
7576
7577        @Override
7578        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7579            return new PackageParser.ServiceIntentInfo[size];
7580        }
7581
7582        @Override
7583        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7584            if (!sUserManager.exists(userId)) return true;
7585            PackageParser.Package p = filter.service.owner;
7586            if (p != null) {
7587                PackageSetting ps = (PackageSetting)p.mExtras;
7588                if (ps != null) {
7589                    // System apps are never considered stopped for purposes of
7590                    // filtering, because there may be no way for the user to
7591                    // actually re-launch them.
7592                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7593                            && ps.getStopped(userId);
7594                }
7595            }
7596            return false;
7597        }
7598
7599        @Override
7600        protected boolean isPackageForFilter(String packageName,
7601                PackageParser.ServiceIntentInfo info) {
7602            return packageName.equals(info.service.owner.packageName);
7603        }
7604
7605        @Override
7606        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7607                int match, int userId) {
7608            if (!sUserManager.exists(userId)) return null;
7609            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7610            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7611                return null;
7612            }
7613            final PackageParser.Service service = info.service;
7614            if (mSafeMode && (service.info.applicationInfo.flags
7615                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7616                return null;
7617            }
7618            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7619            if (ps == null) {
7620                return null;
7621            }
7622            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7623                    ps.readUserState(userId), userId);
7624            if (si == null) {
7625                return null;
7626            }
7627            final ResolveInfo res = new ResolveInfo();
7628            res.serviceInfo = si;
7629            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7630                res.filter = filter;
7631            }
7632            res.priority = info.getPriority();
7633            res.preferredOrder = service.owner.mPreferredOrder;
7634            //System.out.println("Result: " + res.activityInfo.className +
7635            //                   " = " + res.priority);
7636            res.match = match;
7637            res.isDefault = info.hasDefault;
7638            res.labelRes = info.labelRes;
7639            res.nonLocalizedLabel = info.nonLocalizedLabel;
7640            res.icon = info.icon;
7641            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7642            return res;
7643        }
7644
7645        @Override
7646        protected void sortResults(List<ResolveInfo> results) {
7647            Collections.sort(results, mResolvePrioritySorter);
7648        }
7649
7650        @Override
7651        protected void dumpFilter(PrintWriter out, String prefix,
7652                PackageParser.ServiceIntentInfo filter) {
7653            out.print(prefix); out.print(
7654                    Integer.toHexString(System.identityHashCode(filter.service)));
7655                    out.print(' ');
7656                    filter.service.printComponentShortName(out);
7657                    out.print(" filter ");
7658                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7659        }
7660
7661        @Override
7662        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7663            return filter.service;
7664        }
7665
7666        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7667            PackageParser.Service service = (PackageParser.Service)label;
7668            out.print(prefix); out.print(
7669                    Integer.toHexString(System.identityHashCode(service)));
7670                    out.print(' ');
7671                    service.printComponentShortName(out);
7672            if (count > 1) {
7673                out.print(" ("); out.print(count); out.print(" filters)");
7674            }
7675            out.println();
7676        }
7677
7678//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7679//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7680//            final List<ResolveInfo> retList = Lists.newArrayList();
7681//            while (i.hasNext()) {
7682//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7683//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7684//                    retList.add(resolveInfo);
7685//                }
7686//            }
7687//            return retList;
7688//        }
7689
7690        // Keys are String (activity class name), values are Activity.
7691        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7692                = new ArrayMap<ComponentName, PackageParser.Service>();
7693        private int mFlags;
7694    };
7695
7696    private final class ProviderIntentResolver
7697            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7698        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7699                boolean defaultOnly, int userId) {
7700            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7701            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7702        }
7703
7704        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7705                int userId) {
7706            if (!sUserManager.exists(userId))
7707                return null;
7708            mFlags = flags;
7709            return super.queryIntent(intent, resolvedType,
7710                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7711        }
7712
7713        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7714                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7715            if (!sUserManager.exists(userId))
7716                return null;
7717            if (packageProviders == null) {
7718                return null;
7719            }
7720            mFlags = flags;
7721            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7722            final int N = packageProviders.size();
7723            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7724                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7725
7726            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7727            for (int i = 0; i < N; ++i) {
7728                intentFilters = packageProviders.get(i).intents;
7729                if (intentFilters != null && intentFilters.size() > 0) {
7730                    PackageParser.ProviderIntentInfo[] array =
7731                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7732                    intentFilters.toArray(array);
7733                    listCut.add(array);
7734                }
7735            }
7736            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7737        }
7738
7739        public final void addProvider(PackageParser.Provider p) {
7740            if (mProviders.containsKey(p.getComponentName())) {
7741                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7742                return;
7743            }
7744
7745            mProviders.put(p.getComponentName(), p);
7746            if (DEBUG_SHOW_INFO) {
7747                Log.v(TAG, "  "
7748                        + (p.info.nonLocalizedLabel != null
7749                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7750                Log.v(TAG, "    Class=" + p.info.name);
7751            }
7752            final int NI = p.intents.size();
7753            int j;
7754            for (j = 0; j < NI; j++) {
7755                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7756                if (DEBUG_SHOW_INFO) {
7757                    Log.v(TAG, "    IntentFilter:");
7758                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7759                }
7760                if (!intent.debugCheck()) {
7761                    Log.w(TAG, "==> For Provider " + p.info.name);
7762                }
7763                addFilter(intent);
7764            }
7765        }
7766
7767        public final void removeProvider(PackageParser.Provider p) {
7768            mProviders.remove(p.getComponentName());
7769            if (DEBUG_SHOW_INFO) {
7770                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7771                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7772                Log.v(TAG, "    Class=" + p.info.name);
7773            }
7774            final int NI = p.intents.size();
7775            int j;
7776            for (j = 0; j < NI; j++) {
7777                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7778                if (DEBUG_SHOW_INFO) {
7779                    Log.v(TAG, "    IntentFilter:");
7780                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7781                }
7782                removeFilter(intent);
7783            }
7784        }
7785
7786        @Override
7787        protected boolean allowFilterResult(
7788                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7789            ProviderInfo filterPi = filter.provider.info;
7790            for (int i = dest.size() - 1; i >= 0; i--) {
7791                ProviderInfo destPi = dest.get(i).providerInfo;
7792                if (destPi.name == filterPi.name
7793                        && destPi.packageName == filterPi.packageName) {
7794                    return false;
7795                }
7796            }
7797            return true;
7798        }
7799
7800        @Override
7801        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7802            return new PackageParser.ProviderIntentInfo[size];
7803        }
7804
7805        @Override
7806        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7807            if (!sUserManager.exists(userId))
7808                return true;
7809            PackageParser.Package p = filter.provider.owner;
7810            if (p != null) {
7811                PackageSetting ps = (PackageSetting) p.mExtras;
7812                if (ps != null) {
7813                    // System apps are never considered stopped for purposes of
7814                    // filtering, because there may be no way for the user to
7815                    // actually re-launch them.
7816                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7817                            && ps.getStopped(userId);
7818                }
7819            }
7820            return false;
7821        }
7822
7823        @Override
7824        protected boolean isPackageForFilter(String packageName,
7825                PackageParser.ProviderIntentInfo info) {
7826            return packageName.equals(info.provider.owner.packageName);
7827        }
7828
7829        @Override
7830        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7831                int match, int userId) {
7832            if (!sUserManager.exists(userId))
7833                return null;
7834            final PackageParser.ProviderIntentInfo info = filter;
7835            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7836                return null;
7837            }
7838            final PackageParser.Provider provider = info.provider;
7839            if (mSafeMode && (provider.info.applicationInfo.flags
7840                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7841                return null;
7842            }
7843            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7844            if (ps == null) {
7845                return null;
7846            }
7847            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7848                    ps.readUserState(userId), userId);
7849            if (pi == null) {
7850                return null;
7851            }
7852            final ResolveInfo res = new ResolveInfo();
7853            res.providerInfo = pi;
7854            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7855                res.filter = filter;
7856            }
7857            res.priority = info.getPriority();
7858            res.preferredOrder = provider.owner.mPreferredOrder;
7859            res.match = match;
7860            res.isDefault = info.hasDefault;
7861            res.labelRes = info.labelRes;
7862            res.nonLocalizedLabel = info.nonLocalizedLabel;
7863            res.icon = info.icon;
7864            res.system = isSystemApp(res.providerInfo.applicationInfo);
7865            return res;
7866        }
7867
7868        @Override
7869        protected void sortResults(List<ResolveInfo> results) {
7870            Collections.sort(results, mResolvePrioritySorter);
7871        }
7872
7873        @Override
7874        protected void dumpFilter(PrintWriter out, String prefix,
7875                PackageParser.ProviderIntentInfo filter) {
7876            out.print(prefix);
7877            out.print(
7878                    Integer.toHexString(System.identityHashCode(filter.provider)));
7879            out.print(' ');
7880            filter.provider.printComponentShortName(out);
7881            out.print(" filter ");
7882            out.println(Integer.toHexString(System.identityHashCode(filter)));
7883        }
7884
7885        @Override
7886        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7887            return filter.provider;
7888        }
7889
7890        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7891            PackageParser.Provider provider = (PackageParser.Provider)label;
7892            out.print(prefix); out.print(
7893                    Integer.toHexString(System.identityHashCode(provider)));
7894                    out.print(' ');
7895                    provider.printComponentShortName(out);
7896            if (count > 1) {
7897                out.print(" ("); out.print(count); out.print(" filters)");
7898            }
7899            out.println();
7900        }
7901
7902        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7903                = new ArrayMap<ComponentName, PackageParser.Provider>();
7904        private int mFlags;
7905    };
7906
7907    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7908            new Comparator<ResolveInfo>() {
7909        public int compare(ResolveInfo r1, ResolveInfo r2) {
7910            int v1 = r1.priority;
7911            int v2 = r2.priority;
7912            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7913            if (v1 != v2) {
7914                return (v1 > v2) ? -1 : 1;
7915            }
7916            v1 = r1.preferredOrder;
7917            v2 = r2.preferredOrder;
7918            if (v1 != v2) {
7919                return (v1 > v2) ? -1 : 1;
7920            }
7921            if (r1.isDefault != r2.isDefault) {
7922                return r1.isDefault ? -1 : 1;
7923            }
7924            v1 = r1.match;
7925            v2 = r2.match;
7926            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7927            if (v1 != v2) {
7928                return (v1 > v2) ? -1 : 1;
7929            }
7930            if (r1.system != r2.system) {
7931                return r1.system ? -1 : 1;
7932            }
7933            return 0;
7934        }
7935    };
7936
7937    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7938            new Comparator<ProviderInfo>() {
7939        public int compare(ProviderInfo p1, ProviderInfo p2) {
7940            final int v1 = p1.initOrder;
7941            final int v2 = p2.initOrder;
7942            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7943        }
7944    };
7945
7946    static final void sendPackageBroadcast(String action, String pkg,
7947            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7948            int[] userIds) {
7949        IActivityManager am = ActivityManagerNative.getDefault();
7950        if (am != null) {
7951            try {
7952                if (userIds == null) {
7953                    userIds = am.getRunningUserIds();
7954                }
7955                for (int id : userIds) {
7956                    final Intent intent = new Intent(action,
7957                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7958                    if (extras != null) {
7959                        intent.putExtras(extras);
7960                    }
7961                    if (targetPkg != null) {
7962                        intent.setPackage(targetPkg);
7963                    }
7964                    // Modify the UID when posting to other users
7965                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7966                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7967                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7968                        intent.putExtra(Intent.EXTRA_UID, uid);
7969                    }
7970                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7971                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7972                    if (DEBUG_BROADCASTS) {
7973                        RuntimeException here = new RuntimeException("here");
7974                        here.fillInStackTrace();
7975                        Slog.d(TAG, "Sending to user " + id + ": "
7976                                + intent.toShortString(false, true, false, false)
7977                                + " " + intent.getExtras(), here);
7978                    }
7979                    am.broadcastIntent(null, intent, null, finishedReceiver,
7980                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7981                            finishedReceiver != null, false, id);
7982                }
7983            } catch (RemoteException ex) {
7984            }
7985        }
7986    }
7987
7988    /**
7989     * Check if the external storage media is available. This is true if there
7990     * is a mounted external storage medium or if the external storage is
7991     * emulated.
7992     */
7993    private boolean isExternalMediaAvailable() {
7994        return mMediaMounted || Environment.isExternalStorageEmulated();
7995    }
7996
7997    @Override
7998    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7999        // writer
8000        synchronized (mPackages) {
8001            if (!isExternalMediaAvailable()) {
8002                // If the external storage is no longer mounted at this point,
8003                // the caller may not have been able to delete all of this
8004                // packages files and can not delete any more.  Bail.
8005                return null;
8006            }
8007            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8008            if (lastPackage != null) {
8009                pkgs.remove(lastPackage);
8010            }
8011            if (pkgs.size() > 0) {
8012                return pkgs.get(0);
8013            }
8014        }
8015        return null;
8016    }
8017
8018    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8019        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8020                userId, andCode ? 1 : 0, packageName);
8021        if (mSystemReady) {
8022            msg.sendToTarget();
8023        } else {
8024            if (mPostSystemReadyMessages == null) {
8025                mPostSystemReadyMessages = new ArrayList<>();
8026            }
8027            mPostSystemReadyMessages.add(msg);
8028        }
8029    }
8030
8031    void startCleaningPackages() {
8032        // reader
8033        synchronized (mPackages) {
8034            if (!isExternalMediaAvailable()) {
8035                return;
8036            }
8037            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8038                return;
8039            }
8040        }
8041        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8042        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8043        IActivityManager am = ActivityManagerNative.getDefault();
8044        if (am != null) {
8045            try {
8046                am.startService(null, intent, null, UserHandle.USER_OWNER);
8047            } catch (RemoteException e) {
8048            }
8049        }
8050    }
8051
8052    @Override
8053    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8054            int installFlags, String installerPackageName, VerificationParams verificationParams,
8055            String packageAbiOverride) {
8056        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
8057                packageAbiOverride, UserHandle.getCallingUserId());
8058    }
8059
8060    @Override
8061    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8062            int installFlags, String installerPackageName, VerificationParams verificationParams,
8063            String packageAbiOverride, int userId) {
8064        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8065
8066        final int callingUid = Binder.getCallingUid();
8067        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8068
8069        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8070            try {
8071                if (observer != null) {
8072                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8073                }
8074            } catch (RemoteException re) {
8075            }
8076            return;
8077        }
8078
8079        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8080            installFlags |= PackageManager.INSTALL_FROM_ADB;
8081
8082        } else {
8083            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8084            // about installerPackageName.
8085
8086            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8087            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8088        }
8089
8090        UserHandle user;
8091        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8092            user = UserHandle.ALL;
8093        } else {
8094            user = new UserHandle(userId);
8095        }
8096
8097        verificationParams.setInstallerUid(callingUid);
8098
8099        final File originFile = new File(originPath);
8100        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8101
8102        final Message msg = mHandler.obtainMessage(INIT_COPY);
8103        msg.obj = new InstallParams(origin, observer, installFlags,
8104                installerPackageName, verificationParams, user, packageAbiOverride);
8105        mHandler.sendMessage(msg);
8106    }
8107
8108    void installStage(String packageName, File stagedDir, String stagedCid,
8109            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8110            String installerPackageName, int installerUid, UserHandle user) {
8111        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8112                params.referrerUri, installerUid, null);
8113
8114        final OriginInfo origin;
8115        if (stagedDir != null) {
8116            origin = OriginInfo.fromStagedFile(stagedDir);
8117        } else {
8118            origin = OriginInfo.fromStagedContainer(stagedCid);
8119        }
8120
8121        final Message msg = mHandler.obtainMessage(INIT_COPY);
8122        msg.obj = new InstallParams(origin, observer, params.installFlags,
8123                installerPackageName, verifParams, user, params.abiOverride);
8124        mHandler.sendMessage(msg);
8125    }
8126
8127    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8128        Bundle extras = new Bundle(1);
8129        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8130
8131        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8132                packageName, extras, null, null, new int[] {userId});
8133        try {
8134            IActivityManager am = ActivityManagerNative.getDefault();
8135            final boolean isSystem =
8136                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8137            if (isSystem && am.isUserRunning(userId, false)) {
8138                // The just-installed/enabled app is bundled on the system, so presumed
8139                // to be able to run automatically without needing an explicit launch.
8140                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8141                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8142                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8143                        .setPackage(packageName);
8144                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8145                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8146            }
8147        } catch (RemoteException e) {
8148            // shouldn't happen
8149            Slog.w(TAG, "Unable to bootstrap installed package", e);
8150        }
8151    }
8152
8153    @Override
8154    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8155            int userId) {
8156        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8157        PackageSetting pkgSetting;
8158        final int uid = Binder.getCallingUid();
8159        enforceCrossUserPermission(uid, userId, true, true,
8160                "setApplicationHiddenSetting for user " + userId);
8161
8162        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8163            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8164            return false;
8165        }
8166
8167        long callingId = Binder.clearCallingIdentity();
8168        try {
8169            boolean sendAdded = false;
8170            boolean sendRemoved = false;
8171            // writer
8172            synchronized (mPackages) {
8173                pkgSetting = mSettings.mPackages.get(packageName);
8174                if (pkgSetting == null) {
8175                    return false;
8176                }
8177                if (pkgSetting.getHidden(userId) != hidden) {
8178                    pkgSetting.setHidden(hidden, userId);
8179                    mSettings.writePackageRestrictionsLPr(userId);
8180                    if (hidden) {
8181                        sendRemoved = true;
8182                    } else {
8183                        sendAdded = true;
8184                    }
8185                }
8186            }
8187            if (sendAdded) {
8188                sendPackageAddedForUser(packageName, pkgSetting, userId);
8189                return true;
8190            }
8191            if (sendRemoved) {
8192                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8193                        "hiding pkg");
8194                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8195            }
8196        } finally {
8197            Binder.restoreCallingIdentity(callingId);
8198        }
8199        return false;
8200    }
8201
8202    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8203            int userId) {
8204        final PackageRemovedInfo info = new PackageRemovedInfo();
8205        info.removedPackage = packageName;
8206        info.removedUsers = new int[] {userId};
8207        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8208        info.sendBroadcast(false, false, false);
8209    }
8210
8211    /**
8212     * Returns true if application is not found or there was an error. Otherwise it returns
8213     * the hidden state of the package for the given user.
8214     */
8215    @Override
8216    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8217        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8218        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8219                false, "getApplicationHidden for user " + userId);
8220        PackageSetting pkgSetting;
8221        long callingId = Binder.clearCallingIdentity();
8222        try {
8223            // writer
8224            synchronized (mPackages) {
8225                pkgSetting = mSettings.mPackages.get(packageName);
8226                if (pkgSetting == null) {
8227                    return true;
8228                }
8229                return pkgSetting.getHidden(userId);
8230            }
8231        } finally {
8232            Binder.restoreCallingIdentity(callingId);
8233        }
8234    }
8235
8236    /**
8237     * @hide
8238     */
8239    @Override
8240    public int installExistingPackageAsUser(String packageName, int userId) {
8241        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8242                null);
8243        PackageSetting pkgSetting;
8244        final int uid = Binder.getCallingUid();
8245        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8246                + userId);
8247        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8248            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8249        }
8250
8251        long callingId = Binder.clearCallingIdentity();
8252        try {
8253            boolean sendAdded = false;
8254            Bundle extras = new Bundle(1);
8255
8256            // writer
8257            synchronized (mPackages) {
8258                pkgSetting = mSettings.mPackages.get(packageName);
8259                if (pkgSetting == null) {
8260                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8261                }
8262                if (!pkgSetting.getInstalled(userId)) {
8263                    pkgSetting.setInstalled(true, userId);
8264                    pkgSetting.setHidden(false, userId);
8265                    mSettings.writePackageRestrictionsLPr(userId);
8266                    sendAdded = true;
8267                }
8268            }
8269
8270            if (sendAdded) {
8271                sendPackageAddedForUser(packageName, pkgSetting, userId);
8272            }
8273        } finally {
8274            Binder.restoreCallingIdentity(callingId);
8275        }
8276
8277        return PackageManager.INSTALL_SUCCEEDED;
8278    }
8279
8280    boolean isUserRestricted(int userId, String restrictionKey) {
8281        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8282        if (restrictions.getBoolean(restrictionKey, false)) {
8283            Log.w(TAG, "User is restricted: " + restrictionKey);
8284            return true;
8285        }
8286        return false;
8287    }
8288
8289    @Override
8290    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8291        mContext.enforceCallingOrSelfPermission(
8292                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8293                "Only package verification agents can verify applications");
8294
8295        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8296        final PackageVerificationResponse response = new PackageVerificationResponse(
8297                verificationCode, Binder.getCallingUid());
8298        msg.arg1 = id;
8299        msg.obj = response;
8300        mHandler.sendMessage(msg);
8301    }
8302
8303    @Override
8304    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8305            long millisecondsToDelay) {
8306        mContext.enforceCallingOrSelfPermission(
8307                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8308                "Only package verification agents can extend verification timeouts");
8309
8310        final PackageVerificationState state = mPendingVerification.get(id);
8311        final PackageVerificationResponse response = new PackageVerificationResponse(
8312                verificationCodeAtTimeout, Binder.getCallingUid());
8313
8314        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8315            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8316        }
8317        if (millisecondsToDelay < 0) {
8318            millisecondsToDelay = 0;
8319        }
8320        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8321                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8322            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8323        }
8324
8325        if ((state != null) && !state.timeoutExtended()) {
8326            state.extendTimeout();
8327
8328            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8329            msg.arg1 = id;
8330            msg.obj = response;
8331            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8332        }
8333    }
8334
8335    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8336            int verificationCode, UserHandle user) {
8337        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8338        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8339        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8340        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8341        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8342
8343        mContext.sendBroadcastAsUser(intent, user,
8344                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8345    }
8346
8347    private ComponentName matchComponentForVerifier(String packageName,
8348            List<ResolveInfo> receivers) {
8349        ActivityInfo targetReceiver = null;
8350
8351        final int NR = receivers.size();
8352        for (int i = 0; i < NR; i++) {
8353            final ResolveInfo info = receivers.get(i);
8354            if (info.activityInfo == null) {
8355                continue;
8356            }
8357
8358            if (packageName.equals(info.activityInfo.packageName)) {
8359                targetReceiver = info.activityInfo;
8360                break;
8361            }
8362        }
8363
8364        if (targetReceiver == null) {
8365            return null;
8366        }
8367
8368        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8369    }
8370
8371    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8372            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8373        if (pkgInfo.verifiers.length == 0) {
8374            return null;
8375        }
8376
8377        final int N = pkgInfo.verifiers.length;
8378        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8379        for (int i = 0; i < N; i++) {
8380            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8381
8382            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8383                    receivers);
8384            if (comp == null) {
8385                continue;
8386            }
8387
8388            final int verifierUid = getUidForVerifier(verifierInfo);
8389            if (verifierUid == -1) {
8390                continue;
8391            }
8392
8393            if (DEBUG_VERIFY) {
8394                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8395                        + " with the correct signature");
8396            }
8397            sufficientVerifiers.add(comp);
8398            verificationState.addSufficientVerifier(verifierUid);
8399        }
8400
8401        return sufficientVerifiers;
8402    }
8403
8404    private int getUidForVerifier(VerifierInfo verifierInfo) {
8405        synchronized (mPackages) {
8406            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8407            if (pkg == null) {
8408                return -1;
8409            } else if (pkg.mSignatures.length != 1) {
8410                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8411                        + " has more than one signature; ignoring");
8412                return -1;
8413            }
8414
8415            /*
8416             * If the public key of the package's signature does not match
8417             * our expected public key, then this is a different package and
8418             * we should skip.
8419             */
8420
8421            final byte[] expectedPublicKey;
8422            try {
8423                final Signature verifierSig = pkg.mSignatures[0];
8424                final PublicKey publicKey = verifierSig.getPublicKey();
8425                expectedPublicKey = publicKey.getEncoded();
8426            } catch (CertificateException e) {
8427                return -1;
8428            }
8429
8430            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8431
8432            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8433                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8434                        + " does not have the expected public key; ignoring");
8435                return -1;
8436            }
8437
8438            return pkg.applicationInfo.uid;
8439        }
8440    }
8441
8442    @Override
8443    public void finishPackageInstall(int token) {
8444        enforceSystemOrRoot("Only the system is allowed to finish installs");
8445
8446        if (DEBUG_INSTALL) {
8447            Slog.v(TAG, "BM finishing package install for " + token);
8448        }
8449
8450        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8451        mHandler.sendMessage(msg);
8452    }
8453
8454    /**
8455     * Get the verification agent timeout.
8456     *
8457     * @return verification timeout in milliseconds
8458     */
8459    private long getVerificationTimeout() {
8460        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8461                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8462                DEFAULT_VERIFICATION_TIMEOUT);
8463    }
8464
8465    /**
8466     * Get the default verification agent response code.
8467     *
8468     * @return default verification response code
8469     */
8470    private int getDefaultVerificationResponse() {
8471        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8472                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8473                DEFAULT_VERIFICATION_RESPONSE);
8474    }
8475
8476    /**
8477     * Check whether or not package verification has been enabled.
8478     *
8479     * @return true if verification should be performed
8480     */
8481    private boolean isVerificationEnabled(int userId, int installFlags) {
8482        if (!DEFAULT_VERIFY_ENABLE) {
8483            return false;
8484        }
8485
8486        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8487
8488        // Check if installing from ADB
8489        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8490            // Do not run verification in a test harness environment
8491            if (ActivityManager.isRunningInTestHarness()) {
8492                return false;
8493            }
8494            if (ensureVerifyAppsEnabled) {
8495                return true;
8496            }
8497            // Check if the developer does not want package verification for ADB installs
8498            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8499                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8500                return false;
8501            }
8502        }
8503
8504        if (ensureVerifyAppsEnabled) {
8505            return true;
8506        }
8507
8508        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8509                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8510    }
8511
8512    /**
8513     * Get the "allow unknown sources" setting.
8514     *
8515     * @return the current "allow unknown sources" setting
8516     */
8517    private int getUnknownSourcesSettings() {
8518        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8519                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8520                -1);
8521    }
8522
8523    @Override
8524    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8525        final int uid = Binder.getCallingUid();
8526        // writer
8527        synchronized (mPackages) {
8528            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8529            if (targetPackageSetting == null) {
8530                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8531            }
8532
8533            PackageSetting installerPackageSetting;
8534            if (installerPackageName != null) {
8535                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8536                if (installerPackageSetting == null) {
8537                    throw new IllegalArgumentException("Unknown installer package: "
8538                            + installerPackageName);
8539                }
8540            } else {
8541                installerPackageSetting = null;
8542            }
8543
8544            Signature[] callerSignature;
8545            Object obj = mSettings.getUserIdLPr(uid);
8546            if (obj != null) {
8547                if (obj instanceof SharedUserSetting) {
8548                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8549                } else if (obj instanceof PackageSetting) {
8550                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8551                } else {
8552                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8553                }
8554            } else {
8555                throw new SecurityException("Unknown calling uid " + uid);
8556            }
8557
8558            // Verify: can't set installerPackageName to a package that is
8559            // not signed with the same cert as the caller.
8560            if (installerPackageSetting != null) {
8561                if (compareSignatures(callerSignature,
8562                        installerPackageSetting.signatures.mSignatures)
8563                        != PackageManager.SIGNATURE_MATCH) {
8564                    throw new SecurityException(
8565                            "Caller does not have same cert as new installer package "
8566                            + installerPackageName);
8567                }
8568            }
8569
8570            // Verify: if target already has an installer package, it must
8571            // be signed with the same cert as the caller.
8572            if (targetPackageSetting.installerPackageName != null) {
8573                PackageSetting setting = mSettings.mPackages.get(
8574                        targetPackageSetting.installerPackageName);
8575                // If the currently set package isn't valid, then it's always
8576                // okay to change it.
8577                if (setting != null) {
8578                    if (compareSignatures(callerSignature,
8579                            setting.signatures.mSignatures)
8580                            != PackageManager.SIGNATURE_MATCH) {
8581                        throw new SecurityException(
8582                                "Caller does not have same cert as old installer package "
8583                                + targetPackageSetting.installerPackageName);
8584                    }
8585                }
8586            }
8587
8588            // Okay!
8589            targetPackageSetting.installerPackageName = installerPackageName;
8590            scheduleWriteSettingsLocked();
8591        }
8592    }
8593
8594    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8595        // Queue up an async operation since the package installation may take a little while.
8596        mHandler.post(new Runnable() {
8597            public void run() {
8598                mHandler.removeCallbacks(this);
8599                 // Result object to be returned
8600                PackageInstalledInfo res = new PackageInstalledInfo();
8601                res.returnCode = currentStatus;
8602                res.uid = -1;
8603                res.pkg = null;
8604                res.removedInfo = new PackageRemovedInfo();
8605                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8606                    args.doPreInstall(res.returnCode);
8607                    synchronized (mInstallLock) {
8608                        installPackageLI(args, res);
8609                    }
8610                    args.doPostInstall(res.returnCode, res.uid);
8611                }
8612
8613                // A restore should be performed at this point if (a) the install
8614                // succeeded, (b) the operation is not an update, and (c) the new
8615                // package has not opted out of backup participation.
8616                final boolean update = res.removedInfo.removedPackage != null;
8617                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8618                boolean doRestore = !update
8619                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8620
8621                // Set up the post-install work request bookkeeping.  This will be used
8622                // and cleaned up by the post-install event handling regardless of whether
8623                // there's a restore pass performed.  Token values are >= 1.
8624                int token;
8625                if (mNextInstallToken < 0) mNextInstallToken = 1;
8626                token = mNextInstallToken++;
8627
8628                PostInstallData data = new PostInstallData(args, res);
8629                mRunningInstalls.put(token, data);
8630                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8631
8632                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8633                    // Pass responsibility to the Backup Manager.  It will perform a
8634                    // restore if appropriate, then pass responsibility back to the
8635                    // Package Manager to run the post-install observer callbacks
8636                    // and broadcasts.
8637                    IBackupManager bm = IBackupManager.Stub.asInterface(
8638                            ServiceManager.getService(Context.BACKUP_SERVICE));
8639                    if (bm != null) {
8640                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8641                                + " to BM for possible restore");
8642                        try {
8643                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
8644                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8645                            } else {
8646                                doRestore = false;
8647                            }
8648                        } catch (RemoteException e) {
8649                            // can't happen; the backup manager is local
8650                        } catch (Exception e) {
8651                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8652                            doRestore = false;
8653                        }
8654                    } else {
8655                        Slog.e(TAG, "Backup Manager not found!");
8656                        doRestore = false;
8657                    }
8658                }
8659
8660                if (!doRestore) {
8661                    // No restore possible, or the Backup Manager was mysteriously not
8662                    // available -- just fire the post-install work request directly.
8663                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8664                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8665                    mHandler.sendMessage(msg);
8666                }
8667            }
8668        });
8669    }
8670
8671    private abstract class HandlerParams {
8672        private static final int MAX_RETRIES = 4;
8673
8674        /**
8675         * Number of times startCopy() has been attempted and had a non-fatal
8676         * error.
8677         */
8678        private int mRetries = 0;
8679
8680        /** User handle for the user requesting the information or installation. */
8681        private final UserHandle mUser;
8682
8683        HandlerParams(UserHandle user) {
8684            mUser = user;
8685        }
8686
8687        UserHandle getUser() {
8688            return mUser;
8689        }
8690
8691        final boolean startCopy() {
8692            boolean res;
8693            try {
8694                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8695
8696                if (++mRetries > MAX_RETRIES) {
8697                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8698                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8699                    handleServiceError();
8700                    return false;
8701                } else {
8702                    handleStartCopy();
8703                    res = true;
8704                }
8705            } catch (RemoteException e) {
8706                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8707                mHandler.sendEmptyMessage(MCS_RECONNECT);
8708                res = false;
8709            }
8710            handleReturnCode();
8711            return res;
8712        }
8713
8714        final void serviceError() {
8715            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8716            handleServiceError();
8717            handleReturnCode();
8718        }
8719
8720        abstract void handleStartCopy() throws RemoteException;
8721        abstract void handleServiceError();
8722        abstract void handleReturnCode();
8723    }
8724
8725    class MeasureParams extends HandlerParams {
8726        private final PackageStats mStats;
8727        private boolean mSuccess;
8728
8729        private final IPackageStatsObserver mObserver;
8730
8731        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8732            super(new UserHandle(stats.userHandle));
8733            mObserver = observer;
8734            mStats = stats;
8735        }
8736
8737        @Override
8738        public String toString() {
8739            return "MeasureParams{"
8740                + Integer.toHexString(System.identityHashCode(this))
8741                + " " + mStats.packageName + "}";
8742        }
8743
8744        @Override
8745        void handleStartCopy() throws RemoteException {
8746            synchronized (mInstallLock) {
8747                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8748            }
8749
8750            if (mSuccess) {
8751                final boolean mounted;
8752                if (Environment.isExternalStorageEmulated()) {
8753                    mounted = true;
8754                } else {
8755                    final String status = Environment.getExternalStorageState();
8756                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8757                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8758                }
8759
8760                if (mounted) {
8761                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8762
8763                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8764                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8765
8766                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8767                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8768
8769                    // Always subtract cache size, since it's a subdirectory
8770                    mStats.externalDataSize -= mStats.externalCacheSize;
8771
8772                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8773                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8774
8775                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8776                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8777                }
8778            }
8779        }
8780
8781        @Override
8782        void handleReturnCode() {
8783            if (mObserver != null) {
8784                try {
8785                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8786                } catch (RemoteException e) {
8787                    Slog.i(TAG, "Observer no longer exists.");
8788                }
8789            }
8790        }
8791
8792        @Override
8793        void handleServiceError() {
8794            Slog.e(TAG, "Could not measure application " + mStats.packageName
8795                            + " external storage");
8796        }
8797    }
8798
8799    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8800            throws RemoteException {
8801        long result = 0;
8802        for (File path : paths) {
8803            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8804        }
8805        return result;
8806    }
8807
8808    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8809        for (File path : paths) {
8810            try {
8811                mcs.clearDirectory(path.getAbsolutePath());
8812            } catch (RemoteException e) {
8813            }
8814        }
8815    }
8816
8817    static class OriginInfo {
8818        /**
8819         * Location where install is coming from, before it has been
8820         * copied/renamed into place. This could be a single monolithic APK
8821         * file, or a cluster directory. This location may be untrusted.
8822         */
8823        final File file;
8824        final String cid;
8825
8826        /**
8827         * Flag indicating that {@link #file} or {@link #cid} has already been
8828         * staged, meaning downstream users don't need to defensively copy the
8829         * contents.
8830         */
8831        final boolean staged;
8832
8833        /**
8834         * Flag indicating that {@link #file} or {@link #cid} is an already
8835         * installed app that is being moved.
8836         */
8837        final boolean existing;
8838
8839        final String resolvedPath;
8840        final File resolvedFile;
8841
8842        static OriginInfo fromNothing() {
8843            return new OriginInfo(null, null, false, false);
8844        }
8845
8846        static OriginInfo fromUntrustedFile(File file) {
8847            return new OriginInfo(file, null, false, false);
8848        }
8849
8850        static OriginInfo fromExistingFile(File file) {
8851            return new OriginInfo(file, null, false, true);
8852        }
8853
8854        static OriginInfo fromStagedFile(File file) {
8855            return new OriginInfo(file, null, true, false);
8856        }
8857
8858        static OriginInfo fromStagedContainer(String cid) {
8859            return new OriginInfo(null, cid, true, false);
8860        }
8861
8862        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8863            this.file = file;
8864            this.cid = cid;
8865            this.staged = staged;
8866            this.existing = existing;
8867
8868            if (cid != null) {
8869                resolvedPath = PackageHelper.getSdDir(cid);
8870                resolvedFile = new File(resolvedPath);
8871            } else if (file != null) {
8872                resolvedPath = file.getAbsolutePath();
8873                resolvedFile = file;
8874            } else {
8875                resolvedPath = null;
8876                resolvedFile = null;
8877            }
8878        }
8879    }
8880
8881    class InstallParams extends HandlerParams {
8882        final OriginInfo origin;
8883        final IPackageInstallObserver2 observer;
8884        int installFlags;
8885        final String installerPackageName;
8886        final VerificationParams verificationParams;
8887        private InstallArgs mArgs;
8888        private int mRet;
8889        final String packageAbiOverride;
8890
8891        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8892                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8893                String packageAbiOverride) {
8894            super(user);
8895            this.origin = origin;
8896            this.observer = observer;
8897            this.installFlags = installFlags;
8898            this.installerPackageName = installerPackageName;
8899            this.verificationParams = verificationParams;
8900            this.packageAbiOverride = packageAbiOverride;
8901        }
8902
8903        @Override
8904        public String toString() {
8905            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8906                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8907        }
8908
8909        public ManifestDigest getManifestDigest() {
8910            if (verificationParams == null) {
8911                return null;
8912            }
8913            return verificationParams.getManifestDigest();
8914        }
8915
8916        private int installLocationPolicy(PackageInfoLite pkgLite) {
8917            String packageName = pkgLite.packageName;
8918            int installLocation = pkgLite.installLocation;
8919            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8920            // reader
8921            synchronized (mPackages) {
8922                PackageParser.Package pkg = mPackages.get(packageName);
8923                if (pkg != null) {
8924                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8925                        // Check for downgrading.
8926                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8927                            try {
8928                                checkDowngrade(pkg, pkgLite);
8929                            } catch (PackageManagerException e) {
8930                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8931                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8932                            }
8933                        }
8934                        // Check for updated system application.
8935                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8936                            if (onSd) {
8937                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8938                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8939                            }
8940                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8941                        } else {
8942                            if (onSd) {
8943                                // Install flag overrides everything.
8944                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8945                            }
8946                            // If current upgrade specifies particular preference
8947                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8948                                // Application explicitly specified internal.
8949                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8950                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8951                                // App explictly prefers external. Let policy decide
8952                            } else {
8953                                // Prefer previous location
8954                                if (isExternal(pkg)) {
8955                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8956                                }
8957                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8958                            }
8959                        }
8960                    } else {
8961                        // Invalid install. Return error code
8962                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8963                    }
8964                }
8965            }
8966            // All the special cases have been taken care of.
8967            // Return result based on recommended install location.
8968            if (onSd) {
8969                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8970            }
8971            return pkgLite.recommendedInstallLocation;
8972        }
8973
8974        /*
8975         * Invoke remote method to get package information and install
8976         * location values. Override install location based on default
8977         * policy if needed and then create install arguments based
8978         * on the install location.
8979         */
8980        public void handleStartCopy() throws RemoteException {
8981            int ret = PackageManager.INSTALL_SUCCEEDED;
8982
8983            // If we're already staged, we've firmly committed to an install location
8984            if (origin.staged) {
8985                if (origin.file != null) {
8986                    installFlags |= PackageManager.INSTALL_INTERNAL;
8987                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8988                } else if (origin.cid != null) {
8989                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8990                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8991                } else {
8992                    throw new IllegalStateException("Invalid stage location");
8993                }
8994            }
8995
8996            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8997            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8998
8999            PackageInfoLite pkgLite = null;
9000
9001            if (onInt && onSd) {
9002                // Check if both bits are set.
9003                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9004                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9005            } else {
9006                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9007                        packageAbiOverride);
9008
9009                /*
9010                 * If we have too little free space, try to free cache
9011                 * before giving up.
9012                 */
9013                if (!origin.staged && pkgLite.recommendedInstallLocation
9014                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9015                    // TODO: focus freeing disk space on the target device
9016                    final StorageManager storage = StorageManager.from(mContext);
9017                    final long lowThreshold = storage.getStorageLowBytes(
9018                            Environment.getDataDirectory());
9019
9020                    final long sizeBytes = mContainerService.calculateInstalledSize(
9021                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9022
9023                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9024                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9025                                installFlags, packageAbiOverride);
9026                    }
9027
9028                    /*
9029                     * The cache free must have deleted the file we
9030                     * downloaded to install.
9031                     *
9032                     * TODO: fix the "freeCache" call to not delete
9033                     *       the file we care about.
9034                     */
9035                    if (pkgLite.recommendedInstallLocation
9036                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9037                        pkgLite.recommendedInstallLocation
9038                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9039                    }
9040                }
9041            }
9042
9043            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9044                int loc = pkgLite.recommendedInstallLocation;
9045                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9046                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9047                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9048                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9049                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9050                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9051                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9052                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9053                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9054                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9055                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9056                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9057                } else {
9058                    // Override with defaults if needed.
9059                    loc = installLocationPolicy(pkgLite);
9060                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9061                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9062                    } else if (!onSd && !onInt) {
9063                        // Override install location with flags
9064                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9065                            // Set the flag to install on external media.
9066                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9067                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9068                        } else {
9069                            // Make sure the flag for installing on external
9070                            // media is unset
9071                            installFlags |= PackageManager.INSTALL_INTERNAL;
9072                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9073                        }
9074                    }
9075                }
9076            }
9077
9078            final InstallArgs args = createInstallArgs(this);
9079            mArgs = args;
9080
9081            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9082                 /*
9083                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9084                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9085                 */
9086                int userIdentifier = getUser().getIdentifier();
9087                if (userIdentifier == UserHandle.USER_ALL
9088                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9089                    userIdentifier = UserHandle.USER_OWNER;
9090                }
9091
9092                /*
9093                 * Determine if we have any installed package verifiers. If we
9094                 * do, then we'll defer to them to verify the packages.
9095                 */
9096                final int requiredUid = mRequiredVerifierPackage == null ? -1
9097                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9098                if (!origin.existing && requiredUid != -1
9099                        && isVerificationEnabled(userIdentifier, installFlags)) {
9100                    final Intent verification = new Intent(
9101                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9102                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9103                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9104                            PACKAGE_MIME_TYPE);
9105                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9106
9107                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9108                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9109                            0 /* TODO: Which userId? */);
9110
9111                    if (DEBUG_VERIFY) {
9112                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9113                                + verification.toString() + " with " + pkgLite.verifiers.length
9114                                + " optional verifiers");
9115                    }
9116
9117                    final int verificationId = mPendingVerificationToken++;
9118
9119                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9120
9121                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9122                            installerPackageName);
9123
9124                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9125                            installFlags);
9126
9127                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9128                            pkgLite.packageName);
9129
9130                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9131                            pkgLite.versionCode);
9132
9133                    if (verificationParams != null) {
9134                        if (verificationParams.getVerificationURI() != null) {
9135                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9136                                 verificationParams.getVerificationURI());
9137                        }
9138                        if (verificationParams.getOriginatingURI() != null) {
9139                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9140                                  verificationParams.getOriginatingURI());
9141                        }
9142                        if (verificationParams.getReferrer() != null) {
9143                            verification.putExtra(Intent.EXTRA_REFERRER,
9144                                  verificationParams.getReferrer());
9145                        }
9146                        if (verificationParams.getOriginatingUid() >= 0) {
9147                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9148                                  verificationParams.getOriginatingUid());
9149                        }
9150                        if (verificationParams.getInstallerUid() >= 0) {
9151                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9152                                  verificationParams.getInstallerUid());
9153                        }
9154                    }
9155
9156                    final PackageVerificationState verificationState = new PackageVerificationState(
9157                            requiredUid, args);
9158
9159                    mPendingVerification.append(verificationId, verificationState);
9160
9161                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9162                            receivers, verificationState);
9163
9164                    /*
9165                     * If any sufficient verifiers were listed in the package
9166                     * manifest, attempt to ask them.
9167                     */
9168                    if (sufficientVerifiers != null) {
9169                        final int N = sufficientVerifiers.size();
9170                        if (N == 0) {
9171                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9172                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9173                        } else {
9174                            for (int i = 0; i < N; i++) {
9175                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9176
9177                                final Intent sufficientIntent = new Intent(verification);
9178                                sufficientIntent.setComponent(verifierComponent);
9179
9180                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9181                            }
9182                        }
9183                    }
9184
9185                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9186                            mRequiredVerifierPackage, receivers);
9187                    if (ret == PackageManager.INSTALL_SUCCEEDED
9188                            && mRequiredVerifierPackage != null) {
9189                        /*
9190                         * Send the intent to the required verification agent,
9191                         * but only start the verification timeout after the
9192                         * target BroadcastReceivers have run.
9193                         */
9194                        verification.setComponent(requiredVerifierComponent);
9195                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9196                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9197                                new BroadcastReceiver() {
9198                                    @Override
9199                                    public void onReceive(Context context, Intent intent) {
9200                                        final Message msg = mHandler
9201                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9202                                        msg.arg1 = verificationId;
9203                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9204                                    }
9205                                }, null, 0, null, null);
9206
9207                        /*
9208                         * We don't want the copy to proceed until verification
9209                         * succeeds, so null out this field.
9210                         */
9211                        mArgs = null;
9212                    }
9213                } else {
9214                    /*
9215                     * No package verification is enabled, so immediately start
9216                     * the remote call to initiate copy using temporary file.
9217                     */
9218                    ret = args.copyApk(mContainerService, true);
9219                }
9220            }
9221
9222            mRet = ret;
9223        }
9224
9225        @Override
9226        void handleReturnCode() {
9227            // If mArgs is null, then MCS couldn't be reached. When it
9228            // reconnects, it will try again to install. At that point, this
9229            // will succeed.
9230            if (mArgs != null) {
9231                processPendingInstall(mArgs, mRet);
9232            }
9233        }
9234
9235        @Override
9236        void handleServiceError() {
9237            mArgs = createInstallArgs(this);
9238            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9239        }
9240
9241        public boolean isForwardLocked() {
9242            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9243        }
9244    }
9245
9246    /**
9247     * Used during creation of InstallArgs
9248     *
9249     * @param installFlags package installation flags
9250     * @return true if should be installed on external storage
9251     */
9252    private static boolean installOnSd(int installFlags) {
9253        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9254            return false;
9255        }
9256        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9257            return true;
9258        }
9259        return false;
9260    }
9261
9262    /**
9263     * Used during creation of InstallArgs
9264     *
9265     * @param installFlags package installation flags
9266     * @return true if should be installed as forward locked
9267     */
9268    private static boolean installForwardLocked(int installFlags) {
9269        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9270    }
9271
9272    private InstallArgs createInstallArgs(InstallParams params) {
9273        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9274            return new AsecInstallArgs(params);
9275        } else {
9276            return new FileInstallArgs(params);
9277        }
9278    }
9279
9280    /**
9281     * Create args that describe an existing installed package. Typically used
9282     * when cleaning up old installs, or used as a move source.
9283     */
9284    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9285            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9286        final boolean isInAsec;
9287        if (installOnSd(installFlags)) {
9288            /* Apps on SD card are always in ASEC containers. */
9289            isInAsec = true;
9290        } else if (installForwardLocked(installFlags)
9291                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9292            /*
9293             * Forward-locked apps are only in ASEC containers if they're the
9294             * new style
9295             */
9296            isInAsec = true;
9297        } else {
9298            isInAsec = false;
9299        }
9300
9301        if (isInAsec) {
9302            return new AsecInstallArgs(codePath, instructionSets,
9303                    installOnSd(installFlags), installForwardLocked(installFlags));
9304        } else {
9305            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9306                    instructionSets);
9307        }
9308    }
9309
9310    static abstract class InstallArgs {
9311        /** @see InstallParams#origin */
9312        final OriginInfo origin;
9313
9314        final IPackageInstallObserver2 observer;
9315        // Always refers to PackageManager flags only
9316        final int installFlags;
9317        final String installerPackageName;
9318        final ManifestDigest manifestDigest;
9319        final UserHandle user;
9320        final String abiOverride;
9321
9322        // The list of instruction sets supported by this app. This is currently
9323        // only used during the rmdex() phase to clean up resources. We can get rid of this
9324        // if we move dex files under the common app path.
9325        /* nullable */ String[] instructionSets;
9326
9327        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9328                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9329                String[] instructionSets, String abiOverride) {
9330            this.origin = origin;
9331            this.installFlags = installFlags;
9332            this.observer = observer;
9333            this.installerPackageName = installerPackageName;
9334            this.manifestDigest = manifestDigest;
9335            this.user = user;
9336            this.instructionSets = instructionSets;
9337            this.abiOverride = abiOverride;
9338        }
9339
9340        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9341        abstract int doPreInstall(int status);
9342
9343        /**
9344         * Rename package into final resting place. All paths on the given
9345         * scanned package should be updated to reflect the rename.
9346         */
9347        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9348        abstract int doPostInstall(int status, int uid);
9349
9350        /** @see PackageSettingBase#codePathString */
9351        abstract String getCodePath();
9352        /** @see PackageSettingBase#resourcePathString */
9353        abstract String getResourcePath();
9354        abstract String getLegacyNativeLibraryPath();
9355
9356        // Need installer lock especially for dex file removal.
9357        abstract void cleanUpResourcesLI();
9358        abstract boolean doPostDeleteLI(boolean delete);
9359        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9360
9361        /**
9362         * Called before the source arguments are copied. This is used mostly
9363         * for MoveParams when it needs to read the source file to put it in the
9364         * destination.
9365         */
9366        int doPreCopy() {
9367            return PackageManager.INSTALL_SUCCEEDED;
9368        }
9369
9370        /**
9371         * Called after the source arguments are copied. This is used mostly for
9372         * MoveParams when it needs to read the source file to put it in the
9373         * destination.
9374         *
9375         * @return
9376         */
9377        int doPostCopy(int uid) {
9378            return PackageManager.INSTALL_SUCCEEDED;
9379        }
9380
9381        protected boolean isFwdLocked() {
9382            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9383        }
9384
9385        protected boolean isExternal() {
9386            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9387        }
9388
9389        UserHandle getUser() {
9390            return user;
9391        }
9392    }
9393
9394    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9395        if (!allCodePaths.isEmpty()) {
9396            if (instructionSets == null) {
9397                throw new IllegalStateException("instructionSet == null");
9398            }
9399            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9400            for (String codePath : allCodePaths) {
9401                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9402                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9403                    if (retCode < 0) {
9404                        Slog.w(TAG, "Couldn't remove dex file for package: "
9405                                + " at location " + codePath + ", retcode=" + retCode);
9406                        // we don't consider this to be a failure of the core package deletion
9407                    }
9408                }
9409            }
9410        }
9411    }
9412
9413    /**
9414     * Logic to handle installation of non-ASEC applications, including copying
9415     * and renaming logic.
9416     */
9417    class FileInstallArgs extends InstallArgs {
9418        private File codeFile;
9419        private File resourceFile;
9420        private File legacyNativeLibraryPath;
9421
9422        // Example topology:
9423        // /data/app/com.example/base.apk
9424        // /data/app/com.example/split_foo.apk
9425        // /data/app/com.example/lib/arm/libfoo.so
9426        // /data/app/com.example/lib/arm64/libfoo.so
9427        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9428
9429        /** New install */
9430        FileInstallArgs(InstallParams params) {
9431            super(params.origin, params.observer, params.installFlags,
9432                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9433                    null /* instruction sets */, params.packageAbiOverride);
9434            if (isFwdLocked()) {
9435                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9436            }
9437        }
9438
9439        /** Existing install */
9440        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9441                String[] instructionSets) {
9442            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9443            this.codeFile = (codePath != null) ? new File(codePath) : null;
9444            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9445            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9446                    new File(legacyNativeLibraryPath) : null;
9447        }
9448
9449        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9450            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9451                    isFwdLocked(), abiOverride);
9452
9453            final StorageManager storage = StorageManager.from(mContext);
9454            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9455        }
9456
9457        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9458            if (origin.staged) {
9459                Slog.d(TAG, origin.file + " already staged; skipping copy");
9460                codeFile = origin.file;
9461                resourceFile = origin.file;
9462                return PackageManager.INSTALL_SUCCEEDED;
9463            }
9464
9465            try {
9466                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9467                codeFile = tempDir;
9468                resourceFile = tempDir;
9469            } catch (IOException e) {
9470                Slog.w(TAG, "Failed to create copy file: " + e);
9471                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9472            }
9473
9474            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9475                @Override
9476                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9477                    if (!FileUtils.isValidExtFilename(name)) {
9478                        throw new IllegalArgumentException("Invalid filename: " + name);
9479                    }
9480                    try {
9481                        final File file = new File(codeFile, name);
9482                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9483                                O_RDWR | O_CREAT, 0644);
9484                        Os.chmod(file.getAbsolutePath(), 0644);
9485                        return new ParcelFileDescriptor(fd);
9486                    } catch (ErrnoException e) {
9487                        throw new RemoteException("Failed to open: " + e.getMessage());
9488                    }
9489                }
9490            };
9491
9492            int ret = PackageManager.INSTALL_SUCCEEDED;
9493            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9494            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9495                Slog.e(TAG, "Failed to copy package");
9496                return ret;
9497            }
9498
9499            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9500            NativeLibraryHelper.Handle handle = null;
9501            try {
9502                handle = NativeLibraryHelper.Handle.create(codeFile);
9503                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9504                        abiOverride);
9505            } catch (IOException e) {
9506                Slog.e(TAG, "Copying native libraries failed", e);
9507                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9508            } finally {
9509                IoUtils.closeQuietly(handle);
9510            }
9511
9512            return ret;
9513        }
9514
9515        int doPreInstall(int status) {
9516            if (status != PackageManager.INSTALL_SUCCEEDED) {
9517                cleanUp();
9518            }
9519            return status;
9520        }
9521
9522        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9523            if (status != PackageManager.INSTALL_SUCCEEDED) {
9524                cleanUp();
9525                return false;
9526            } else {
9527                final File beforeCodeFile = codeFile;
9528                final File afterCodeFile = getNextCodePath(pkg.packageName);
9529
9530                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9531                try {
9532                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9533                } catch (ErrnoException e) {
9534                    Slog.d(TAG, "Failed to rename", e);
9535                    return false;
9536                }
9537
9538                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9539                    Slog.d(TAG, "Failed to restorecon");
9540                    return false;
9541                }
9542
9543                // Reflect the rename internally
9544                codeFile = afterCodeFile;
9545                resourceFile = afterCodeFile;
9546
9547                // Reflect the rename in scanned details
9548                pkg.codePath = afterCodeFile.getAbsolutePath();
9549                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9550                        pkg.baseCodePath);
9551                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9552                        pkg.splitCodePaths);
9553
9554                // Reflect the rename in app info
9555                pkg.applicationInfo.setCodePath(pkg.codePath);
9556                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9557                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9558                pkg.applicationInfo.setResourcePath(pkg.codePath);
9559                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9560                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9561
9562                return true;
9563            }
9564        }
9565
9566        int doPostInstall(int status, int uid) {
9567            if (status != PackageManager.INSTALL_SUCCEEDED) {
9568                cleanUp();
9569            }
9570            return status;
9571        }
9572
9573        @Override
9574        String getCodePath() {
9575            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9576        }
9577
9578        @Override
9579        String getResourcePath() {
9580            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9581        }
9582
9583        @Override
9584        String getLegacyNativeLibraryPath() {
9585            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9586        }
9587
9588        private boolean cleanUp() {
9589            if (codeFile == null || !codeFile.exists()) {
9590                return false;
9591            }
9592
9593            if (codeFile.isDirectory()) {
9594                FileUtils.deleteContents(codeFile);
9595            }
9596            codeFile.delete();
9597
9598            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9599                resourceFile.delete();
9600            }
9601
9602            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9603                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9604                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9605                }
9606                legacyNativeLibraryPath.delete();
9607            }
9608
9609            return true;
9610        }
9611
9612        void cleanUpResourcesLI() {
9613            // Try enumerating all code paths before deleting
9614            List<String> allCodePaths = Collections.EMPTY_LIST;
9615            if (codeFile != null && codeFile.exists()) {
9616                try {
9617                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9618                    allCodePaths = pkg.getAllCodePaths();
9619                } catch (PackageParserException e) {
9620                    // Ignored; we tried our best
9621                }
9622            }
9623
9624            cleanUp();
9625            removeDexFiles(allCodePaths, instructionSets);
9626        }
9627
9628        boolean doPostDeleteLI(boolean delete) {
9629            // XXX err, shouldn't we respect the delete flag?
9630            cleanUpResourcesLI();
9631            return true;
9632        }
9633    }
9634
9635    private boolean isAsecExternal(String cid) {
9636        final String asecPath = PackageHelper.getSdFilesystem(cid);
9637        return !asecPath.startsWith(mAsecInternalPath);
9638    }
9639
9640    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9641            PackageManagerException {
9642        if (copyRet < 0) {
9643            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9644                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9645                throw new PackageManagerException(copyRet, message);
9646            }
9647        }
9648    }
9649
9650    /**
9651     * Extract the MountService "container ID" from the full code path of an
9652     * .apk.
9653     */
9654    static String cidFromCodePath(String fullCodePath) {
9655        int eidx = fullCodePath.lastIndexOf("/");
9656        String subStr1 = fullCodePath.substring(0, eidx);
9657        int sidx = subStr1.lastIndexOf("/");
9658        return subStr1.substring(sidx+1, eidx);
9659    }
9660
9661    /**
9662     * Logic to handle installation of ASEC applications, including copying and
9663     * renaming logic.
9664     */
9665    class AsecInstallArgs extends InstallArgs {
9666        static final String RES_FILE_NAME = "pkg.apk";
9667        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9668
9669        String cid;
9670        String packagePath;
9671        String resourcePath;
9672        String legacyNativeLibraryDir;
9673
9674        /** New install */
9675        AsecInstallArgs(InstallParams params) {
9676            super(params.origin, params.observer, params.installFlags,
9677                    params.installerPackageName, params.getManifestDigest(),
9678                    params.getUser(), null /* instruction sets */,
9679                    params.packageAbiOverride);
9680        }
9681
9682        /** Existing install */
9683        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9684                        boolean isExternal, boolean isForwardLocked) {
9685            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9686                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9687                    instructionSets, null);
9688            // Hackily pretend we're still looking at a full code path
9689            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9690                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9691            }
9692
9693            // Extract cid from fullCodePath
9694            int eidx = fullCodePath.lastIndexOf("/");
9695            String subStr1 = fullCodePath.substring(0, eidx);
9696            int sidx = subStr1.lastIndexOf("/");
9697            cid = subStr1.substring(sidx+1, eidx);
9698            setMountPath(subStr1);
9699        }
9700
9701        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9702            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9703                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9704                    instructionSets, null);
9705            this.cid = cid;
9706            setMountPath(PackageHelper.getSdDir(cid));
9707        }
9708
9709        void createCopyFile() {
9710            cid = mInstallerService.allocateExternalStageCidLegacy();
9711        }
9712
9713        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9714            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9715                    abiOverride);
9716
9717            final File target;
9718            if (isExternal()) {
9719                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9720            } else {
9721                target = Environment.getDataDirectory();
9722            }
9723
9724            final StorageManager storage = StorageManager.from(mContext);
9725            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9726        }
9727
9728        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9729            if (origin.staged) {
9730                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9731                cid = origin.cid;
9732                setMountPath(PackageHelper.getSdDir(cid));
9733                return PackageManager.INSTALL_SUCCEEDED;
9734            }
9735
9736            if (temp) {
9737                createCopyFile();
9738            } else {
9739                /*
9740                 * Pre-emptively destroy the container since it's destroyed if
9741                 * copying fails due to it existing anyway.
9742                 */
9743                PackageHelper.destroySdDir(cid);
9744            }
9745
9746            final String newMountPath = imcs.copyPackageToContainer(
9747                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9748                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9749
9750            if (newMountPath != null) {
9751                setMountPath(newMountPath);
9752                return PackageManager.INSTALL_SUCCEEDED;
9753            } else {
9754                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9755            }
9756        }
9757
9758        @Override
9759        String getCodePath() {
9760            return packagePath;
9761        }
9762
9763        @Override
9764        String getResourcePath() {
9765            return resourcePath;
9766        }
9767
9768        @Override
9769        String getLegacyNativeLibraryPath() {
9770            return legacyNativeLibraryDir;
9771        }
9772
9773        int doPreInstall(int status) {
9774            if (status != PackageManager.INSTALL_SUCCEEDED) {
9775                // Destroy container
9776                PackageHelper.destroySdDir(cid);
9777            } else {
9778                boolean mounted = PackageHelper.isContainerMounted(cid);
9779                if (!mounted) {
9780                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9781                            Process.SYSTEM_UID);
9782                    if (newMountPath != null) {
9783                        setMountPath(newMountPath);
9784                    } else {
9785                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9786                    }
9787                }
9788            }
9789            return status;
9790        }
9791
9792        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9793            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9794            String newMountPath = null;
9795            if (PackageHelper.isContainerMounted(cid)) {
9796                // Unmount the container
9797                if (!PackageHelper.unMountSdDir(cid)) {
9798                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9799                    return false;
9800                }
9801            }
9802            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9803                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9804                        " which might be stale. Will try to clean up.");
9805                // Clean up the stale container and proceed to recreate.
9806                if (!PackageHelper.destroySdDir(newCacheId)) {
9807                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9808                    return false;
9809                }
9810                // Successfully cleaned up stale container. Try to rename again.
9811                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9812                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9813                            + " inspite of cleaning it up.");
9814                    return false;
9815                }
9816            }
9817            if (!PackageHelper.isContainerMounted(newCacheId)) {
9818                Slog.w(TAG, "Mounting container " + newCacheId);
9819                newMountPath = PackageHelper.mountSdDir(newCacheId,
9820                        getEncryptKey(), Process.SYSTEM_UID);
9821            } else {
9822                newMountPath = PackageHelper.getSdDir(newCacheId);
9823            }
9824            if (newMountPath == null) {
9825                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9826                return false;
9827            }
9828            Log.i(TAG, "Succesfully renamed " + cid +
9829                    " to " + newCacheId +
9830                    " at new path: " + newMountPath);
9831            cid = newCacheId;
9832
9833            final File beforeCodeFile = new File(packagePath);
9834            setMountPath(newMountPath);
9835            final File afterCodeFile = new File(packagePath);
9836
9837            // Reflect the rename in scanned details
9838            pkg.codePath = afterCodeFile.getAbsolutePath();
9839            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9840                    pkg.baseCodePath);
9841            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9842                    pkg.splitCodePaths);
9843
9844            // Reflect the rename in app info
9845            pkg.applicationInfo.setCodePath(pkg.codePath);
9846            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9847            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9848            pkg.applicationInfo.setResourcePath(pkg.codePath);
9849            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9850            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9851
9852            return true;
9853        }
9854
9855        private void setMountPath(String mountPath) {
9856            final File mountFile = new File(mountPath);
9857
9858            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9859            if (monolithicFile.exists()) {
9860                packagePath = monolithicFile.getAbsolutePath();
9861                if (isFwdLocked()) {
9862                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9863                } else {
9864                    resourcePath = packagePath;
9865                }
9866            } else {
9867                packagePath = mountFile.getAbsolutePath();
9868                resourcePath = packagePath;
9869            }
9870
9871            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9872        }
9873
9874        int doPostInstall(int status, int uid) {
9875            if (status != PackageManager.INSTALL_SUCCEEDED) {
9876                cleanUp();
9877            } else {
9878                final int groupOwner;
9879                final String protectedFile;
9880                if (isFwdLocked()) {
9881                    groupOwner = UserHandle.getSharedAppGid(uid);
9882                    protectedFile = RES_FILE_NAME;
9883                } else {
9884                    groupOwner = -1;
9885                    protectedFile = null;
9886                }
9887
9888                if (uid < Process.FIRST_APPLICATION_UID
9889                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9890                    Slog.e(TAG, "Failed to finalize " + cid);
9891                    PackageHelper.destroySdDir(cid);
9892                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9893                }
9894
9895                boolean mounted = PackageHelper.isContainerMounted(cid);
9896                if (!mounted) {
9897                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9898                }
9899            }
9900            return status;
9901        }
9902
9903        private void cleanUp() {
9904            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9905
9906            // Destroy secure container
9907            PackageHelper.destroySdDir(cid);
9908        }
9909
9910        private List<String> getAllCodePaths() {
9911            final File codeFile = new File(getCodePath());
9912            if (codeFile != null && codeFile.exists()) {
9913                try {
9914                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9915                    return pkg.getAllCodePaths();
9916                } catch (PackageParserException e) {
9917                    // Ignored; we tried our best
9918                }
9919            }
9920            return Collections.EMPTY_LIST;
9921        }
9922
9923        void cleanUpResourcesLI() {
9924            // Enumerate all code paths before deleting
9925            cleanUpResourcesLI(getAllCodePaths());
9926        }
9927
9928        private void cleanUpResourcesLI(List<String> allCodePaths) {
9929            cleanUp();
9930            removeDexFiles(allCodePaths, instructionSets);
9931        }
9932
9933
9934
9935        String getPackageName() {
9936            return getAsecPackageName(cid);
9937        }
9938
9939        boolean doPostDeleteLI(boolean delete) {
9940            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9941            final List<String> allCodePaths = getAllCodePaths();
9942            boolean mounted = PackageHelper.isContainerMounted(cid);
9943            if (mounted) {
9944                // Unmount first
9945                if (PackageHelper.unMountSdDir(cid)) {
9946                    mounted = false;
9947                }
9948            }
9949            if (!mounted && delete) {
9950                cleanUpResourcesLI(allCodePaths);
9951            }
9952            return !mounted;
9953        }
9954
9955        @Override
9956        int doPreCopy() {
9957            if (isFwdLocked()) {
9958                if (!PackageHelper.fixSdPermissions(cid,
9959                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9960                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9961                }
9962            }
9963
9964            return PackageManager.INSTALL_SUCCEEDED;
9965        }
9966
9967        @Override
9968        int doPostCopy(int uid) {
9969            if (isFwdLocked()) {
9970                if (uid < Process.FIRST_APPLICATION_UID
9971                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9972                                RES_FILE_NAME)) {
9973                    Slog.e(TAG, "Failed to finalize " + cid);
9974                    PackageHelper.destroySdDir(cid);
9975                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9976                }
9977            }
9978
9979            return PackageManager.INSTALL_SUCCEEDED;
9980        }
9981    }
9982
9983    static String getAsecPackageName(String packageCid) {
9984        int idx = packageCid.lastIndexOf("-");
9985        if (idx == -1) {
9986            return packageCid;
9987        }
9988        return packageCid.substring(0, idx);
9989    }
9990
9991    // Utility method used to create code paths based on package name and available index.
9992    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9993        String idxStr = "";
9994        int idx = 1;
9995        // Fall back to default value of idx=1 if prefix is not
9996        // part of oldCodePath
9997        if (oldCodePath != null) {
9998            String subStr = oldCodePath;
9999            // Drop the suffix right away
10000            if (suffix != null && subStr.endsWith(suffix)) {
10001                subStr = subStr.substring(0, subStr.length() - suffix.length());
10002            }
10003            // If oldCodePath already contains prefix find out the
10004            // ending index to either increment or decrement.
10005            int sidx = subStr.lastIndexOf(prefix);
10006            if (sidx != -1) {
10007                subStr = subStr.substring(sidx + prefix.length());
10008                if (subStr != null) {
10009                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10010                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10011                    }
10012                    try {
10013                        idx = Integer.parseInt(subStr);
10014                        if (idx <= 1) {
10015                            idx++;
10016                        } else {
10017                            idx--;
10018                        }
10019                    } catch(NumberFormatException e) {
10020                    }
10021                }
10022            }
10023        }
10024        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10025        return prefix + idxStr;
10026    }
10027
10028    private File getNextCodePath(String packageName) {
10029        int suffix = 1;
10030        File result;
10031        do {
10032            result = new File(mAppInstallDir, packageName + "-" + suffix);
10033            suffix++;
10034        } while (result.exists());
10035        return result;
10036    }
10037
10038    // Utility method used to ignore ADD/REMOVE events
10039    // by directory observer.
10040    private static boolean ignoreCodePath(String fullPathStr) {
10041        String apkName = deriveCodePathName(fullPathStr);
10042        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
10043        if (idx != -1 && ((idx+1) < apkName.length())) {
10044            // Make sure the package ends with a numeral
10045            String version = apkName.substring(idx+1);
10046            try {
10047                Integer.parseInt(version);
10048                return true;
10049            } catch (NumberFormatException e) {}
10050        }
10051        return false;
10052    }
10053
10054    // Utility method that returns the relative package path with respect
10055    // to the installation directory. Like say for /data/data/com.test-1.apk
10056    // string com.test-1 is returned.
10057    static String deriveCodePathName(String codePath) {
10058        if (codePath == null) {
10059            return null;
10060        }
10061        final File codeFile = new File(codePath);
10062        final String name = codeFile.getName();
10063        if (codeFile.isDirectory()) {
10064            return name;
10065        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10066            final int lastDot = name.lastIndexOf('.');
10067            return name.substring(0, lastDot);
10068        } else {
10069            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10070            return null;
10071        }
10072    }
10073
10074    class PackageInstalledInfo {
10075        String name;
10076        int uid;
10077        // The set of users that originally had this package installed.
10078        int[] origUsers;
10079        // The set of users that now have this package installed.
10080        int[] newUsers;
10081        PackageParser.Package pkg;
10082        int returnCode;
10083        String returnMsg;
10084        PackageRemovedInfo removedInfo;
10085
10086        public void setError(int code, String msg) {
10087            returnCode = code;
10088            returnMsg = msg;
10089            Slog.w(TAG, msg);
10090        }
10091
10092        public void setError(String msg, PackageParserException e) {
10093            returnCode = e.error;
10094            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10095            Slog.w(TAG, msg, e);
10096        }
10097
10098        public void setError(String msg, PackageManagerException e) {
10099            returnCode = e.error;
10100            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10101            Slog.w(TAG, msg, e);
10102        }
10103
10104        // In some error cases we want to convey more info back to the observer
10105        String origPackage;
10106        String origPermission;
10107    }
10108
10109    /*
10110     * Install a non-existing package.
10111     */
10112    private void installNewPackageLI(PackageParser.Package pkg,
10113            int parseFlags, int scanFlags, UserHandle user,
10114            String installerPackageName, PackageInstalledInfo res) {
10115        // Remember this for later, in case we need to rollback this install
10116        String pkgName = pkg.packageName;
10117
10118        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10119        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10120        synchronized(mPackages) {
10121            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10122                // A package with the same name is already installed, though
10123                // it has been renamed to an older name.  The package we
10124                // are trying to install should be installed as an update to
10125                // the existing one, but that has not been requested, so bail.
10126                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10127                        + " without first uninstalling package running as "
10128                        + mSettings.mRenamedPackages.get(pkgName));
10129                return;
10130            }
10131            if (mPackages.containsKey(pkgName)) {
10132                // Don't allow installation over an existing package with the same name.
10133                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10134                        + " without first uninstalling.");
10135                return;
10136            }
10137        }
10138
10139        try {
10140            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10141                    System.currentTimeMillis(), user);
10142
10143            updateSettingsLI(newPackage, installerPackageName, null, null, res, user);
10144            // delete the partially installed application. the data directory will have to be
10145            // restored if it was already existing
10146            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10147                // remove package from internal structures.  Note that we want deletePackageX to
10148                // delete the package data and cache directories that it created in
10149                // scanPackageLocked, unless those directories existed before we even tried to
10150                // install.
10151                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10152                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10153                                res.removedInfo, true);
10154            }
10155
10156        } catch (PackageManagerException e) {
10157            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10158        }
10159    }
10160
10161    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10162        // Upgrade keysets are being used.  Determine if new package has a superset of the
10163        // required keys.
10164        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10165        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10166        for (int i = 0; i < upgradeKeySets.length; i++) {
10167            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10168            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10169                return true;
10170            }
10171        }
10172        return false;
10173    }
10174
10175    private void replacePackageLI(PackageParser.Package pkg,
10176            int parseFlags, int scanFlags, UserHandle user,
10177            String installerPackageName, PackageInstalledInfo res) {
10178        PackageParser.Package oldPackage;
10179        String pkgName = pkg.packageName;
10180        int[] allUsers;
10181        boolean[] perUserInstalled;
10182
10183        // First find the old package info and check signatures
10184        synchronized(mPackages) {
10185            oldPackage = mPackages.get(pkgName);
10186            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10187            PackageSetting ps = mSettings.mPackages.get(pkgName);
10188            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10189                // default to original signature matching
10190                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10191                    != PackageManager.SIGNATURE_MATCH) {
10192                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10193                            "New package has a different signature: " + pkgName);
10194                    return;
10195                }
10196            } else {
10197                if(!checkUpgradeKeySetLP(ps, pkg)) {
10198                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10199                            "New package not signed by keys specified by upgrade-keysets: "
10200                            + pkgName);
10201                    return;
10202                }
10203            }
10204
10205            // In case of rollback, remember per-user/profile install state
10206            allUsers = sUserManager.getUserIds();
10207            perUserInstalled = new boolean[allUsers.length];
10208            for (int i = 0; i < allUsers.length; i++) {
10209                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10210            }
10211        }
10212
10213        boolean sysPkg = (isSystemApp(oldPackage));
10214        if (sysPkg) {
10215            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10216                    user, allUsers, perUserInstalled, installerPackageName, res);
10217        } else {
10218            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10219                    user, allUsers, perUserInstalled, installerPackageName, res);
10220        }
10221    }
10222
10223    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10224            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10225            int[] allUsers, boolean[] perUserInstalled,
10226            String installerPackageName, PackageInstalledInfo res) {
10227        String pkgName = deletedPackage.packageName;
10228        boolean deletedPkg = true;
10229        boolean updatedSettings = false;
10230
10231        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10232                + deletedPackage);
10233        long origUpdateTime;
10234        if (pkg.mExtras != null) {
10235            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10236        } else {
10237            origUpdateTime = 0;
10238        }
10239
10240        // First delete the existing package while retaining the data directory
10241        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10242                res.removedInfo, true)) {
10243            // If the existing package wasn't successfully deleted
10244            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10245            deletedPkg = false;
10246        } else {
10247            // Successfully deleted the old package; proceed with replace.
10248
10249            // If deleted package lived in a container, give users a chance to
10250            // relinquish resources before killing.
10251            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10252                if (DEBUG_INSTALL) {
10253                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10254                }
10255                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10256                final ArrayList<String> pkgList = new ArrayList<String>(1);
10257                pkgList.add(deletedPackage.applicationInfo.packageName);
10258                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10259            }
10260
10261            deleteCodeCacheDirsLI(pkgName);
10262            try {
10263                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10264                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10265                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res,
10266                        user);
10267                updatedSettings = true;
10268            } catch (PackageManagerException e) {
10269                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10270            }
10271        }
10272
10273        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10274            // remove package from internal structures.  Note that we want deletePackageX to
10275            // delete the package data and cache directories that it created in
10276            // scanPackageLocked, unless those directories existed before we even tried to
10277            // install.
10278            if(updatedSettings) {
10279                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10280                deletePackageLI(
10281                        pkgName, null, true, allUsers, perUserInstalled,
10282                        PackageManager.DELETE_KEEP_DATA,
10283                                res.removedInfo, true);
10284            }
10285            // Since we failed to install the new package we need to restore the old
10286            // package that we deleted.
10287            if (deletedPkg) {
10288                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10289                File restoreFile = new File(deletedPackage.codePath);
10290                // Parse old package
10291                boolean oldOnSd = isExternal(deletedPackage);
10292                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10293                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10294                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10295                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10296                try {
10297                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10298                } catch (PackageManagerException e) {
10299                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10300                            + e.getMessage());
10301                    return;
10302                }
10303                // Restore of old package succeeded. Update permissions.
10304                // writer
10305                synchronized (mPackages) {
10306                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10307                            UPDATE_PERMISSIONS_ALL);
10308                    // can downgrade to reader
10309                    mSettings.writeLPr();
10310                }
10311                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10312            }
10313        }
10314    }
10315
10316    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10317            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10318            int[] allUsers, boolean[] perUserInstalled,
10319            String installerPackageName, PackageInstalledInfo res) {
10320        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10321                + ", old=" + deletedPackage);
10322        boolean disabledSystem = false;
10323        boolean updatedSettings = false;
10324        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10325        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10326                != 0) {
10327            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10328        }
10329        String packageName = deletedPackage.packageName;
10330        if (packageName == null) {
10331            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10332                    "Attempt to delete null packageName.");
10333            return;
10334        }
10335        PackageParser.Package oldPkg;
10336        PackageSetting oldPkgSetting;
10337        // reader
10338        synchronized (mPackages) {
10339            oldPkg = mPackages.get(packageName);
10340            oldPkgSetting = mSettings.mPackages.get(packageName);
10341            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10342                    (oldPkgSetting == null)) {
10343                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10344                        "Couldn't find package:" + packageName + " information");
10345                return;
10346            }
10347        }
10348
10349        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10350
10351        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10352        res.removedInfo.removedPackage = packageName;
10353        // Remove existing system package
10354        removePackageLI(oldPkgSetting, true);
10355        // writer
10356        synchronized (mPackages) {
10357            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10358            if (!disabledSystem && deletedPackage != null) {
10359                // We didn't need to disable the .apk as a current system package,
10360                // which means we are replacing another update that is already
10361                // installed.  We need to make sure to delete the older one's .apk.
10362                res.removedInfo.args = createInstallArgsForExisting(0,
10363                        deletedPackage.applicationInfo.getCodePath(),
10364                        deletedPackage.applicationInfo.getResourcePath(),
10365                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10366                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10367            } else {
10368                res.removedInfo.args = null;
10369            }
10370        }
10371
10372        // Successfully disabled the old package. Now proceed with re-installation
10373        deleteCodeCacheDirsLI(packageName);
10374
10375        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10376        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10377
10378        PackageParser.Package newPackage = null;
10379        try {
10380            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10381            if (newPackage.mExtras != null) {
10382                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10383                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10384                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10385
10386                // is the update attempting to change shared user? that isn't going to work...
10387                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10388                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10389                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10390                            + " to " + newPkgSetting.sharedUser);
10391                    updatedSettings = true;
10392                }
10393            }
10394
10395            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10396                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res,
10397                        user);
10398                updatedSettings = true;
10399            }
10400
10401        } catch (PackageManagerException e) {
10402            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10403        }
10404
10405        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10406            // Re installation failed. Restore old information
10407            // Remove new pkg information
10408            if (newPackage != null) {
10409                removeInstalledPackageLI(newPackage, true);
10410            }
10411            // Add back the old system package
10412            try {
10413                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10414            } catch (PackageManagerException e) {
10415                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10416            }
10417            // Restore the old system information in Settings
10418            synchronized (mPackages) {
10419                if (disabledSystem) {
10420                    mSettings.enableSystemPackageLPw(packageName);
10421                }
10422                if (updatedSettings) {
10423                    mSettings.setInstallerPackageName(packageName,
10424                            oldPkgSetting.installerPackageName);
10425                }
10426                mSettings.writeLPr();
10427            }
10428        }
10429    }
10430
10431    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10432            int[] allUsers, boolean[] perUserInstalled,
10433            PackageInstalledInfo res, UserHandle user) {
10434        String pkgName = newPackage.packageName;
10435        synchronized (mPackages) {
10436            //write settings. the installStatus will be incomplete at this stage.
10437            //note that the new package setting would have already been
10438            //added to mPackages. It hasn't been persisted yet.
10439            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10440            mSettings.writeLPr();
10441        }
10442
10443        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10444
10445        synchronized (mPackages) {
10446            updatePermissionsLPw(newPackage.packageName, newPackage,
10447                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10448                            ? UPDATE_PERMISSIONS_ALL : 0));
10449            // For system-bundled packages, we assume that installing an upgraded version
10450            // of the package implies that the user actually wants to run that new code,
10451            // so we enable the package.
10452            PackageSetting ps = mSettings.mPackages.get(pkgName);
10453            if (ps != null) {
10454                if (isSystemApp(newPackage)) {
10455                    // NB: implicit assumption that system package upgrades apply to all users
10456                    if (DEBUG_INSTALL) {
10457                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10458                    }
10459                    if (res.origUsers != null) {
10460                        for (int userHandle : res.origUsers) {
10461                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10462                                    userHandle, installerPackageName);
10463                        }
10464                    }
10465                    // Also convey the prior install/uninstall state
10466                    if (allUsers != null && perUserInstalled != null) {
10467                        for (int i = 0; i < allUsers.length; i++) {
10468                            if (DEBUG_INSTALL) {
10469                                Slog.d(TAG, "    user " + allUsers[i]
10470                                        + " => " + perUserInstalled[i]);
10471                            }
10472                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10473                        }
10474                        // these install state changes will be persisted in the
10475                        // upcoming call to mSettings.writeLPr().
10476                    }
10477                }
10478                // It's implied that when a user requests installation, they want the app to be
10479                // installed and enabled.
10480                int userId = user.getIdentifier();
10481                if (userId != UserHandle.USER_ALL) {
10482                    ps.setInstalled(true, userId);
10483                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
10484                }
10485            }
10486            res.name = pkgName;
10487            res.uid = newPackage.applicationInfo.uid;
10488            res.pkg = newPackage;
10489            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10490            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10491            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10492            //to update install status
10493            mSettings.writeLPr();
10494        }
10495    }
10496
10497    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10498        final int installFlags = args.installFlags;
10499        String installerPackageName = args.installerPackageName;
10500        File tmpPackageFile = new File(args.getCodePath());
10501        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10502        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10503        boolean replace = false;
10504        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10505        // Result object to be returned
10506        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10507
10508        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10509        // Retrieve PackageSettings and parse package
10510        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10511                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10512                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10513        PackageParser pp = new PackageParser();
10514        pp.setSeparateProcesses(mSeparateProcesses);
10515        pp.setDisplayMetrics(mMetrics);
10516
10517        final PackageParser.Package pkg;
10518        try {
10519            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10520        } catch (PackageParserException e) {
10521            res.setError("Failed parse during installPackageLI", e);
10522            return;
10523        }
10524
10525        // Mark that we have an install time CPU ABI override.
10526        pkg.cpuAbiOverride = args.abiOverride;
10527
10528        String pkgName = res.name = pkg.packageName;
10529        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10530            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10531                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10532                return;
10533            }
10534        }
10535
10536        try {
10537            pp.collectCertificates(pkg, parseFlags);
10538            pp.collectManifestDigest(pkg);
10539        } catch (PackageParserException e) {
10540            res.setError("Failed collect during installPackageLI", e);
10541            return;
10542        }
10543
10544        /* If the installer passed in a manifest digest, compare it now. */
10545        if (args.manifestDigest != null) {
10546            if (DEBUG_INSTALL) {
10547                final String parsedManifest = pkg.manifestDigest == null ? "null"
10548                        : pkg.manifestDigest.toString();
10549                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10550                        + parsedManifest);
10551            }
10552
10553            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10554                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10555                return;
10556            }
10557        } else if (DEBUG_INSTALL) {
10558            final String parsedManifest = pkg.manifestDigest == null
10559                    ? "null" : pkg.manifestDigest.toString();
10560            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10561        }
10562
10563        // Get rid of all references to package scan path via parser.
10564        pp = null;
10565        String oldCodePath = null;
10566        boolean systemApp = false;
10567        synchronized (mPackages) {
10568            // Check if installing already existing package
10569            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10570                String oldName = mSettings.mRenamedPackages.get(pkgName);
10571                if (pkg.mOriginalPackages != null
10572                        && pkg.mOriginalPackages.contains(oldName)
10573                        && mPackages.containsKey(oldName)) {
10574                    // This package is derived from an original package,
10575                    // and this device has been updating from that original
10576                    // name.  We must continue using the original name, so
10577                    // rename the new package here.
10578                    pkg.setPackageName(oldName);
10579                    pkgName = pkg.packageName;
10580                    replace = true;
10581                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10582                            + oldName + " pkgName=" + pkgName);
10583                } else if (mPackages.containsKey(pkgName)) {
10584                    // This package, under its official name, already exists
10585                    // on the device; we should replace it.
10586                    replace = true;
10587                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10588                }
10589            }
10590
10591            PackageSetting ps = mSettings.mPackages.get(pkgName);
10592            if (ps != null) {
10593                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10594
10595                // Quick sanity check that we're signed correctly if updating;
10596                // we'll check this again later when scanning, but we want to
10597                // bail early here before tripping over redefined permissions.
10598                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10599                    try {
10600                        verifySignaturesLP(ps, pkg);
10601                    } catch (PackageManagerException e) {
10602                        res.setError(e.error, e.getMessage());
10603                        return;
10604                    }
10605                } else {
10606                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10607                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10608                                + pkg.packageName + " upgrade keys do not match the "
10609                                + "previously installed version");
10610                        return;
10611                    }
10612                }
10613
10614                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10615                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10616                    systemApp = (ps.pkg.applicationInfo.flags &
10617                            ApplicationInfo.FLAG_SYSTEM) != 0;
10618                }
10619                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10620            }
10621
10622            // Check whether the newly-scanned package wants to define an already-defined perm
10623            int N = pkg.permissions.size();
10624            for (int i = N-1; i >= 0; i--) {
10625                PackageParser.Permission perm = pkg.permissions.get(i);
10626                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10627                if (bp != null) {
10628                    // If the defining package is signed with our cert, it's okay.  This
10629                    // also includes the "updating the same package" case, of course.
10630                    // "updating same package" could also involve key-rotation.
10631                    final boolean sigsOk;
10632                    if (!bp.sourcePackage.equals(pkg.packageName)
10633                            || !(bp.packageSetting instanceof PackageSetting)
10634                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10635                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10636                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10637                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10638                    } else {
10639                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10640                    }
10641                    if (!sigsOk) {
10642                        // If the owning package is the system itself, we log but allow
10643                        // install to proceed; we fail the install on all other permission
10644                        // redefinitions.
10645                        if (!bp.sourcePackage.equals("android")) {
10646                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10647                                    + pkg.packageName + " attempting to redeclare permission "
10648                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10649                            res.origPermission = perm.info.name;
10650                            res.origPackage = bp.sourcePackage;
10651                            return;
10652                        } else {
10653                            Slog.w(TAG, "Package " + pkg.packageName
10654                                    + " attempting to redeclare system permission "
10655                                    + perm.info.name + "; ignoring new declaration");
10656                            pkg.permissions.remove(i);
10657                        }
10658                    }
10659                }
10660            }
10661
10662        }
10663
10664        if (systemApp && onSd) {
10665            // Disable updates to system apps on sdcard
10666            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10667                    "Cannot install updates to system apps on sdcard");
10668            return;
10669        }
10670
10671        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10672            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10673            return;
10674        }
10675
10676        if (replace) {
10677            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10678                    installerPackageName, res);
10679        } else {
10680            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10681                    args.user, installerPackageName, res);
10682        }
10683        synchronized (mPackages) {
10684            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10685            if (ps != null) {
10686                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10687            }
10688        }
10689    }
10690
10691    private static boolean isMultiArch(PackageSetting ps) {
10692        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10693    }
10694
10695    private static boolean isMultiArch(ApplicationInfo info) {
10696        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10697    }
10698
10699    private static boolean isExternal(PackageParser.Package pkg) {
10700        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10701    }
10702
10703    private static boolean isExternal(PackageSetting ps) {
10704        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10705    }
10706
10707    private static boolean isExternal(ApplicationInfo info) {
10708        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10709    }
10710
10711    private static boolean isSystemApp(PackageParser.Package pkg) {
10712        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10713    }
10714
10715    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10716        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
10717    }
10718
10719    private static boolean isSystemApp(ApplicationInfo info) {
10720        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10721    }
10722
10723    private static boolean isSystemApp(PackageSetting ps) {
10724        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10725    }
10726
10727    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10728        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10729    }
10730
10731    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10732        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10733    }
10734
10735    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10736        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10737    }
10738
10739    private int packageFlagsToInstallFlags(PackageSetting ps) {
10740        int installFlags = 0;
10741        if (isExternal(ps)) {
10742            installFlags |= PackageManager.INSTALL_EXTERNAL;
10743        }
10744        if (ps.isForwardLocked()) {
10745            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10746        }
10747        return installFlags;
10748    }
10749
10750    private void deleteTempPackageFiles() {
10751        final FilenameFilter filter = new FilenameFilter() {
10752            public boolean accept(File dir, String name) {
10753                return name.startsWith("vmdl") && name.endsWith(".tmp");
10754            }
10755        };
10756        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10757            file.delete();
10758        }
10759    }
10760
10761    @Override
10762    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10763            int flags) {
10764        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10765                flags);
10766    }
10767
10768    @Override
10769    public void deletePackage(final String packageName,
10770            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10771        mContext.enforceCallingOrSelfPermission(
10772                android.Manifest.permission.DELETE_PACKAGES, null);
10773        final int uid = Binder.getCallingUid();
10774        if (UserHandle.getUserId(uid) != userId) {
10775            mContext.enforceCallingPermission(
10776                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10777                    "deletePackage for user " + userId);
10778        }
10779        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10780            try {
10781                observer.onPackageDeleted(packageName,
10782                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10783            } catch (RemoteException re) {
10784            }
10785            return;
10786        }
10787
10788        boolean uninstallBlocked = false;
10789        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10790            int[] users = sUserManager.getUserIds();
10791            for (int i = 0; i < users.length; ++i) {
10792                if (getBlockUninstallForUser(packageName, users[i])) {
10793                    uninstallBlocked = true;
10794                    break;
10795                }
10796            }
10797        } else {
10798            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10799        }
10800        if (uninstallBlocked) {
10801            try {
10802                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10803                        null);
10804            } catch (RemoteException re) {
10805            }
10806            return;
10807        }
10808
10809        if (DEBUG_REMOVE) {
10810            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10811        }
10812        // Queue up an async operation since the package deletion may take a little while.
10813        mHandler.post(new Runnable() {
10814            public void run() {
10815                mHandler.removeCallbacks(this);
10816                final int returnCode = deletePackageX(packageName, userId, flags);
10817                if (observer != null) {
10818                    try {
10819                        observer.onPackageDeleted(packageName, returnCode, null);
10820                    } catch (RemoteException e) {
10821                        Log.i(TAG, "Observer no longer exists.");
10822                    } //end catch
10823                } //end if
10824            } //end run
10825        });
10826    }
10827
10828    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10829        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10830                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10831        try {
10832            if (dpm != null) {
10833                if (dpm.isDeviceOwner(packageName)) {
10834                    return true;
10835                }
10836                int[] users;
10837                if (userId == UserHandle.USER_ALL) {
10838                    users = sUserManager.getUserIds();
10839                } else {
10840                    users = new int[]{userId};
10841                }
10842                for (int i = 0; i < users.length; ++i) {
10843                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10844                        return true;
10845                    }
10846                }
10847            }
10848        } catch (RemoteException e) {
10849        }
10850        return false;
10851    }
10852
10853    /**
10854     *  This method is an internal method that could be get invoked either
10855     *  to delete an installed package or to clean up a failed installation.
10856     *  After deleting an installed package, a broadcast is sent to notify any
10857     *  listeners that the package has been installed. For cleaning up a failed
10858     *  installation, the broadcast is not necessary since the package's
10859     *  installation wouldn't have sent the initial broadcast either
10860     *  The key steps in deleting a package are
10861     *  deleting the package information in internal structures like mPackages,
10862     *  deleting the packages base directories through installd
10863     *  updating mSettings to reflect current status
10864     *  persisting settings for later use
10865     *  sending a broadcast if necessary
10866     */
10867    private int deletePackageX(String packageName, int userId, int flags) {
10868        final PackageRemovedInfo info = new PackageRemovedInfo();
10869        final boolean res;
10870
10871        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10872                ? UserHandle.ALL : new UserHandle(userId);
10873
10874        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10875            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10876            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10877        }
10878
10879        boolean removedForAllUsers = false;
10880        boolean systemUpdate = false;
10881
10882        // for the uninstall-updates case and restricted profiles, remember the per-
10883        // userhandle installed state
10884        int[] allUsers;
10885        boolean[] perUserInstalled;
10886        synchronized (mPackages) {
10887            PackageSetting ps = mSettings.mPackages.get(packageName);
10888            allUsers = sUserManager.getUserIds();
10889            perUserInstalled = new boolean[allUsers.length];
10890            for (int i = 0; i < allUsers.length; i++) {
10891                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10892            }
10893        }
10894
10895        synchronized (mInstallLock) {
10896            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10897            res = deletePackageLI(packageName, removeForUser,
10898                    true, allUsers, perUserInstalled,
10899                    flags | REMOVE_CHATTY, info, true);
10900            systemUpdate = info.isRemovedPackageSystemUpdate;
10901            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10902                removedForAllUsers = true;
10903            }
10904            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10905                    + " removedForAllUsers=" + removedForAllUsers);
10906        }
10907
10908        if (res) {
10909            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10910
10911            // If the removed package was a system update, the old system package
10912            // was re-enabled; we need to broadcast this information
10913            if (systemUpdate) {
10914                Bundle extras = new Bundle(1);
10915                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10916                        ? info.removedAppId : info.uid);
10917                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10918
10919                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10920                        extras, null, null, null);
10921                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10922                        extras, null, null, null);
10923                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10924                        null, packageName, null, null);
10925            }
10926        }
10927        // Force a gc here.
10928        Runtime.getRuntime().gc();
10929        // Delete the resources here after sending the broadcast to let
10930        // other processes clean up before deleting resources.
10931        if (info.args != null) {
10932            synchronized (mInstallLock) {
10933                info.args.doPostDeleteLI(true);
10934            }
10935        }
10936
10937        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10938    }
10939
10940    static class PackageRemovedInfo {
10941        String removedPackage;
10942        int uid = -1;
10943        int removedAppId = -1;
10944        int[] removedUsers = null;
10945        boolean isRemovedPackageSystemUpdate = false;
10946        // Clean up resources deleted packages.
10947        InstallArgs args = null;
10948
10949        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10950            Bundle extras = new Bundle(1);
10951            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10952            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10953            if (replacing) {
10954                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10955            }
10956            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10957            if (removedPackage != null) {
10958                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10959                        extras, null, null, removedUsers);
10960                if (fullRemove && !replacing) {
10961                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10962                            extras, null, null, removedUsers);
10963                }
10964            }
10965            if (removedAppId >= 0) {
10966                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10967                        removedUsers);
10968            }
10969        }
10970    }
10971
10972    /*
10973     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10974     * flag is not set, the data directory is removed as well.
10975     * make sure this flag is set for partially installed apps. If not its meaningless to
10976     * delete a partially installed application.
10977     */
10978    private void removePackageDataLI(PackageSetting ps,
10979            int[] allUserHandles, boolean[] perUserInstalled,
10980            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10981        String packageName = ps.name;
10982        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10983        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10984        // Retrieve object to delete permissions for shared user later on
10985        final PackageSetting deletedPs;
10986        // reader
10987        synchronized (mPackages) {
10988            deletedPs = mSettings.mPackages.get(packageName);
10989            if (outInfo != null) {
10990                outInfo.removedPackage = packageName;
10991                outInfo.removedUsers = deletedPs != null
10992                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10993                        : null;
10994            }
10995        }
10996        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10997            removeDataDirsLI(packageName);
10998            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10999        }
11000        // writer
11001        synchronized (mPackages) {
11002            if (deletedPs != null) {
11003                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11004                    if (outInfo != null) {
11005                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11006                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11007                    }
11008                    updatePermissionsLPw(deletedPs.name, null, 0);
11009                    if (deletedPs.sharedUser != null) {
11010                        // Remove permissions associated with package. Since runtime
11011                        // permissions are per user we have to kill the removed package
11012                        // or packages running under the shared user of the removed
11013                        // package if revoking the permissions requested only by the removed
11014                        // package is successful and this causes a change in gids.
11015                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11016                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11017                                    userId);
11018                            if (userIdToKill == userId) {
11019                                // If gids changed for this user, kill all affected packages.
11020                                killSettingPackagesForUser(deletedPs, userIdToKill,
11021                                        KILL_APP_REASON_GIDS_CHANGED);
11022                            } else if (userIdToKill == UserHandle.USER_ALL) {
11023                                // If gids changed for all users, kill them all - done.
11024                                killSettingPackagesForUser(deletedPs, userIdToKill,
11025                                        KILL_APP_REASON_GIDS_CHANGED);
11026                                break;
11027                            }
11028                        }
11029                    }
11030                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11031                }
11032                // make sure to preserve per-user disabled state if this removal was just
11033                // a downgrade of a system app to the factory package
11034                if (allUserHandles != null && perUserInstalled != null) {
11035                    if (DEBUG_REMOVE) {
11036                        Slog.d(TAG, "Propagating install state across downgrade");
11037                    }
11038                    for (int i = 0; i < allUserHandles.length; i++) {
11039                        if (DEBUG_REMOVE) {
11040                            Slog.d(TAG, "    user " + allUserHandles[i]
11041                                    + " => " + perUserInstalled[i]);
11042                        }
11043                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11044                    }
11045                }
11046            }
11047            // can downgrade to reader
11048            if (writeSettings) {
11049                // Save settings now
11050                mSettings.writeLPr();
11051            }
11052        }
11053        if (outInfo != null) {
11054            // A user ID was deleted here. Go through all users and remove it
11055            // from KeyStore.
11056            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11057        }
11058    }
11059
11060    static boolean locationIsPrivileged(File path) {
11061        try {
11062            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11063                    .getCanonicalPath();
11064            return path.getCanonicalPath().startsWith(privilegedAppDir);
11065        } catch (IOException e) {
11066            Slog.e(TAG, "Unable to access code path " + path);
11067        }
11068        return false;
11069    }
11070
11071    /*
11072     * Tries to delete system package.
11073     */
11074    private boolean deleteSystemPackageLI(PackageSetting newPs,
11075            int[] allUserHandles, boolean[] perUserInstalled,
11076            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11077        final boolean applyUserRestrictions
11078                = (allUserHandles != null) && (perUserInstalled != null);
11079        PackageSetting disabledPs = null;
11080        // Confirm if the system package has been updated
11081        // An updated system app can be deleted. This will also have to restore
11082        // the system pkg from system partition
11083        // reader
11084        synchronized (mPackages) {
11085            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11086        }
11087        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11088                + " disabledPs=" + disabledPs);
11089        if (disabledPs == null) {
11090            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11091            return false;
11092        } else if (DEBUG_REMOVE) {
11093            Slog.d(TAG, "Deleting system pkg from data partition");
11094        }
11095        if (DEBUG_REMOVE) {
11096            if (applyUserRestrictions) {
11097                Slog.d(TAG, "Remembering install states:");
11098                for (int i = 0; i < allUserHandles.length; i++) {
11099                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11100                }
11101            }
11102        }
11103        // Delete the updated package
11104        outInfo.isRemovedPackageSystemUpdate = true;
11105        if (disabledPs.versionCode < newPs.versionCode) {
11106            // Delete data for downgrades
11107            flags &= ~PackageManager.DELETE_KEEP_DATA;
11108        } else {
11109            // Preserve data by setting flag
11110            flags |= PackageManager.DELETE_KEEP_DATA;
11111        }
11112        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11113                allUserHandles, perUserInstalled, outInfo, writeSettings);
11114        if (!ret) {
11115            return false;
11116        }
11117        // writer
11118        synchronized (mPackages) {
11119            // Reinstate the old system package
11120            mSettings.enableSystemPackageLPw(newPs.name);
11121            // Remove any native libraries from the upgraded package.
11122            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11123        }
11124        // Install the system package
11125        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11126        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11127        if (locationIsPrivileged(disabledPs.codePath)) {
11128            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11129        }
11130
11131        final PackageParser.Package newPkg;
11132        try {
11133            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11134        } catch (PackageManagerException e) {
11135            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11136            return false;
11137        }
11138
11139        // writer
11140        synchronized (mPackages) {
11141            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11142            updatePermissionsLPw(newPkg.packageName, newPkg,
11143                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11144            if (applyUserRestrictions) {
11145                if (DEBUG_REMOVE) {
11146                    Slog.d(TAG, "Propagating install state across reinstall");
11147                }
11148                for (int i = 0; i < allUserHandles.length; i++) {
11149                    if (DEBUG_REMOVE) {
11150                        Slog.d(TAG, "    user " + allUserHandles[i]
11151                                + " => " + perUserInstalled[i]);
11152                    }
11153                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11154                }
11155                // Regardless of writeSettings we need to ensure that this restriction
11156                // state propagation is persisted
11157                mSettings.writeAllUsersPackageRestrictionsLPr();
11158            }
11159            // can downgrade to reader here
11160            if (writeSettings) {
11161                mSettings.writeLPr();
11162            }
11163        }
11164        return true;
11165    }
11166
11167    private boolean deleteInstalledPackageLI(PackageSetting ps,
11168            boolean deleteCodeAndResources, int flags,
11169            int[] allUserHandles, boolean[] perUserInstalled,
11170            PackageRemovedInfo outInfo, boolean writeSettings) {
11171        if (outInfo != null) {
11172            outInfo.uid = ps.appId;
11173        }
11174
11175        // Delete package data from internal structures and also remove data if flag is set
11176        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11177
11178        // Delete application code and resources
11179        if (deleteCodeAndResources && (outInfo != null)) {
11180            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11181                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11182                    getAppDexInstructionSets(ps));
11183            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11184        }
11185        return true;
11186    }
11187
11188    @Override
11189    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11190            int userId) {
11191        mContext.enforceCallingOrSelfPermission(
11192                android.Manifest.permission.DELETE_PACKAGES, null);
11193        synchronized (mPackages) {
11194            PackageSetting ps = mSettings.mPackages.get(packageName);
11195            if (ps == null) {
11196                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11197                return false;
11198            }
11199            if (!ps.getInstalled(userId)) {
11200                // Can't block uninstall for an app that is not installed or enabled.
11201                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11202                return false;
11203            }
11204            ps.setBlockUninstall(blockUninstall, userId);
11205            mSettings.writePackageRestrictionsLPr(userId);
11206        }
11207        return true;
11208    }
11209
11210    @Override
11211    public boolean getBlockUninstallForUser(String packageName, int userId) {
11212        synchronized (mPackages) {
11213            PackageSetting ps = mSettings.mPackages.get(packageName);
11214            if (ps == null) {
11215                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11216                return false;
11217            }
11218            return ps.getBlockUninstall(userId);
11219        }
11220    }
11221
11222    /*
11223     * This method handles package deletion in general
11224     */
11225    private boolean deletePackageLI(String packageName, UserHandle user,
11226            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11227            int flags, PackageRemovedInfo outInfo,
11228            boolean writeSettings) {
11229        if (packageName == null) {
11230            Slog.w(TAG, "Attempt to delete null packageName.");
11231            return false;
11232        }
11233        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11234        PackageSetting ps;
11235        boolean dataOnly = false;
11236        int removeUser = -1;
11237        int appId = -1;
11238        synchronized (mPackages) {
11239            ps = mSettings.mPackages.get(packageName);
11240            if (ps == null) {
11241                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11242                return false;
11243            }
11244            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11245                    && user.getIdentifier() != UserHandle.USER_ALL) {
11246                // The caller is asking that the package only be deleted for a single
11247                // user.  To do this, we just mark its uninstalled state and delete
11248                // its data.  If this is a system app, we only allow this to happen if
11249                // they have set the special DELETE_SYSTEM_APP which requests different
11250                // semantics than normal for uninstalling system apps.
11251                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11252                ps.setUserState(user.getIdentifier(),
11253                        COMPONENT_ENABLED_STATE_DEFAULT,
11254                        false, //installed
11255                        true,  //stopped
11256                        true,  //notLaunched
11257                        false, //hidden
11258                        null, null, null,
11259                        false // blockUninstall
11260                        );
11261                if (!isSystemApp(ps)) {
11262                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11263                        // Other user still have this package installed, so all
11264                        // we need to do is clear this user's data and save that
11265                        // it is uninstalled.
11266                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11267                        removeUser = user.getIdentifier();
11268                        appId = ps.appId;
11269                        mSettings.writePackageRestrictionsLPr(removeUser);
11270                    } else {
11271                        // We need to set it back to 'installed' so the uninstall
11272                        // broadcasts will be sent correctly.
11273                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11274                        ps.setInstalled(true, user.getIdentifier());
11275                    }
11276                } else {
11277                    // This is a system app, so we assume that the
11278                    // other users still have this package installed, so all
11279                    // we need to do is clear this user's data and save that
11280                    // it is uninstalled.
11281                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11282                    removeUser = user.getIdentifier();
11283                    appId = ps.appId;
11284                    mSettings.writePackageRestrictionsLPr(removeUser);
11285                }
11286            }
11287        }
11288
11289        if (removeUser >= 0) {
11290            // From above, we determined that we are deleting this only
11291            // for a single user.  Continue the work here.
11292            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11293            if (outInfo != null) {
11294                outInfo.removedPackage = packageName;
11295                outInfo.removedAppId = appId;
11296                outInfo.removedUsers = new int[] {removeUser};
11297            }
11298            mInstaller.clearUserData(packageName, removeUser);
11299            removeKeystoreDataIfNeeded(removeUser, appId);
11300            schedulePackageCleaning(packageName, removeUser, false);
11301            return true;
11302        }
11303
11304        if (dataOnly) {
11305            // Delete application data first
11306            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11307            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11308            return true;
11309        }
11310
11311        boolean ret = false;
11312        if (isSystemApp(ps)) {
11313            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11314            // When an updated system application is deleted we delete the existing resources as well and
11315            // fall back to existing code in system partition
11316            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11317                    flags, outInfo, writeSettings);
11318        } else {
11319            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11320            // Kill application pre-emptively especially for apps on sd.
11321            killApplication(packageName, ps.appId, "uninstall pkg");
11322            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11323                    allUserHandles, perUserInstalled,
11324                    outInfo, writeSettings);
11325        }
11326
11327        return ret;
11328    }
11329
11330    private final class ClearStorageConnection implements ServiceConnection {
11331        IMediaContainerService mContainerService;
11332
11333        @Override
11334        public void onServiceConnected(ComponentName name, IBinder service) {
11335            synchronized (this) {
11336                mContainerService = IMediaContainerService.Stub.asInterface(service);
11337                notifyAll();
11338            }
11339        }
11340
11341        @Override
11342        public void onServiceDisconnected(ComponentName name) {
11343        }
11344    }
11345
11346    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11347        final boolean mounted;
11348        if (Environment.isExternalStorageEmulated()) {
11349            mounted = true;
11350        } else {
11351            final String status = Environment.getExternalStorageState();
11352
11353            mounted = status.equals(Environment.MEDIA_MOUNTED)
11354                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11355        }
11356
11357        if (!mounted) {
11358            return;
11359        }
11360
11361        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11362        int[] users;
11363        if (userId == UserHandle.USER_ALL) {
11364            users = sUserManager.getUserIds();
11365        } else {
11366            users = new int[] { userId };
11367        }
11368        final ClearStorageConnection conn = new ClearStorageConnection();
11369        if (mContext.bindServiceAsUser(
11370                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11371            try {
11372                for (int curUser : users) {
11373                    long timeout = SystemClock.uptimeMillis() + 5000;
11374                    synchronized (conn) {
11375                        long now = SystemClock.uptimeMillis();
11376                        while (conn.mContainerService == null && now < timeout) {
11377                            try {
11378                                conn.wait(timeout - now);
11379                            } catch (InterruptedException e) {
11380                            }
11381                        }
11382                    }
11383                    if (conn.mContainerService == null) {
11384                        return;
11385                    }
11386
11387                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11388                    clearDirectory(conn.mContainerService,
11389                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11390                    if (allData) {
11391                        clearDirectory(conn.mContainerService,
11392                                userEnv.buildExternalStorageAppDataDirs(packageName));
11393                        clearDirectory(conn.mContainerService,
11394                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11395                    }
11396                }
11397            } finally {
11398                mContext.unbindService(conn);
11399            }
11400        }
11401    }
11402
11403    @Override
11404    public void clearApplicationUserData(final String packageName,
11405            final IPackageDataObserver observer, final int userId) {
11406        mContext.enforceCallingOrSelfPermission(
11407                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11408        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11409        // Queue up an async operation since the package deletion may take a little while.
11410        mHandler.post(new Runnable() {
11411            public void run() {
11412                mHandler.removeCallbacks(this);
11413                final boolean succeeded;
11414                synchronized (mInstallLock) {
11415                    succeeded = clearApplicationUserDataLI(packageName, userId);
11416                }
11417                clearExternalStorageDataSync(packageName, userId, true);
11418                if (succeeded) {
11419                    // invoke DeviceStorageMonitor's update method to clear any notifications
11420                    DeviceStorageMonitorInternal
11421                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11422                    if (dsm != null) {
11423                        dsm.checkMemory();
11424                    }
11425                }
11426                if(observer != null) {
11427                    try {
11428                        observer.onRemoveCompleted(packageName, succeeded);
11429                    } catch (RemoteException e) {
11430                        Log.i(TAG, "Observer no longer exists.");
11431                    }
11432                } //end if observer
11433            } //end run
11434        });
11435    }
11436
11437    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11438        if (packageName == null) {
11439            Slog.w(TAG, "Attempt to delete null packageName.");
11440            return false;
11441        }
11442
11443        // Try finding details about the requested package
11444        PackageParser.Package pkg;
11445        synchronized (mPackages) {
11446            pkg = mPackages.get(packageName);
11447            if (pkg == null) {
11448                final PackageSetting ps = mSettings.mPackages.get(packageName);
11449                if (ps != null) {
11450                    pkg = ps.pkg;
11451                }
11452            }
11453        }
11454
11455        if (pkg == null) {
11456            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11457        }
11458
11459        // Always delete data directories for package, even if we found no other
11460        // record of app. This helps users recover from UID mismatches without
11461        // resorting to a full data wipe.
11462        int retCode = mInstaller.clearUserData(packageName, userId);
11463        if (retCode < 0) {
11464            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11465            return false;
11466        }
11467
11468        if (pkg == null) {
11469            return false;
11470        }
11471
11472        if (pkg != null && pkg.applicationInfo != null) {
11473            final int appId = pkg.applicationInfo.uid;
11474            removeKeystoreDataIfNeeded(userId, appId);
11475        }
11476
11477        // Create a native library symlink only if we have native libraries
11478        // and if the native libraries are 32 bit libraries. We do not provide
11479        // this symlink for 64 bit libraries.
11480        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11481                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11482            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11483            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11484                Slog.w(TAG, "Failed linking native library dir");
11485                return false;
11486            }
11487        }
11488
11489        return true;
11490    }
11491
11492    /**
11493     * Remove entries from the keystore daemon. Will only remove it if the
11494     * {@code appId} is valid.
11495     */
11496    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11497        if (appId < 0) {
11498            return;
11499        }
11500
11501        final KeyStore keyStore = KeyStore.getInstance();
11502        if (keyStore != null) {
11503            if (userId == UserHandle.USER_ALL) {
11504                for (final int individual : sUserManager.getUserIds()) {
11505                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11506                }
11507            } else {
11508                keyStore.clearUid(UserHandle.getUid(userId, appId));
11509            }
11510        } else {
11511            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11512        }
11513    }
11514
11515    @Override
11516    public void deleteApplicationCacheFiles(final String packageName,
11517            final IPackageDataObserver observer) {
11518        mContext.enforceCallingOrSelfPermission(
11519                android.Manifest.permission.DELETE_CACHE_FILES, null);
11520        // Queue up an async operation since the package deletion may take a little while.
11521        final int userId = UserHandle.getCallingUserId();
11522        mHandler.post(new Runnable() {
11523            public void run() {
11524                mHandler.removeCallbacks(this);
11525                final boolean succeded;
11526                synchronized (mInstallLock) {
11527                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11528                }
11529                clearExternalStorageDataSync(packageName, userId, false);
11530                if(observer != null) {
11531                    try {
11532                        observer.onRemoveCompleted(packageName, succeded);
11533                    } catch (RemoteException e) {
11534                        Log.i(TAG, "Observer no longer exists.");
11535                    }
11536                } //end if observer
11537            } //end run
11538        });
11539    }
11540
11541    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11542        if (packageName == null) {
11543            Slog.w(TAG, "Attempt to delete null packageName.");
11544            return false;
11545        }
11546        PackageParser.Package p;
11547        synchronized (mPackages) {
11548            p = mPackages.get(packageName);
11549        }
11550        if (p == null) {
11551            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11552            return false;
11553        }
11554        final ApplicationInfo applicationInfo = p.applicationInfo;
11555        if (applicationInfo == null) {
11556            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11557            return false;
11558        }
11559        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11560        if (retCode < 0) {
11561            Slog.w(TAG, "Couldn't remove cache files for package: "
11562                       + packageName + " u" + userId);
11563            return false;
11564        }
11565        return true;
11566    }
11567
11568    @Override
11569    public void getPackageSizeInfo(final String packageName, int userHandle,
11570            final IPackageStatsObserver observer) {
11571        mContext.enforceCallingOrSelfPermission(
11572                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11573        if (packageName == null) {
11574            throw new IllegalArgumentException("Attempt to get size of null packageName");
11575        }
11576
11577        PackageStats stats = new PackageStats(packageName, userHandle);
11578
11579        /*
11580         * Queue up an async operation since the package measurement may take a
11581         * little while.
11582         */
11583        Message msg = mHandler.obtainMessage(INIT_COPY);
11584        msg.obj = new MeasureParams(stats, observer);
11585        mHandler.sendMessage(msg);
11586    }
11587
11588    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11589            PackageStats pStats) {
11590        if (packageName == null) {
11591            Slog.w(TAG, "Attempt to get size of null packageName.");
11592            return false;
11593        }
11594        PackageParser.Package p;
11595        boolean dataOnly = false;
11596        String libDirRoot = null;
11597        String asecPath = null;
11598        PackageSetting ps = null;
11599        synchronized (mPackages) {
11600            p = mPackages.get(packageName);
11601            ps = mSettings.mPackages.get(packageName);
11602            if(p == null) {
11603                dataOnly = true;
11604                if((ps == null) || (ps.pkg == null)) {
11605                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11606                    return false;
11607                }
11608                p = ps.pkg;
11609            }
11610            if (ps != null) {
11611                libDirRoot = ps.legacyNativeLibraryPathString;
11612            }
11613            if (p != null && (isExternal(p) || p.isForwardLocked())) {
11614                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11615                if (secureContainerId != null) {
11616                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11617                }
11618            }
11619        }
11620        String publicSrcDir = null;
11621        if(!dataOnly) {
11622            final ApplicationInfo applicationInfo = p.applicationInfo;
11623            if (applicationInfo == null) {
11624                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11625                return false;
11626            }
11627            if (p.isForwardLocked()) {
11628                publicSrcDir = applicationInfo.getBaseResourcePath();
11629            }
11630        }
11631        // TODO: extend to measure size of split APKs
11632        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11633        // not just the first level.
11634        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11635        // just the primary.
11636        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11637        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11638                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11639        if (res < 0) {
11640            return false;
11641        }
11642
11643        // Fix-up for forward-locked applications in ASEC containers.
11644        if (!isExternal(p)) {
11645            pStats.codeSize += pStats.externalCodeSize;
11646            pStats.externalCodeSize = 0L;
11647        }
11648
11649        return true;
11650    }
11651
11652
11653    @Override
11654    public void addPackageToPreferred(String packageName) {
11655        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11656    }
11657
11658    @Override
11659    public void removePackageFromPreferred(String packageName) {
11660        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11661    }
11662
11663    @Override
11664    public List<PackageInfo> getPreferredPackages(int flags) {
11665        return new ArrayList<PackageInfo>();
11666    }
11667
11668    private int getUidTargetSdkVersionLockedLPr(int uid) {
11669        Object obj = mSettings.getUserIdLPr(uid);
11670        if (obj instanceof SharedUserSetting) {
11671            final SharedUserSetting sus = (SharedUserSetting) obj;
11672            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11673            final Iterator<PackageSetting> it = sus.packages.iterator();
11674            while (it.hasNext()) {
11675                final PackageSetting ps = it.next();
11676                if (ps.pkg != null) {
11677                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11678                    if (v < vers) vers = v;
11679                }
11680            }
11681            return vers;
11682        } else if (obj instanceof PackageSetting) {
11683            final PackageSetting ps = (PackageSetting) obj;
11684            if (ps.pkg != null) {
11685                return ps.pkg.applicationInfo.targetSdkVersion;
11686            }
11687        }
11688        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11689    }
11690
11691    @Override
11692    public void addPreferredActivity(IntentFilter filter, int match,
11693            ComponentName[] set, ComponentName activity, int userId) {
11694        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11695                "Adding preferred");
11696    }
11697
11698    private void addPreferredActivityInternal(IntentFilter filter, int match,
11699            ComponentName[] set, ComponentName activity, boolean always, int userId,
11700            String opname) {
11701        // writer
11702        int callingUid = Binder.getCallingUid();
11703        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11704        if (filter.countActions() == 0) {
11705            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11706            return;
11707        }
11708        synchronized (mPackages) {
11709            if (mContext.checkCallingOrSelfPermission(
11710                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11711                    != PackageManager.PERMISSION_GRANTED) {
11712                if (getUidTargetSdkVersionLockedLPr(callingUid)
11713                        < Build.VERSION_CODES.FROYO) {
11714                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11715                            + callingUid);
11716                    return;
11717                }
11718                mContext.enforceCallingOrSelfPermission(
11719                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11720            }
11721
11722            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11723            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11724                    + userId + ":");
11725            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11726            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11727            scheduleWritePackageRestrictionsLocked(userId);
11728        }
11729    }
11730
11731    @Override
11732    public void replacePreferredActivity(IntentFilter filter, int match,
11733            ComponentName[] set, ComponentName activity, int userId) {
11734        if (filter.countActions() != 1) {
11735            throw new IllegalArgumentException(
11736                    "replacePreferredActivity expects filter to have only 1 action.");
11737        }
11738        if (filter.countDataAuthorities() != 0
11739                || filter.countDataPaths() != 0
11740                || filter.countDataSchemes() > 1
11741                || filter.countDataTypes() != 0) {
11742            throw new IllegalArgumentException(
11743                    "replacePreferredActivity expects filter to have no data authorities, " +
11744                    "paths, or types; and at most one scheme.");
11745        }
11746
11747        final int callingUid = Binder.getCallingUid();
11748        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11749        synchronized (mPackages) {
11750            if (mContext.checkCallingOrSelfPermission(
11751                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11752                    != PackageManager.PERMISSION_GRANTED) {
11753                if (getUidTargetSdkVersionLockedLPr(callingUid)
11754                        < Build.VERSION_CODES.FROYO) {
11755                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11756                            + Binder.getCallingUid());
11757                    return;
11758                }
11759                mContext.enforceCallingOrSelfPermission(
11760                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11761            }
11762
11763            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11764            if (pir != null) {
11765                // Get all of the existing entries that exactly match this filter.
11766                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11767                if (existing != null && existing.size() == 1) {
11768                    PreferredActivity cur = existing.get(0);
11769                    if (DEBUG_PREFERRED) {
11770                        Slog.i(TAG, "Checking replace of preferred:");
11771                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11772                        if (!cur.mPref.mAlways) {
11773                            Slog.i(TAG, "  -- CUR; not mAlways!");
11774                        } else {
11775                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11776                            Slog.i(TAG, "  -- CUR: mSet="
11777                                    + Arrays.toString(cur.mPref.mSetComponents));
11778                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11779                            Slog.i(TAG, "  -- NEW: mMatch="
11780                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11781                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11782                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11783                        }
11784                    }
11785                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11786                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11787                            && cur.mPref.sameSet(set)) {
11788                        // Setting the preferred activity to what it happens to be already
11789                        if (DEBUG_PREFERRED) {
11790                            Slog.i(TAG, "Replacing with same preferred activity "
11791                                    + cur.mPref.mShortComponent + " for user "
11792                                    + userId + ":");
11793                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11794                        }
11795                        return;
11796                    }
11797                }
11798
11799                if (existing != null) {
11800                    if (DEBUG_PREFERRED) {
11801                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11802                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11803                    }
11804                    for (int i = 0; i < existing.size(); i++) {
11805                        PreferredActivity pa = existing.get(i);
11806                        if (DEBUG_PREFERRED) {
11807                            Slog.i(TAG, "Removing existing preferred activity "
11808                                    + pa.mPref.mComponent + ":");
11809                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11810                        }
11811                        pir.removeFilter(pa);
11812                    }
11813                }
11814            }
11815            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11816                    "Replacing preferred");
11817        }
11818    }
11819
11820    @Override
11821    public void clearPackagePreferredActivities(String packageName) {
11822        final int uid = Binder.getCallingUid();
11823        // writer
11824        synchronized (mPackages) {
11825            PackageParser.Package pkg = mPackages.get(packageName);
11826            if (pkg == null || pkg.applicationInfo.uid != uid) {
11827                if (mContext.checkCallingOrSelfPermission(
11828                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11829                        != PackageManager.PERMISSION_GRANTED) {
11830                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11831                            < Build.VERSION_CODES.FROYO) {
11832                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11833                                + Binder.getCallingUid());
11834                        return;
11835                    }
11836                    mContext.enforceCallingOrSelfPermission(
11837                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11838                }
11839            }
11840
11841            int user = UserHandle.getCallingUserId();
11842            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11843                scheduleWritePackageRestrictionsLocked(user);
11844            }
11845        }
11846    }
11847
11848    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11849    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11850        ArrayList<PreferredActivity> removed = null;
11851        boolean changed = false;
11852        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11853            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11854            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11855            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11856                continue;
11857            }
11858            Iterator<PreferredActivity> it = pir.filterIterator();
11859            while (it.hasNext()) {
11860                PreferredActivity pa = it.next();
11861                // Mark entry for removal only if it matches the package name
11862                // and the entry is of type "always".
11863                if (packageName == null ||
11864                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11865                                && pa.mPref.mAlways)) {
11866                    if (removed == null) {
11867                        removed = new ArrayList<PreferredActivity>();
11868                    }
11869                    removed.add(pa);
11870                }
11871            }
11872            if (removed != null) {
11873                for (int j=0; j<removed.size(); j++) {
11874                    PreferredActivity pa = removed.get(j);
11875                    pir.removeFilter(pa);
11876                }
11877                changed = true;
11878            }
11879        }
11880        return changed;
11881    }
11882
11883    @Override
11884    public void resetPreferredActivities(int userId) {
11885        /* TODO: Actually use userId. Why is it being passed in? */
11886        mContext.enforceCallingOrSelfPermission(
11887                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11888        // writer
11889        synchronized (mPackages) {
11890            int user = UserHandle.getCallingUserId();
11891            clearPackagePreferredActivitiesLPw(null, user);
11892            mSettings.readDefaultPreferredAppsLPw(this, user);
11893            scheduleWritePackageRestrictionsLocked(user);
11894        }
11895    }
11896
11897    @Override
11898    public int getPreferredActivities(List<IntentFilter> outFilters,
11899            List<ComponentName> outActivities, String packageName) {
11900
11901        int num = 0;
11902        final int userId = UserHandle.getCallingUserId();
11903        // reader
11904        synchronized (mPackages) {
11905            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11906            if (pir != null) {
11907                final Iterator<PreferredActivity> it = pir.filterIterator();
11908                while (it.hasNext()) {
11909                    final PreferredActivity pa = it.next();
11910                    if (packageName == null
11911                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11912                                    && pa.mPref.mAlways)) {
11913                        if (outFilters != null) {
11914                            outFilters.add(new IntentFilter(pa));
11915                        }
11916                        if (outActivities != null) {
11917                            outActivities.add(pa.mPref.mComponent);
11918                        }
11919                    }
11920                }
11921            }
11922        }
11923
11924        return num;
11925    }
11926
11927    @Override
11928    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11929            int userId) {
11930        int callingUid = Binder.getCallingUid();
11931        if (callingUid != Process.SYSTEM_UID) {
11932            throw new SecurityException(
11933                    "addPersistentPreferredActivity can only be run by the system");
11934        }
11935        if (filter.countActions() == 0) {
11936            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11937            return;
11938        }
11939        synchronized (mPackages) {
11940            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11941                    " :");
11942            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11943            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11944                    new PersistentPreferredActivity(filter, activity));
11945            scheduleWritePackageRestrictionsLocked(userId);
11946        }
11947    }
11948
11949    @Override
11950    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11951        int callingUid = Binder.getCallingUid();
11952        if (callingUid != Process.SYSTEM_UID) {
11953            throw new SecurityException(
11954                    "clearPackagePersistentPreferredActivities can only be run by the system");
11955        }
11956        ArrayList<PersistentPreferredActivity> removed = null;
11957        boolean changed = false;
11958        synchronized (mPackages) {
11959            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11960                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11961                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11962                        .valueAt(i);
11963                if (userId != thisUserId) {
11964                    continue;
11965                }
11966                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11967                while (it.hasNext()) {
11968                    PersistentPreferredActivity ppa = it.next();
11969                    // Mark entry for removal only if it matches the package name.
11970                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11971                        if (removed == null) {
11972                            removed = new ArrayList<PersistentPreferredActivity>();
11973                        }
11974                        removed.add(ppa);
11975                    }
11976                }
11977                if (removed != null) {
11978                    for (int j=0; j<removed.size(); j++) {
11979                        PersistentPreferredActivity ppa = removed.get(j);
11980                        ppir.removeFilter(ppa);
11981                    }
11982                    changed = true;
11983                }
11984            }
11985
11986            if (changed) {
11987                scheduleWritePackageRestrictionsLocked(userId);
11988            }
11989        }
11990    }
11991
11992    @Override
11993    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11994            int sourceUserId, int targetUserId, int flags) {
11995        mContext.enforceCallingOrSelfPermission(
11996                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11997        int callingUid = Binder.getCallingUid();
11998        enforceOwnerRights(ownerPackage, callingUid);
11999        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12000        if (intentFilter.countActions() == 0) {
12001            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12002            return;
12003        }
12004        synchronized (mPackages) {
12005            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12006                    ownerPackage, targetUserId, flags);
12007            CrossProfileIntentResolver resolver =
12008                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12009            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12010            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12011            if (existing != null) {
12012                int size = existing.size();
12013                for (int i = 0; i < size; i++) {
12014                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12015                        return;
12016                    }
12017                }
12018            }
12019            resolver.addFilter(newFilter);
12020            scheduleWritePackageRestrictionsLocked(sourceUserId);
12021        }
12022    }
12023
12024    @Override
12025    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12026        mContext.enforceCallingOrSelfPermission(
12027                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12028        int callingUid = Binder.getCallingUid();
12029        enforceOwnerRights(ownerPackage, callingUid);
12030        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12031        synchronized (mPackages) {
12032            CrossProfileIntentResolver resolver =
12033                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12034            ArraySet<CrossProfileIntentFilter> set =
12035                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12036            for (CrossProfileIntentFilter filter : set) {
12037                if (filter.getOwnerPackage().equals(ownerPackage)) {
12038                    resolver.removeFilter(filter);
12039                }
12040            }
12041            scheduleWritePackageRestrictionsLocked(sourceUserId);
12042        }
12043    }
12044
12045    // Enforcing that callingUid is owning pkg on userId
12046    private void enforceOwnerRights(String pkg, int callingUid) {
12047        // The system owns everything.
12048        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12049            return;
12050        }
12051        int callingUserId = UserHandle.getUserId(callingUid);
12052        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12053        if (pi == null) {
12054            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12055                    + callingUserId);
12056        }
12057        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12058            throw new SecurityException("Calling uid " + callingUid
12059                    + " does not own package " + pkg);
12060        }
12061    }
12062
12063    @Override
12064    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12065        Intent intent = new Intent(Intent.ACTION_MAIN);
12066        intent.addCategory(Intent.CATEGORY_HOME);
12067
12068        final int callingUserId = UserHandle.getCallingUserId();
12069        List<ResolveInfo> list = queryIntentActivities(intent, null,
12070                PackageManager.GET_META_DATA, callingUserId);
12071        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12072                true, false, false, callingUserId);
12073
12074        allHomeCandidates.clear();
12075        if (list != null) {
12076            for (ResolveInfo ri : list) {
12077                allHomeCandidates.add(ri);
12078            }
12079        }
12080        return (preferred == null || preferred.activityInfo == null)
12081                ? null
12082                : new ComponentName(preferred.activityInfo.packageName,
12083                        preferred.activityInfo.name);
12084    }
12085
12086    @Override
12087    public void setApplicationEnabledSetting(String appPackageName,
12088            int newState, int flags, int userId, String callingPackage) {
12089        if (!sUserManager.exists(userId)) return;
12090        if (callingPackage == null) {
12091            callingPackage = Integer.toString(Binder.getCallingUid());
12092        }
12093        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12094    }
12095
12096    @Override
12097    public void setComponentEnabledSetting(ComponentName componentName,
12098            int newState, int flags, int userId) {
12099        if (!sUserManager.exists(userId)) return;
12100        setEnabledSetting(componentName.getPackageName(),
12101                componentName.getClassName(), newState, flags, userId, null);
12102    }
12103
12104    private void setEnabledSetting(final String packageName, String className, int newState,
12105            final int flags, int userId, String callingPackage) {
12106        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12107              || newState == COMPONENT_ENABLED_STATE_ENABLED
12108              || newState == COMPONENT_ENABLED_STATE_DISABLED
12109              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12110              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12111            throw new IllegalArgumentException("Invalid new component state: "
12112                    + newState);
12113        }
12114        PackageSetting pkgSetting;
12115        final int uid = Binder.getCallingUid();
12116        final int permission = mContext.checkCallingOrSelfPermission(
12117                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12118        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12119        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12120        boolean sendNow = false;
12121        boolean isApp = (className == null);
12122        String componentName = isApp ? packageName : className;
12123        int packageUid = -1;
12124        ArrayList<String> components;
12125
12126        // writer
12127        synchronized (mPackages) {
12128            pkgSetting = mSettings.mPackages.get(packageName);
12129            if (pkgSetting == null) {
12130                if (className == null) {
12131                    throw new IllegalArgumentException(
12132                            "Unknown package: " + packageName);
12133                }
12134                throw new IllegalArgumentException(
12135                        "Unknown component: " + packageName
12136                        + "/" + className);
12137            }
12138            // Allow root and verify that userId is not being specified by a different user
12139            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12140                throw new SecurityException(
12141                        "Permission Denial: attempt to change component state from pid="
12142                        + Binder.getCallingPid()
12143                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12144            }
12145            if (className == null) {
12146                // We're dealing with an application/package level state change
12147                if (pkgSetting.getEnabled(userId) == newState) {
12148                    // Nothing to do
12149                    return;
12150                }
12151                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12152                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12153                    // Don't care about who enables an app.
12154                    callingPackage = null;
12155                }
12156                pkgSetting.setEnabled(newState, userId, callingPackage);
12157                // pkgSetting.pkg.mSetEnabled = newState;
12158            } else {
12159                // We're dealing with a component level state change
12160                // First, verify that this is a valid class name.
12161                PackageParser.Package pkg = pkgSetting.pkg;
12162                if (pkg == null || !pkg.hasComponentClassName(className)) {
12163                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12164                        throw new IllegalArgumentException("Component class " + className
12165                                + " does not exist in " + packageName);
12166                    } else {
12167                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12168                                + className + " does not exist in " + packageName);
12169                    }
12170                }
12171                switch (newState) {
12172                case COMPONENT_ENABLED_STATE_ENABLED:
12173                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12174                        return;
12175                    }
12176                    break;
12177                case COMPONENT_ENABLED_STATE_DISABLED:
12178                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12179                        return;
12180                    }
12181                    break;
12182                case COMPONENT_ENABLED_STATE_DEFAULT:
12183                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12184                        return;
12185                    }
12186                    break;
12187                default:
12188                    Slog.e(TAG, "Invalid new component state: " + newState);
12189                    return;
12190                }
12191            }
12192            scheduleWritePackageRestrictionsLocked(userId);
12193            components = mPendingBroadcasts.get(userId, packageName);
12194            final boolean newPackage = components == null;
12195            if (newPackage) {
12196                components = new ArrayList<String>();
12197            }
12198            if (!components.contains(componentName)) {
12199                components.add(componentName);
12200            }
12201            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12202                sendNow = true;
12203                // Purge entry from pending broadcast list if another one exists already
12204                // since we are sending one right away.
12205                mPendingBroadcasts.remove(userId, packageName);
12206            } else {
12207                if (newPackage) {
12208                    mPendingBroadcasts.put(userId, packageName, components);
12209                }
12210                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12211                    // Schedule a message
12212                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12213                }
12214            }
12215        }
12216
12217        long callingId = Binder.clearCallingIdentity();
12218        try {
12219            if (sendNow) {
12220                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12221                sendPackageChangedBroadcast(packageName,
12222                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12223            }
12224        } finally {
12225            Binder.restoreCallingIdentity(callingId);
12226        }
12227    }
12228
12229    private void sendPackageChangedBroadcast(String packageName,
12230            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12231        if (DEBUG_INSTALL)
12232            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12233                    + componentNames);
12234        Bundle extras = new Bundle(4);
12235        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12236        String nameList[] = new String[componentNames.size()];
12237        componentNames.toArray(nameList);
12238        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12239        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12240        extras.putInt(Intent.EXTRA_UID, packageUid);
12241        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12242                new int[] {UserHandle.getUserId(packageUid)});
12243    }
12244
12245    @Override
12246    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12247        if (!sUserManager.exists(userId)) return;
12248        final int uid = Binder.getCallingUid();
12249        final int permission = mContext.checkCallingOrSelfPermission(
12250                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12251        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12252        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12253        // writer
12254        synchronized (mPackages) {
12255            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12256                    uid, userId)) {
12257                scheduleWritePackageRestrictionsLocked(userId);
12258            }
12259        }
12260    }
12261
12262    @Override
12263    public String getInstallerPackageName(String packageName) {
12264        // reader
12265        synchronized (mPackages) {
12266            return mSettings.getInstallerPackageNameLPr(packageName);
12267        }
12268    }
12269
12270    @Override
12271    public int getApplicationEnabledSetting(String packageName, int userId) {
12272        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12273        int uid = Binder.getCallingUid();
12274        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12275        // reader
12276        synchronized (mPackages) {
12277            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12278        }
12279    }
12280
12281    @Override
12282    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12283        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12284        int uid = Binder.getCallingUid();
12285        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12286        // reader
12287        synchronized (mPackages) {
12288            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12289        }
12290    }
12291
12292    @Override
12293    public void enterSafeMode() {
12294        enforceSystemOrRoot("Only the system can request entering safe mode");
12295
12296        if (!mSystemReady) {
12297            mSafeMode = true;
12298        }
12299    }
12300
12301    @Override
12302    public void systemReady() {
12303        mSystemReady = true;
12304
12305        // Read the compatibilty setting when the system is ready.
12306        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12307                mContext.getContentResolver(),
12308                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12309        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12310        if (DEBUG_SETTINGS) {
12311            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12312        }
12313
12314        synchronized (mPackages) {
12315            // Verify that all of the preferred activity components actually
12316            // exist.  It is possible for applications to be updated and at
12317            // that point remove a previously declared activity component that
12318            // had been set as a preferred activity.  We try to clean this up
12319            // the next time we encounter that preferred activity, but it is
12320            // possible for the user flow to never be able to return to that
12321            // situation so here we do a sanity check to make sure we haven't
12322            // left any junk around.
12323            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12324            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12325                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12326                removed.clear();
12327                for (PreferredActivity pa : pir.filterSet()) {
12328                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12329                        removed.add(pa);
12330                    }
12331                }
12332                if (removed.size() > 0) {
12333                    for (int r=0; r<removed.size(); r++) {
12334                        PreferredActivity pa = removed.get(r);
12335                        Slog.w(TAG, "Removing dangling preferred activity: "
12336                                + pa.mPref.mComponent);
12337                        pir.removeFilter(pa);
12338                    }
12339                    mSettings.writePackageRestrictionsLPr(
12340                            mSettings.mPreferredActivities.keyAt(i));
12341                }
12342            }
12343        }
12344        sUserManager.systemReady();
12345
12346        // Kick off any messages waiting for system ready
12347        if (mPostSystemReadyMessages != null) {
12348            for (Message msg : mPostSystemReadyMessages) {
12349                msg.sendToTarget();
12350            }
12351            mPostSystemReadyMessages = null;
12352        }
12353    }
12354
12355    @Override
12356    public boolean isSafeMode() {
12357        return mSafeMode;
12358    }
12359
12360    @Override
12361    public boolean hasSystemUidErrors() {
12362        return mHasSystemUidErrors;
12363    }
12364
12365    static String arrayToString(int[] array) {
12366        StringBuffer buf = new StringBuffer(128);
12367        buf.append('[');
12368        if (array != null) {
12369            for (int i=0; i<array.length; i++) {
12370                if (i > 0) buf.append(", ");
12371                buf.append(array[i]);
12372            }
12373        }
12374        buf.append(']');
12375        return buf.toString();
12376    }
12377
12378    static class DumpState {
12379        public static final int DUMP_LIBS = 1 << 0;
12380        public static final int DUMP_FEATURES = 1 << 1;
12381        public static final int DUMP_RESOLVERS = 1 << 2;
12382        public static final int DUMP_PERMISSIONS = 1 << 3;
12383        public static final int DUMP_PACKAGES = 1 << 4;
12384        public static final int DUMP_SHARED_USERS = 1 << 5;
12385        public static final int DUMP_MESSAGES = 1 << 6;
12386        public static final int DUMP_PROVIDERS = 1 << 7;
12387        public static final int DUMP_VERIFIERS = 1 << 8;
12388        public static final int DUMP_PREFERRED = 1 << 9;
12389        public static final int DUMP_PREFERRED_XML = 1 << 10;
12390        public static final int DUMP_KEYSETS = 1 << 11;
12391        public static final int DUMP_VERSION = 1 << 12;
12392        public static final int DUMP_INSTALLS = 1 << 13;
12393
12394        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12395
12396        private int mTypes;
12397
12398        private int mOptions;
12399
12400        private boolean mTitlePrinted;
12401
12402        private SharedUserSetting mSharedUser;
12403
12404        public boolean isDumping(int type) {
12405            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12406                return true;
12407            }
12408
12409            return (mTypes & type) != 0;
12410        }
12411
12412        public void setDump(int type) {
12413            mTypes |= type;
12414        }
12415
12416        public boolean isOptionEnabled(int option) {
12417            return (mOptions & option) != 0;
12418        }
12419
12420        public void setOptionEnabled(int option) {
12421            mOptions |= option;
12422        }
12423
12424        public boolean onTitlePrinted() {
12425            final boolean printed = mTitlePrinted;
12426            mTitlePrinted = true;
12427            return printed;
12428        }
12429
12430        public boolean getTitlePrinted() {
12431            return mTitlePrinted;
12432        }
12433
12434        public void setTitlePrinted(boolean enabled) {
12435            mTitlePrinted = enabled;
12436        }
12437
12438        public SharedUserSetting getSharedUser() {
12439            return mSharedUser;
12440        }
12441
12442        public void setSharedUser(SharedUserSetting user) {
12443            mSharedUser = user;
12444        }
12445    }
12446
12447    @Override
12448    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12449        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12450                != PackageManager.PERMISSION_GRANTED) {
12451            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12452                    + Binder.getCallingPid()
12453                    + ", uid=" + Binder.getCallingUid()
12454                    + " without permission "
12455                    + android.Manifest.permission.DUMP);
12456            return;
12457        }
12458
12459        DumpState dumpState = new DumpState();
12460        boolean fullPreferred = false;
12461        boolean checkin = false;
12462
12463        String packageName = null;
12464
12465        int opti = 0;
12466        while (opti < args.length) {
12467            String opt = args[opti];
12468            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12469                break;
12470            }
12471            opti++;
12472
12473            if ("-a".equals(opt)) {
12474                // Right now we only know how to print all.
12475            } else if ("-h".equals(opt)) {
12476                pw.println("Package manager dump options:");
12477                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12478                pw.println("    --checkin: dump for a checkin");
12479                pw.println("    -f: print details of intent filters");
12480                pw.println("    -h: print this help");
12481                pw.println("  cmd may be one of:");
12482                pw.println("    l[ibraries]: list known shared libraries");
12483                pw.println("    f[ibraries]: list device features");
12484                pw.println("    k[eysets]: print known keysets");
12485                pw.println("    r[esolvers]: dump intent resolvers");
12486                pw.println("    perm[issions]: dump permissions");
12487                pw.println("    pref[erred]: print preferred package settings");
12488                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12489                pw.println("    prov[iders]: dump content providers");
12490                pw.println("    p[ackages]: dump installed packages");
12491                pw.println("    s[hared-users]: dump shared user IDs");
12492                pw.println("    m[essages]: print collected runtime messages");
12493                pw.println("    v[erifiers]: print package verifier info");
12494                pw.println("    version: print database version info");
12495                pw.println("    write: write current settings now");
12496                pw.println("    <package.name>: info about given package");
12497                pw.println("    installs: details about install sessions");
12498                return;
12499            } else if ("--checkin".equals(opt)) {
12500                checkin = true;
12501            } else if ("-f".equals(opt)) {
12502                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12503            } else {
12504                pw.println("Unknown argument: " + opt + "; use -h for help");
12505            }
12506        }
12507
12508        // Is the caller requesting to dump a particular piece of data?
12509        if (opti < args.length) {
12510            String cmd = args[opti];
12511            opti++;
12512            // Is this a package name?
12513            if ("android".equals(cmd) || cmd.contains(".")) {
12514                packageName = cmd;
12515                // When dumping a single package, we always dump all of its
12516                // filter information since the amount of data will be reasonable.
12517                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12518            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12519                dumpState.setDump(DumpState.DUMP_LIBS);
12520            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12521                dumpState.setDump(DumpState.DUMP_FEATURES);
12522            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12523                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12524            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12525                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12526            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12527                dumpState.setDump(DumpState.DUMP_PREFERRED);
12528            } else if ("preferred-xml".equals(cmd)) {
12529                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12530                if (opti < args.length && "--full".equals(args[opti])) {
12531                    fullPreferred = true;
12532                    opti++;
12533                }
12534            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12535                dumpState.setDump(DumpState.DUMP_PACKAGES);
12536            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12537                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12538            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12539                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12540            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12541                dumpState.setDump(DumpState.DUMP_MESSAGES);
12542            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12543                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12544            } else if ("version".equals(cmd)) {
12545                dumpState.setDump(DumpState.DUMP_VERSION);
12546            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12547                dumpState.setDump(DumpState.DUMP_KEYSETS);
12548            } else if ("installs".equals(cmd)) {
12549                dumpState.setDump(DumpState.DUMP_INSTALLS);
12550            } else if ("write".equals(cmd)) {
12551                synchronized (mPackages) {
12552                    mSettings.writeLPr();
12553                    pw.println("Settings written.");
12554                    return;
12555                }
12556            }
12557        }
12558
12559        if (checkin) {
12560            pw.println("vers,1");
12561        }
12562
12563        // reader
12564        synchronized (mPackages) {
12565            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12566                if (!checkin) {
12567                    if (dumpState.onTitlePrinted())
12568                        pw.println();
12569                    pw.println("Database versions:");
12570                    pw.print("  SDK Version:");
12571                    pw.print(" internal=");
12572                    pw.print(mSettings.mInternalSdkPlatform);
12573                    pw.print(" external=");
12574                    pw.println(mSettings.mExternalSdkPlatform);
12575                    pw.print("  DB Version:");
12576                    pw.print(" internal=");
12577                    pw.print(mSettings.mInternalDatabaseVersion);
12578                    pw.print(" external=");
12579                    pw.println(mSettings.mExternalDatabaseVersion);
12580                }
12581            }
12582
12583            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12584                if (!checkin) {
12585                    if (dumpState.onTitlePrinted())
12586                        pw.println();
12587                    pw.println("Verifiers:");
12588                    pw.print("  Required: ");
12589                    pw.print(mRequiredVerifierPackage);
12590                    pw.print(" (uid=");
12591                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12592                    pw.println(")");
12593                } else if (mRequiredVerifierPackage != null) {
12594                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12595                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12596                }
12597            }
12598
12599            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12600                boolean printedHeader = false;
12601                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12602                while (it.hasNext()) {
12603                    String name = it.next();
12604                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12605                    if (!checkin) {
12606                        if (!printedHeader) {
12607                            if (dumpState.onTitlePrinted())
12608                                pw.println();
12609                            pw.println("Libraries:");
12610                            printedHeader = true;
12611                        }
12612                        pw.print("  ");
12613                    } else {
12614                        pw.print("lib,");
12615                    }
12616                    pw.print(name);
12617                    if (!checkin) {
12618                        pw.print(" -> ");
12619                    }
12620                    if (ent.path != null) {
12621                        if (!checkin) {
12622                            pw.print("(jar) ");
12623                            pw.print(ent.path);
12624                        } else {
12625                            pw.print(",jar,");
12626                            pw.print(ent.path);
12627                        }
12628                    } else {
12629                        if (!checkin) {
12630                            pw.print("(apk) ");
12631                            pw.print(ent.apk);
12632                        } else {
12633                            pw.print(",apk,");
12634                            pw.print(ent.apk);
12635                        }
12636                    }
12637                    pw.println();
12638                }
12639            }
12640
12641            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12642                if (dumpState.onTitlePrinted())
12643                    pw.println();
12644                if (!checkin) {
12645                    pw.println("Features:");
12646                }
12647                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12648                while (it.hasNext()) {
12649                    String name = it.next();
12650                    if (!checkin) {
12651                        pw.print("  ");
12652                    } else {
12653                        pw.print("feat,");
12654                    }
12655                    pw.println(name);
12656                }
12657            }
12658
12659            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12660                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12661                        : "Activity Resolver Table:", "  ", packageName,
12662                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12663                    dumpState.setTitlePrinted(true);
12664                }
12665                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12666                        : "Receiver Resolver Table:", "  ", packageName,
12667                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12668                    dumpState.setTitlePrinted(true);
12669                }
12670                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12671                        : "Service Resolver Table:", "  ", packageName,
12672                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12673                    dumpState.setTitlePrinted(true);
12674                }
12675                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12676                        : "Provider Resolver Table:", "  ", packageName,
12677                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12678                    dumpState.setTitlePrinted(true);
12679                }
12680            }
12681
12682            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12683                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12684                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12685                    int user = mSettings.mPreferredActivities.keyAt(i);
12686                    if (pir.dump(pw,
12687                            dumpState.getTitlePrinted()
12688                                ? "\nPreferred Activities User " + user + ":"
12689                                : "Preferred Activities User " + user + ":", "  ",
12690                            packageName, true, false)) {
12691                        dumpState.setTitlePrinted(true);
12692                    }
12693                }
12694            }
12695
12696            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12697                pw.flush();
12698                FileOutputStream fout = new FileOutputStream(fd);
12699                BufferedOutputStream str = new BufferedOutputStream(fout);
12700                XmlSerializer serializer = new FastXmlSerializer();
12701                try {
12702                    serializer.setOutput(str, "utf-8");
12703                    serializer.startDocument(null, true);
12704                    serializer.setFeature(
12705                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12706                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12707                    serializer.endDocument();
12708                    serializer.flush();
12709                } catch (IllegalArgumentException e) {
12710                    pw.println("Failed writing: " + e);
12711                } catch (IllegalStateException e) {
12712                    pw.println("Failed writing: " + e);
12713                } catch (IOException e) {
12714                    pw.println("Failed writing: " + e);
12715                }
12716            }
12717
12718            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12719                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12720                if (packageName == null) {
12721                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12722                        if (iperm == 0) {
12723                            if (dumpState.onTitlePrinted())
12724                                pw.println();
12725                            pw.println("AppOp Permissions:");
12726                        }
12727                        pw.print("  AppOp Permission ");
12728                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12729                        pw.println(":");
12730                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12731                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12732                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12733                        }
12734                    }
12735                }
12736            }
12737
12738            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12739                boolean printedSomething = false;
12740                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12741                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12742                        continue;
12743                    }
12744                    if (!printedSomething) {
12745                        if (dumpState.onTitlePrinted())
12746                            pw.println();
12747                        pw.println("Registered ContentProviders:");
12748                        printedSomething = true;
12749                    }
12750                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12751                    pw.print("    "); pw.println(p.toString());
12752                }
12753                printedSomething = false;
12754                for (Map.Entry<String, PackageParser.Provider> entry :
12755                        mProvidersByAuthority.entrySet()) {
12756                    PackageParser.Provider p = entry.getValue();
12757                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12758                        continue;
12759                    }
12760                    if (!printedSomething) {
12761                        if (dumpState.onTitlePrinted())
12762                            pw.println();
12763                        pw.println("ContentProvider Authorities:");
12764                        printedSomething = true;
12765                    }
12766                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12767                    pw.print("    "); pw.println(p.toString());
12768                    if (p.info != null && p.info.applicationInfo != null) {
12769                        final String appInfo = p.info.applicationInfo.toString();
12770                        pw.print("      applicationInfo="); pw.println(appInfo);
12771                    }
12772                }
12773            }
12774
12775            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12776                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12777            }
12778
12779            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12780                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12781            }
12782
12783            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12784                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12785            }
12786
12787            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12788                // XXX should handle packageName != null by dumping only install data that
12789                // the given package is involved with.
12790                if (dumpState.onTitlePrinted()) pw.println();
12791                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12792            }
12793
12794            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12795                if (dumpState.onTitlePrinted()) pw.println();
12796                mSettings.dumpReadMessagesLPr(pw, dumpState);
12797
12798                pw.println();
12799                pw.println("Package warning messages:");
12800                BufferedReader in = null;
12801                String line = null;
12802                try {
12803                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12804                    while ((line = in.readLine()) != null) {
12805                        if (line.contains("ignored: updated version")) continue;
12806                        pw.println(line);
12807                    }
12808                } catch (IOException ignored) {
12809                } finally {
12810                    IoUtils.closeQuietly(in);
12811                }
12812            }
12813
12814            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12815                BufferedReader in = null;
12816                String line = null;
12817                try {
12818                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12819                    while ((line = in.readLine()) != null) {
12820                        if (line.contains("ignored: updated version")) continue;
12821                        pw.print("msg,");
12822                        pw.println(line);
12823                    }
12824                } catch (IOException ignored) {
12825                } finally {
12826                    IoUtils.closeQuietly(in);
12827                }
12828            }
12829        }
12830    }
12831
12832    // ------- apps on sdcard specific code -------
12833    static final boolean DEBUG_SD_INSTALL = false;
12834
12835    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12836
12837    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12838
12839    private boolean mMediaMounted = false;
12840
12841    static String getEncryptKey() {
12842        try {
12843            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12844                    SD_ENCRYPTION_KEYSTORE_NAME);
12845            if (sdEncKey == null) {
12846                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12847                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12848                if (sdEncKey == null) {
12849                    Slog.e(TAG, "Failed to create encryption keys");
12850                    return null;
12851                }
12852            }
12853            return sdEncKey;
12854        } catch (NoSuchAlgorithmException nsae) {
12855            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12856            return null;
12857        } catch (IOException ioe) {
12858            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12859            return null;
12860        }
12861    }
12862
12863    /*
12864     * Update media status on PackageManager.
12865     */
12866    @Override
12867    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12868        int callingUid = Binder.getCallingUid();
12869        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12870            throw new SecurityException("Media status can only be updated by the system");
12871        }
12872        // reader; this apparently protects mMediaMounted, but should probably
12873        // be a different lock in that case.
12874        synchronized (mPackages) {
12875            Log.i(TAG, "Updating external media status from "
12876                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12877                    + (mediaStatus ? "mounted" : "unmounted"));
12878            if (DEBUG_SD_INSTALL)
12879                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12880                        + ", mMediaMounted=" + mMediaMounted);
12881            if (mediaStatus == mMediaMounted) {
12882                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12883                        : 0, -1);
12884                mHandler.sendMessage(msg);
12885                return;
12886            }
12887            mMediaMounted = mediaStatus;
12888        }
12889        // Queue up an async operation since the package installation may take a
12890        // little while.
12891        mHandler.post(new Runnable() {
12892            public void run() {
12893                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12894            }
12895        });
12896    }
12897
12898    /**
12899     * Called by MountService when the initial ASECs to scan are available.
12900     * Should block until all the ASEC containers are finished being scanned.
12901     */
12902    public void scanAvailableAsecs() {
12903        updateExternalMediaStatusInner(true, false, false);
12904        if (mShouldRestoreconData) {
12905            SELinuxMMAC.setRestoreconDone();
12906            mShouldRestoreconData = false;
12907        }
12908    }
12909
12910    /*
12911     * Collect information of applications on external media, map them against
12912     * existing containers and update information based on current mount status.
12913     * Please note that we always have to report status if reportStatus has been
12914     * set to true especially when unloading packages.
12915     */
12916    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12917            boolean externalStorage) {
12918        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12919        int[] uidArr = EmptyArray.INT;
12920
12921        final String[] list = PackageHelper.getSecureContainerList();
12922        if (ArrayUtils.isEmpty(list)) {
12923            Log.i(TAG, "No secure containers found");
12924        } else {
12925            // Process list of secure containers and categorize them
12926            // as active or stale based on their package internal state.
12927
12928            // reader
12929            synchronized (mPackages) {
12930                for (String cid : list) {
12931                    // Leave stages untouched for now; installer service owns them
12932                    if (PackageInstallerService.isStageName(cid)) continue;
12933
12934                    if (DEBUG_SD_INSTALL)
12935                        Log.i(TAG, "Processing container " + cid);
12936                    String pkgName = getAsecPackageName(cid);
12937                    if (pkgName == null) {
12938                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12939                        continue;
12940                    }
12941                    if (DEBUG_SD_INSTALL)
12942                        Log.i(TAG, "Looking for pkg : " + pkgName);
12943
12944                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12945                    if (ps == null) {
12946                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12947                        continue;
12948                    }
12949
12950                    /*
12951                     * Skip packages that are not external if we're unmounting
12952                     * external storage.
12953                     */
12954                    if (externalStorage && !isMounted && !isExternal(ps)) {
12955                        continue;
12956                    }
12957
12958                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12959                            getAppDexInstructionSets(ps), ps.isForwardLocked());
12960                    // The package status is changed only if the code path
12961                    // matches between settings and the container id.
12962                    if (ps.codePathString != null
12963                            && ps.codePathString.startsWith(args.getCodePath())) {
12964                        if (DEBUG_SD_INSTALL) {
12965                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12966                                    + " at code path: " + ps.codePathString);
12967                        }
12968
12969                        // We do have a valid package installed on sdcard
12970                        processCids.put(args, ps.codePathString);
12971                        final int uid = ps.appId;
12972                        if (uid != -1) {
12973                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12974                        }
12975                    } else {
12976                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12977                                + ps.codePathString);
12978                    }
12979                }
12980            }
12981
12982            Arrays.sort(uidArr);
12983        }
12984
12985        // Process packages with valid entries.
12986        if (isMounted) {
12987            if (DEBUG_SD_INSTALL)
12988                Log.i(TAG, "Loading packages");
12989            loadMediaPackages(processCids, uidArr);
12990            startCleaningPackages();
12991            mInstallerService.onSecureContainersAvailable();
12992        } else {
12993            if (DEBUG_SD_INSTALL)
12994                Log.i(TAG, "Unloading packages");
12995            unloadMediaPackages(processCids, uidArr, reportStatus);
12996        }
12997    }
12998
12999    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13000            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13001        int size = pkgList.size();
13002        if (size > 0) {
13003            // Send broadcasts here
13004            Bundle extras = new Bundle();
13005            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
13006                    .toArray(new String[size]));
13007            if (uidArr != null) {
13008                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13009            }
13010            if (replacing) {
13011                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13012            }
13013            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13014                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13015            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13016        }
13017    }
13018
13019   /*
13020     * Look at potentially valid container ids from processCids If package
13021     * information doesn't match the one on record or package scanning fails,
13022     * the cid is added to list of removeCids. We currently don't delete stale
13023     * containers.
13024     */
13025    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13026        ArrayList<String> pkgList = new ArrayList<String>();
13027        Set<AsecInstallArgs> keys = processCids.keySet();
13028
13029        for (AsecInstallArgs args : keys) {
13030            String codePath = processCids.get(args);
13031            if (DEBUG_SD_INSTALL)
13032                Log.i(TAG, "Loading container : " + args.cid);
13033            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13034            try {
13035                // Make sure there are no container errors first.
13036                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13037                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13038                            + " when installing from sdcard");
13039                    continue;
13040                }
13041                // Check code path here.
13042                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13043                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13044                            + " does not match one in settings " + codePath);
13045                    continue;
13046                }
13047                // Parse package
13048                int parseFlags = mDefParseFlags;
13049                if (args.isExternal()) {
13050                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
13051                }
13052                if (args.isFwdLocked()) {
13053                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13054                }
13055
13056                synchronized (mInstallLock) {
13057                    PackageParser.Package pkg = null;
13058                    try {
13059                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13060                    } catch (PackageManagerException e) {
13061                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13062                    }
13063                    // Scan the package
13064                    if (pkg != null) {
13065                        /*
13066                         * TODO why is the lock being held? doPostInstall is
13067                         * called in other places without the lock. This needs
13068                         * to be straightened out.
13069                         */
13070                        // writer
13071                        synchronized (mPackages) {
13072                            retCode = PackageManager.INSTALL_SUCCEEDED;
13073                            pkgList.add(pkg.packageName);
13074                            // Post process args
13075                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13076                                    pkg.applicationInfo.uid);
13077                        }
13078                    } else {
13079                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13080                    }
13081                }
13082
13083            } finally {
13084                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13085                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13086                }
13087            }
13088        }
13089        // writer
13090        synchronized (mPackages) {
13091            // If the platform SDK has changed since the last time we booted,
13092            // we need to re-grant app permission to catch any new ones that
13093            // appear. This is really a hack, and means that apps can in some
13094            // cases get permissions that the user didn't initially explicitly
13095            // allow... it would be nice to have some better way to handle
13096            // this situation.
13097            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13098            if (regrantPermissions)
13099                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13100                        + mSdkVersion + "; regranting permissions for external storage");
13101            mSettings.mExternalSdkPlatform = mSdkVersion;
13102
13103            // Make sure group IDs have been assigned, and any permission
13104            // changes in other apps are accounted for
13105            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13106                    | (regrantPermissions
13107                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13108                            : 0));
13109
13110            mSettings.updateExternalDatabaseVersion();
13111
13112            // can downgrade to reader
13113            // Persist settings
13114            mSettings.writeLPr();
13115        }
13116        // Send a broadcast to let everyone know we are done processing
13117        if (pkgList.size() > 0) {
13118            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13119        }
13120    }
13121
13122   /*
13123     * Utility method to unload a list of specified containers
13124     */
13125    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13126        // Just unmount all valid containers.
13127        for (AsecInstallArgs arg : cidArgs) {
13128            synchronized (mInstallLock) {
13129                arg.doPostDeleteLI(false);
13130           }
13131       }
13132   }
13133
13134    /*
13135     * Unload packages mounted on external media. This involves deleting package
13136     * data from internal structures, sending broadcasts about diabled packages,
13137     * gc'ing to free up references, unmounting all secure containers
13138     * corresponding to packages on external media, and posting a
13139     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13140     * that we always have to post this message if status has been requested no
13141     * matter what.
13142     */
13143    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13144            final boolean reportStatus) {
13145        if (DEBUG_SD_INSTALL)
13146            Log.i(TAG, "unloading media packages");
13147        ArrayList<String> pkgList = new ArrayList<String>();
13148        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13149        final Set<AsecInstallArgs> keys = processCids.keySet();
13150        for (AsecInstallArgs args : keys) {
13151            String pkgName = args.getPackageName();
13152            if (DEBUG_SD_INSTALL)
13153                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13154            // Delete package internally
13155            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13156            synchronized (mInstallLock) {
13157                boolean res = deletePackageLI(pkgName, null, false, null, null,
13158                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13159                if (res) {
13160                    pkgList.add(pkgName);
13161                } else {
13162                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13163                    failedList.add(args);
13164                }
13165            }
13166        }
13167
13168        // reader
13169        synchronized (mPackages) {
13170            // We didn't update the settings after removing each package;
13171            // write them now for all packages.
13172            mSettings.writeLPr();
13173        }
13174
13175        // We have to absolutely send UPDATED_MEDIA_STATUS only
13176        // after confirming that all the receivers processed the ordered
13177        // broadcast when packages get disabled, force a gc to clean things up.
13178        // and unload all the containers.
13179        if (pkgList.size() > 0) {
13180            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13181                    new IIntentReceiver.Stub() {
13182                public void performReceive(Intent intent, int resultCode, String data,
13183                        Bundle extras, boolean ordered, boolean sticky,
13184                        int sendingUser) throws RemoteException {
13185                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13186                            reportStatus ? 1 : 0, 1, keys);
13187                    mHandler.sendMessage(msg);
13188                }
13189            });
13190        } else {
13191            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13192                    keys);
13193            mHandler.sendMessage(msg);
13194        }
13195    }
13196
13197    /** Binder call */
13198    @Override
13199    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13200            final int flags) {
13201        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13202        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13203        int returnCode = PackageManager.MOVE_SUCCEEDED;
13204        int currInstallFlags = 0;
13205        int newInstallFlags = 0;
13206
13207        File codeFile = null;
13208        String installerPackageName = null;
13209        String packageAbiOverride = null;
13210
13211        // reader
13212        synchronized (mPackages) {
13213            final PackageParser.Package pkg = mPackages.get(packageName);
13214            final PackageSetting ps = mSettings.mPackages.get(packageName);
13215            if (pkg == null || ps == null) {
13216                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13217            } else {
13218                // Disable moving fwd locked apps and system packages
13219                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13220                    Slog.w(TAG, "Cannot move system application");
13221                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13222                } else if (pkg.mOperationPending) {
13223                    Slog.w(TAG, "Attempt to move package which has pending operations");
13224                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13225                } else {
13226                    // Find install location first
13227                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13228                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13229                        Slog.w(TAG, "Ambigous flags specified for move location.");
13230                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13231                    } else {
13232                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13233                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13234                        currInstallFlags = isExternal(pkg)
13235                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13236
13237                        if (newInstallFlags == currInstallFlags) {
13238                            Slog.w(TAG, "No move required. Trying to move to same location");
13239                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13240                        } else {
13241                            if (pkg.isForwardLocked()) {
13242                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13243                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13244                            }
13245                        }
13246                    }
13247                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13248                        pkg.mOperationPending = true;
13249                    }
13250                }
13251
13252                codeFile = new File(pkg.codePath);
13253                installerPackageName = ps.installerPackageName;
13254                packageAbiOverride = ps.cpuAbiOverrideString;
13255            }
13256        }
13257
13258        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13259            try {
13260                observer.packageMoved(packageName, returnCode);
13261            } catch (RemoteException ignored) {
13262            }
13263            return;
13264        }
13265
13266        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13267            @Override
13268            public void onUserActionRequired(Intent intent) throws RemoteException {
13269                throw new IllegalStateException();
13270            }
13271
13272            @Override
13273            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13274                    Bundle extras) throws RemoteException {
13275                Slog.d(TAG, "Install result for move: "
13276                        + PackageManager.installStatusToString(returnCode, msg));
13277
13278                // We usually have a new package now after the install, but if
13279                // we failed we need to clear the pending flag on the original
13280                // package object.
13281                synchronized (mPackages) {
13282                    final PackageParser.Package pkg = mPackages.get(packageName);
13283                    if (pkg != null) {
13284                        pkg.mOperationPending = false;
13285                    }
13286                }
13287
13288                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13289                switch (status) {
13290                    case PackageInstaller.STATUS_SUCCESS:
13291                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13292                        break;
13293                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13294                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13295                        break;
13296                    default:
13297                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13298                        break;
13299                }
13300            }
13301        };
13302
13303        // Treat a move like reinstalling an existing app, which ensures that we
13304        // process everythign uniformly, like unpacking native libraries.
13305        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13306
13307        final Message msg = mHandler.obtainMessage(INIT_COPY);
13308        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13309        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13310                installerPackageName, null, user, packageAbiOverride);
13311        mHandler.sendMessage(msg);
13312    }
13313
13314    @Override
13315    public boolean setInstallLocation(int loc) {
13316        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13317                null);
13318        if (getInstallLocation() == loc) {
13319            return true;
13320        }
13321        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13322                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13323            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13324                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13325            return true;
13326        }
13327        return false;
13328   }
13329
13330    @Override
13331    public int getInstallLocation() {
13332        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13333                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13334                PackageHelper.APP_INSTALL_AUTO);
13335    }
13336
13337    /** Called by UserManagerService */
13338    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13339        mDirtyUsers.remove(userHandle);
13340        mSettings.removeUserLPw(userHandle);
13341        mPendingBroadcasts.remove(userHandle);
13342        if (mInstaller != null) {
13343            // Technically, we shouldn't be doing this with the package lock
13344            // held.  However, this is very rare, and there is already so much
13345            // other disk I/O going on, that we'll let it slide for now.
13346            mInstaller.removeUserDataDirs(userHandle);
13347        }
13348        mUserNeedsBadging.delete(userHandle);
13349        removeUnusedPackagesLILPw(userManager, userHandle);
13350    }
13351
13352    /**
13353     * We're removing userHandle and would like to remove any downloaded packages
13354     * that are no longer in use by any other user.
13355     * @param userHandle the user being removed
13356     */
13357    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13358        final boolean DEBUG_CLEAN_APKS = false;
13359        int [] users = userManager.getUserIdsLPr();
13360        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13361        while (psit.hasNext()) {
13362            PackageSetting ps = psit.next();
13363            if (ps.pkg == null) {
13364                continue;
13365            }
13366            final String packageName = ps.pkg.packageName;
13367            // Skip over if system app
13368            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13369                continue;
13370            }
13371            if (DEBUG_CLEAN_APKS) {
13372                Slog.i(TAG, "Checking package " + packageName);
13373            }
13374            boolean keep = false;
13375            for (int i = 0; i < users.length; i++) {
13376                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13377                    keep = true;
13378                    if (DEBUG_CLEAN_APKS) {
13379                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13380                                + users[i]);
13381                    }
13382                    break;
13383                }
13384            }
13385            if (!keep) {
13386                if (DEBUG_CLEAN_APKS) {
13387                    Slog.i(TAG, "  Removing package " + packageName);
13388                }
13389                mHandler.post(new Runnable() {
13390                    public void run() {
13391                        deletePackageX(packageName, userHandle, 0);
13392                    } //end run
13393                });
13394            }
13395        }
13396    }
13397
13398    /** Called by UserManagerService */
13399    void createNewUserLILPw(int userHandle, File path) {
13400        if (mInstaller != null) {
13401            mInstaller.createUserConfig(userHandle);
13402            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13403        }
13404    }
13405
13406    void newUserCreatedLILPw(int userHandle) {
13407        // Adding a user requires updating runtime permissions for system apps.
13408        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
13409    }
13410
13411    @Override
13412    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13413        mContext.enforceCallingOrSelfPermission(
13414                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13415                "Only package verification agents can read the verifier device identity");
13416
13417        synchronized (mPackages) {
13418            return mSettings.getVerifierDeviceIdentityLPw();
13419        }
13420    }
13421
13422    @Override
13423    public void setPermissionEnforced(String permission, boolean enforced) {
13424        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13425        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13426            synchronized (mPackages) {
13427                if (mSettings.mReadExternalStorageEnforced == null
13428                        || mSettings.mReadExternalStorageEnforced != enforced) {
13429                    mSettings.mReadExternalStorageEnforced = enforced;
13430                    mSettings.writeLPr();
13431                }
13432            }
13433            // kill any non-foreground processes so we restart them and
13434            // grant/revoke the GID.
13435            final IActivityManager am = ActivityManagerNative.getDefault();
13436            if (am != null) {
13437                final long token = Binder.clearCallingIdentity();
13438                try {
13439                    am.killProcessesBelowForeground("setPermissionEnforcement");
13440                } catch (RemoteException e) {
13441                } finally {
13442                    Binder.restoreCallingIdentity(token);
13443                }
13444            }
13445        } else {
13446            throw new IllegalArgumentException("No selective enforcement for " + permission);
13447        }
13448    }
13449
13450    @Override
13451    @Deprecated
13452    public boolean isPermissionEnforced(String permission) {
13453        return true;
13454    }
13455
13456    @Override
13457    public boolean isStorageLow() {
13458        final long token = Binder.clearCallingIdentity();
13459        try {
13460            final DeviceStorageMonitorInternal
13461                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13462            if (dsm != null) {
13463                return dsm.isMemoryLow();
13464            } else {
13465                return false;
13466            }
13467        } finally {
13468            Binder.restoreCallingIdentity(token);
13469        }
13470    }
13471
13472    @Override
13473    public IPackageInstaller getPackageInstaller() {
13474        return mInstallerService;
13475    }
13476
13477    private boolean userNeedsBadging(int userId) {
13478        int index = mUserNeedsBadging.indexOfKey(userId);
13479        if (index < 0) {
13480            final UserInfo userInfo;
13481            final long token = Binder.clearCallingIdentity();
13482            try {
13483                userInfo = sUserManager.getUserInfo(userId);
13484            } finally {
13485                Binder.restoreCallingIdentity(token);
13486            }
13487            final boolean b;
13488            if (userInfo != null && userInfo.isManagedProfile()) {
13489                b = true;
13490            } else {
13491                b = false;
13492            }
13493            mUserNeedsBadging.put(userId, b);
13494            return b;
13495        }
13496        return mUserNeedsBadging.valueAt(index);
13497    }
13498
13499    @Override
13500    public KeySet getKeySetByAlias(String packageName, String alias) {
13501        if (packageName == null || alias == null) {
13502            return null;
13503        }
13504        synchronized(mPackages) {
13505            final PackageParser.Package pkg = mPackages.get(packageName);
13506            if (pkg == null) {
13507                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13508                throw new IllegalArgumentException("Unknown package: " + packageName);
13509            }
13510            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13511            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13512        }
13513    }
13514
13515    @Override
13516    public KeySet getSigningKeySet(String packageName) {
13517        if (packageName == null) {
13518            return null;
13519        }
13520        synchronized(mPackages) {
13521            final PackageParser.Package pkg = mPackages.get(packageName);
13522            if (pkg == null) {
13523                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13524                throw new IllegalArgumentException("Unknown package: " + packageName);
13525            }
13526            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13527                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13528                throw new SecurityException("May not access signing KeySet of other apps.");
13529            }
13530            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13531            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13532        }
13533    }
13534
13535    @Override
13536    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13537        if (packageName == null || ks == null) {
13538            return false;
13539        }
13540        synchronized(mPackages) {
13541            final PackageParser.Package pkg = mPackages.get(packageName);
13542            if (pkg == null) {
13543                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13544                throw new IllegalArgumentException("Unknown package: " + packageName);
13545            }
13546            IBinder ksh = ks.getToken();
13547            if (ksh instanceof KeySetHandle) {
13548                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13549                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13550            }
13551            return false;
13552        }
13553    }
13554
13555    @Override
13556    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13557        if (packageName == null || ks == null) {
13558            return false;
13559        }
13560        synchronized(mPackages) {
13561            final PackageParser.Package pkg = mPackages.get(packageName);
13562            if (pkg == null) {
13563                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13564                throw new IllegalArgumentException("Unknown package: " + packageName);
13565            }
13566            IBinder ksh = ks.getToken();
13567            if (ksh instanceof KeySetHandle) {
13568                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13569                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13570            }
13571            return false;
13572        }
13573    }
13574
13575    public void getUsageStatsIfNoPackageUsageInfo() {
13576        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13577            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13578            if (usm == null) {
13579                throw new IllegalStateException("UsageStatsManager must be initialized");
13580            }
13581            long now = System.currentTimeMillis();
13582            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13583            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13584                String packageName = entry.getKey();
13585                PackageParser.Package pkg = mPackages.get(packageName);
13586                if (pkg == null) {
13587                    continue;
13588                }
13589                UsageStats usage = entry.getValue();
13590                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13591                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13592            }
13593        }
13594    }
13595
13596    /**
13597     * Check and throw if the given before/after packages would be considered a
13598     * downgrade.
13599     */
13600    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13601            throws PackageManagerException {
13602        if (after.versionCode < before.mVersionCode) {
13603            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13604                    "Update version code " + after.versionCode + " is older than current "
13605                    + before.mVersionCode);
13606        } else if (after.versionCode == before.mVersionCode) {
13607            if (after.baseRevisionCode < before.baseRevisionCode) {
13608                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13609                        "Update base revision code " + after.baseRevisionCode
13610                        + " is older than current " + before.baseRevisionCode);
13611            }
13612
13613            if (!ArrayUtils.isEmpty(after.splitNames)) {
13614                for (int i = 0; i < after.splitNames.length; i++) {
13615                    final String splitName = after.splitNames[i];
13616                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13617                    if (j != -1) {
13618                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13619                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13620                                    "Update split " + splitName + " revision code "
13621                                    + after.splitRevisionCodes[i] + " is older than current "
13622                                    + before.splitRevisionCodes[j]);
13623                        }
13624                    }
13625                }
13626            }
13627        }
13628    }
13629}
13630