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