PackageManagerService.java revision 2a880312086147577e1e814bda6985fa97fb343b
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_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.PACKAGE_INFO_GID;
59import static android.os.Process.SYSTEM_UID;
60import static android.system.OsConstants.O_CREAT;
61import static android.system.OsConstants.O_RDWR;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
66import static com.android.internal.util.ArrayUtils.appendInt;
67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
72
73import android.Manifest;
74import android.app.ActivityManager;
75import android.app.ActivityManagerNative;
76import android.app.AppGlobals;
77import android.app.IActivityManager;
78import android.app.admin.IDevicePolicyManager;
79import android.app.backup.IBackupManager;
80import android.app.usage.UsageStats;
81import android.app.usage.UsageStatsManager;
82import android.content.BroadcastReceiver;
83import android.content.ComponentName;
84import android.content.Context;
85import android.content.IIntentReceiver;
86import android.content.Intent;
87import android.content.IntentFilter;
88import android.content.IntentSender;
89import android.content.IntentSender.SendIntentException;
90import android.content.ServiceConnection;
91import android.content.pm.ActivityInfo;
92import android.content.pm.ApplicationInfo;
93import android.content.pm.FeatureInfo;
94import android.content.pm.IOnPermissionsChangeListener;
95import android.content.pm.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.IPackagesProvider;
104import android.content.pm.InstrumentationInfo;
105import android.content.pm.IntentFilterVerificationInfo;
106import android.content.pm.KeySet;
107import android.content.pm.ManifestDigest;
108import android.content.pm.PackageCleanItem;
109import android.content.pm.PackageInfo;
110import android.content.pm.PackageInfoLite;
111import android.content.pm.PackageInstaller;
112import android.content.pm.PackageManager;
113import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
114import android.content.pm.PackageManagerInternal;
115import android.content.pm.PackageParser;
116import android.content.pm.PackageParser.ActivityIntentInfo;
117import android.content.pm.PackageParser.PackageLite;
118import android.content.pm.PackageParser.PackageParserException;
119import android.content.pm.PackageStats;
120import android.content.pm.PackageUserState;
121import android.content.pm.ParceledListSlice;
122import android.content.pm.PermissionGroupInfo;
123import android.content.pm.PermissionInfo;
124import android.content.pm.ProviderInfo;
125import android.content.pm.ResolveInfo;
126import android.content.pm.ServiceInfo;
127import android.content.pm.Signature;
128import android.content.pm.UserInfo;
129import android.content.pm.VerificationParams;
130import android.content.pm.VerifierDeviceIdentity;
131import android.content.pm.VerifierInfo;
132import android.content.res.Resources;
133import android.hardware.display.DisplayManager;
134import android.net.Uri;
135import android.os.Binder;
136import android.os.Build;
137import android.os.Bundle;
138import android.os.Debug;
139import android.os.Environment;
140import android.os.Environment.UserEnvironment;
141import android.os.FileUtils;
142import android.os.Handler;
143import android.os.IBinder;
144import android.os.Looper;
145import android.os.Message;
146import android.os.Parcel;
147import android.os.ParcelFileDescriptor;
148import android.os.Process;
149import android.os.RemoteCallbackList;
150import android.os.RemoteException;
151import android.os.SELinux;
152import android.os.ServiceManager;
153import android.os.SystemClock;
154import android.os.SystemProperties;
155import android.os.UserHandle;
156import android.os.UserManager;
157import android.os.storage.IMountService;
158import android.os.storage.StorageEventListener;
159import android.os.storage.StorageManager;
160import android.os.storage.VolumeInfo;
161import android.os.storage.VolumeRecord;
162import android.security.KeyStore;
163import android.security.SystemKeyStore;
164import android.system.ErrnoException;
165import android.system.Os;
166import android.system.StructStat;
167import android.text.TextUtils;
168import android.text.format.DateUtils;
169import android.util.ArrayMap;
170import android.util.ArraySet;
171import android.util.AtomicFile;
172import android.util.DisplayMetrics;
173import android.util.EventLog;
174import android.util.ExceptionUtils;
175import android.util.Log;
176import android.util.LogPrinter;
177import android.util.MathUtils;
178import android.util.PrintStreamPrinter;
179import android.util.Slog;
180import android.util.SparseArray;
181import android.util.SparseBooleanArray;
182import android.util.SparseIntArray;
183import android.util.Xml;
184import android.view.Display;
185
186import dalvik.system.DexFile;
187import dalvik.system.VMRuntime;
188
189import libcore.io.IoUtils;
190import libcore.util.EmptyArray;
191
192import com.android.internal.R;
193import com.android.internal.app.IMediaContainerService;
194import com.android.internal.app.ResolverActivity;
195import com.android.internal.content.NativeLibraryHelper;
196import com.android.internal.content.PackageHelper;
197import com.android.internal.os.IParcelFileDescriptorFactory;
198import com.android.internal.os.SomeArgs;
199import com.android.internal.util.ArrayUtils;
200import com.android.internal.util.FastPrintWriter;
201import com.android.internal.util.FastXmlSerializer;
202import com.android.internal.util.IndentingPrintWriter;
203import com.android.internal.util.Preconditions;
204import com.android.server.EventLogTags;
205import com.android.server.FgThread;
206import com.android.server.IntentResolver;
207import com.android.server.LocalServices;
208import com.android.server.ServiceThread;
209import com.android.server.SystemConfig;
210import com.android.server.Watchdog;
211import com.android.server.pm.Settings.DatabaseVersion;
212import com.android.server.pm.PermissionsState.PermissionState;
213import com.android.server.storage.DeviceStorageMonitorInternal;
214
215import org.xmlpull.v1.XmlPullParser;
216import org.xmlpull.v1.XmlSerializer;
217
218import java.io.BufferedInputStream;
219import java.io.BufferedOutputStream;
220import java.io.BufferedReader;
221import java.io.ByteArrayInputStream;
222import java.io.ByteArrayOutputStream;
223import java.io.File;
224import java.io.FileDescriptor;
225import java.io.FileNotFoundException;
226import java.io.FileOutputStream;
227import java.io.FileReader;
228import java.io.FilenameFilter;
229import java.io.IOException;
230import java.io.InputStream;
231import java.io.PrintWriter;
232import java.nio.charset.StandardCharsets;
233import java.security.NoSuchAlgorithmException;
234import java.security.PublicKey;
235import java.security.cert.CertificateEncodingException;
236import java.security.cert.CertificateException;
237import java.text.SimpleDateFormat;
238import java.util.ArrayList;
239import java.util.Arrays;
240import java.util.Collection;
241import java.util.Collections;
242import java.util.Comparator;
243import java.util.Date;
244import java.util.Iterator;
245import java.util.List;
246import java.util.Map;
247import java.util.Objects;
248import java.util.Set;
249import java.util.concurrent.CountDownLatch;
250import java.util.concurrent.TimeUnit;
251import java.util.concurrent.atomic.AtomicBoolean;
252import java.util.concurrent.atomic.AtomicInteger;
253import java.util.concurrent.atomic.AtomicLong;
254
255/**
256 * Keep track of all those .apks everywhere.
257 *
258 * This is very central to the platform's security; please run the unit
259 * tests whenever making modifications here:
260 *
261mmm frameworks/base/tests/AndroidTests
262adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
263adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
264 *
265 * {@hide}
266 */
267public class PackageManagerService extends IPackageManager.Stub {
268    static final String TAG = "PackageManager";
269    static final boolean DEBUG_SETTINGS = false;
270    static final boolean DEBUG_PREFERRED = false;
271    static final boolean DEBUG_UPGRADE = false;
272    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
273    private static final boolean DEBUG_BACKUP = true;
274    private static final boolean DEBUG_INSTALL = false;
275    private static final boolean DEBUG_REMOVE = false;
276    private static final boolean DEBUG_BROADCASTS = false;
277    private static final boolean DEBUG_SHOW_INFO = false;
278    private static final boolean DEBUG_PACKAGE_INFO = false;
279    private static final boolean DEBUG_INTENT_MATCHING = false;
280    private static final boolean DEBUG_PACKAGE_SCANNING = false;
281    private static final boolean DEBUG_VERIFY = false;
282    private static final boolean DEBUG_DEXOPT = false;
283    private static final boolean DEBUG_ABI_SELECTION = false;
284
285    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
286
287    private static final int RADIO_UID = Process.PHONE_UID;
288    private static final int LOG_UID = Process.LOG_UID;
289    private static final int NFC_UID = Process.NFC_UID;
290    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
291    private static final int SHELL_UID = Process.SHELL_UID;
292
293    // Cap the size of permission trees that 3rd party apps can define
294    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
295
296    // Suffix used during package installation when copying/moving
297    // package apks to install directory.
298    private static final String INSTALL_PACKAGE_SUFFIX = "-";
299
300    static final int SCAN_NO_DEX = 1<<1;
301    static final int SCAN_FORCE_DEX = 1<<2;
302    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
303    static final int SCAN_NEW_INSTALL = 1<<4;
304    static final int SCAN_NO_PATHS = 1<<5;
305    static final int SCAN_UPDATE_TIME = 1<<6;
306    static final int SCAN_DEFER_DEX = 1<<7;
307    static final int SCAN_BOOTING = 1<<8;
308    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
309    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
310    static final int SCAN_REQUIRE_KNOWN = 1<<12;
311    static final int SCAN_MOVE = 1<<13;
312
313    static final int REMOVE_CHATTY = 1<<16;
314
315    private static final int[] EMPTY_INT_ARRAY = new int[0];
316
317    /**
318     * Timeout (in milliseconds) after which the watchdog should declare that
319     * our handler thread is wedged.  The usual default for such things is one
320     * minute but we sometimes do very lengthy I/O operations on this thread,
321     * such as installing multi-gigabyte applications, so ours needs to be longer.
322     */
323    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
324
325    /**
326     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
327     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
328     * settings entry if available, otherwise we use the hardcoded default.  If it's been
329     * more than this long since the last fstrim, we force one during the boot sequence.
330     *
331     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
332     * one gets run at the next available charging+idle time.  This final mandatory
333     * no-fstrim check kicks in only of the other scheduling criteria is never met.
334     */
335    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
336
337    /**
338     * Whether verification is enabled by default.
339     */
340    private static final boolean DEFAULT_VERIFY_ENABLE = true;
341
342    /**
343     * The default maximum time to wait for the verification agent to return in
344     * milliseconds.
345     */
346    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
347
348    /**
349     * The default response for package verification timeout.
350     *
351     * This can be either PackageManager.VERIFICATION_ALLOW or
352     * PackageManager.VERIFICATION_REJECT.
353     */
354    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
355
356    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
357
358    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
359            DEFAULT_CONTAINER_PACKAGE,
360            "com.android.defcontainer.DefaultContainerService");
361
362    private static final String KILL_APP_REASON_GIDS_CHANGED =
363            "permission grant or revoke changed gids";
364
365    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
366            "permissions revoked";
367
368    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
369
370    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
371
372    /** Permission grant: not grant the permission. */
373    private static final int GRANT_DENIED = 1;
374
375    /** Permission grant: grant the permission as an install permission. */
376    private static final int GRANT_INSTALL = 2;
377
378    /** Permission grant: grant the permission as an install permission for a legacy app. */
379    private static final int GRANT_INSTALL_LEGACY = 3;
380
381    /** Permission grant: grant the permission as a runtime one. */
382    private static final int GRANT_RUNTIME = 4;
383
384    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
385    private static final int GRANT_UPGRADE = 5;
386
387    final ServiceThread mHandlerThread;
388
389    final PackageHandler mHandler;
390
391    /**
392     * Messages for {@link #mHandler} that need to wait for system ready before
393     * being dispatched.
394     */
395    private ArrayList<Message> mPostSystemReadyMessages;
396
397    final int mSdkVersion = Build.VERSION.SDK_INT;
398
399    final Context mContext;
400    final boolean mFactoryTest;
401    final boolean mOnlyCore;
402    final boolean mLazyDexOpt;
403    final long mDexOptLRUThresholdInMills;
404    final DisplayMetrics mMetrics;
405    final int mDefParseFlags;
406    final String[] mSeparateProcesses;
407    final boolean mIsUpgrade;
408
409    // This is where all application persistent data goes.
410    final File mAppDataDir;
411
412    // This is where all application persistent data goes for secondary users.
413    final File mUserAppDataDir;
414
415    /** The location for ASEC container files on internal storage. */
416    final String mAsecInternalPath;
417
418    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
419    // LOCK HELD.  Can be called with mInstallLock held.
420    final Installer mInstaller;
421
422    /** Directory where installed third-party apps stored */
423    final File mAppInstallDir;
424
425    /**
426     * Directory to which applications installed internally have their
427     * 32 bit native libraries copied.
428     */
429    private File mAppLib32InstallDir;
430
431    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
432    // apps.
433    final File mDrmAppPrivateInstallDir;
434
435    // ----------------------------------------------------------------
436
437    // Lock for state used when installing and doing other long running
438    // operations.  Methods that must be called with this lock held have
439    // the suffix "LI".
440    final Object mInstallLock = new Object();
441
442    // ----------------------------------------------------------------
443
444    // Keys are String (package name), values are Package.  This also serves
445    // as the lock for the global state.  Methods that must be called with
446    // this lock held have the prefix "LP".
447    final ArrayMap<String, PackageParser.Package> mPackages =
448            new ArrayMap<String, PackageParser.Package>();
449
450    // Tracks available target package names -> overlay package paths.
451    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
452        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
453
454    final Settings mSettings;
455    boolean mRestoredSettings;
456
457    // System configuration read by SystemConfig.
458    final int[] mGlobalGids;
459    final SparseArray<ArraySet<String>> mSystemPermissions;
460    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
461
462    // If mac_permissions.xml was found for seinfo labeling.
463    boolean mFoundPolicyFile;
464
465    // If a recursive restorecon of /data/data/<pkg> is needed.
466    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
467
468    public static final class SharedLibraryEntry {
469        public final String path;
470        public final String apk;
471
472        SharedLibraryEntry(String _path, String _apk) {
473            path = _path;
474            apk = _apk;
475        }
476    }
477
478    // Currently known shared libraries.
479    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
480            new ArrayMap<String, SharedLibraryEntry>();
481
482    // All available activities, for your resolving pleasure.
483    final ActivityIntentResolver mActivities =
484            new ActivityIntentResolver();
485
486    // All available receivers, for your resolving pleasure.
487    final ActivityIntentResolver mReceivers =
488            new ActivityIntentResolver();
489
490    // All available services, for your resolving pleasure.
491    final ServiceIntentResolver mServices = new ServiceIntentResolver();
492
493    // All available providers, for your resolving pleasure.
494    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
495
496    // Mapping from provider base names (first directory in content URI codePath)
497    // to the provider information.
498    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
499            new ArrayMap<String, PackageParser.Provider>();
500
501    // Mapping from instrumentation class names to info about them.
502    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
503            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
504
505    // Mapping from permission names to info about them.
506    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
507            new ArrayMap<String, PackageParser.PermissionGroup>();
508
509    // Packages whose data we have transfered into another package, thus
510    // should no longer exist.
511    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
512
513    // Broadcast actions that are only available to the system.
514    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
515
516    /** List of packages waiting for verification. */
517    final SparseArray<PackageVerificationState> mPendingVerification
518            = new SparseArray<PackageVerificationState>();
519
520    /** Set of packages associated with each app op permission. */
521    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
522
523    final PackageInstallerService mInstallerService;
524
525    private final PackageDexOptimizer mPackageDexOptimizer;
526
527    private AtomicInteger mNextMoveId = new AtomicInteger();
528    private final MoveCallbacks mMoveCallbacks;
529
530    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
531
532    // Cache of users who need badging.
533    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
534
535    /** Token for keys in mPendingVerification. */
536    private int mPendingVerificationToken = 0;
537
538    volatile boolean mSystemReady;
539    volatile boolean mSafeMode;
540    volatile boolean mHasSystemUidErrors;
541
542    ApplicationInfo mAndroidApplication;
543    final ActivityInfo mResolveActivity = new ActivityInfo();
544    final ResolveInfo mResolveInfo = new ResolveInfo();
545    ComponentName mResolveComponentName;
546    PackageParser.Package mPlatformPackage;
547    ComponentName mCustomResolverComponentName;
548
549    boolean mResolverReplaced = false;
550
551    private final ComponentName mIntentFilterVerifierComponent;
552    private int mIntentFilterVerificationToken = 0;
553
554    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
555            = new SparseArray<IntentFilterVerificationState>();
556
557    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
558            new DefaultPermissionGrantPolicy(this);
559
560    private interface IntentFilterVerifier<T extends IntentFilter> {
561        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
562                                               T filter, String packageName);
563        void startVerifications(int userId);
564        void receiveVerificationResponse(int verificationId);
565    }
566
567    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
568        private Context mContext;
569        private ComponentName mIntentFilterVerifierComponent;
570        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
571
572        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
573            mContext = context;
574            mIntentFilterVerifierComponent = verifierComponent;
575        }
576
577        private String getDefaultScheme() {
578            return IntentFilter.SCHEME_HTTPS;
579        }
580
581        @Override
582        public void startVerifications(int userId) {
583            // Launch verifications requests
584            int count = mCurrentIntentFilterVerifications.size();
585            for (int n=0; n<count; n++) {
586                int verificationId = mCurrentIntentFilterVerifications.get(n);
587                final IntentFilterVerificationState ivs =
588                        mIntentFilterVerificationStates.get(verificationId);
589
590                String packageName = ivs.getPackageName();
591
592                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
593                final int filterCount = filters.size();
594                ArraySet<String> domainsSet = new ArraySet<>();
595                for (int m=0; m<filterCount; m++) {
596                    PackageParser.ActivityIntentInfo filter = filters.get(m);
597                    domainsSet.addAll(filter.getHostsList());
598                }
599                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
600                synchronized (mPackages) {
601                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
602                            packageName, domainsList) != null) {
603                        scheduleWriteSettingsLocked();
604                    }
605                }
606                sendVerificationRequest(userId, verificationId, ivs);
607            }
608            mCurrentIntentFilterVerifications.clear();
609        }
610
611        private void sendVerificationRequest(int userId, int verificationId,
612                IntentFilterVerificationState ivs) {
613
614            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
615            verificationIntent.putExtra(
616                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
617                    verificationId);
618            verificationIntent.putExtra(
619                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
620                    getDefaultScheme());
621            verificationIntent.putExtra(
622                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
623                    ivs.getHostsString());
624            verificationIntent.putExtra(
625                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
626                    ivs.getPackageName());
627            verificationIntent.setComponent(mIntentFilterVerifierComponent);
628            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
629
630            UserHandle user = new UserHandle(userId);
631            mContext.sendBroadcastAsUser(verificationIntent, user);
632            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
633                    "Sending IntenFilter verification broadcast");
634        }
635
636        public void receiveVerificationResponse(int verificationId) {
637            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
638
639            final boolean verified = ivs.isVerified();
640
641            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
642            final int count = filters.size();
643            for (int n=0; n<count; n++) {
644                PackageParser.ActivityIntentInfo filter = filters.get(n);
645                filter.setVerified(verified);
646
647                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
648                        + " verified with result:" + verified + " and hosts:"
649                        + ivs.getHostsString());
650            }
651
652            mIntentFilterVerificationStates.remove(verificationId);
653
654            final String packageName = ivs.getPackageName();
655            IntentFilterVerificationInfo ivi = null;
656
657            synchronized (mPackages) {
658                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
659            }
660            if (ivi == null) {
661                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
662                        + verificationId + " packageName:" + packageName);
663                return;
664            }
665            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
666                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
667
668            synchronized (mPackages) {
669                if (verified) {
670                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
671                } else {
672                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
673                }
674                scheduleWriteSettingsLocked();
675
676                final int userId = ivs.getUserId();
677                if (userId != UserHandle.USER_ALL) {
678                    final int userStatus =
679                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
680
681                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
682                    boolean needUpdate = false;
683
684                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
685                    // already been set by the User thru the Disambiguation dialog
686                    switch (userStatus) {
687                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
688                            if (verified) {
689                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
690                            } else {
691                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
692                            }
693                            needUpdate = true;
694                            break;
695
696                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
697                            if (verified) {
698                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
699                                needUpdate = true;
700                            }
701                            break;
702
703                        default:
704                            // Nothing to do
705                    }
706
707                    if (needUpdate) {
708                        mSettings.updateIntentFilterVerificationStatusLPw(
709                                packageName, updatedStatus, userId);
710                        scheduleWritePackageRestrictionsLocked(userId);
711                    }
712                }
713            }
714        }
715
716        @Override
717        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
718                    ActivityIntentInfo filter, String packageName) {
719            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
720                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
721                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
722                        "IntentFilter does not contain HTTP nor HTTPS data scheme");
723                return false;
724            }
725            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
726            if (ivs == null) {
727                ivs = createDomainVerificationState(verifierId, userId, verificationId,
728                        packageName);
729            }
730            if (!hasValidDomains(filter)) {
731                return false;
732            }
733            ivs.addFilter(filter);
734            return true;
735        }
736
737        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
738                int userId, int verificationId, String packageName) {
739            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
740                    verifierId, userId, packageName);
741            ivs.setPendingState();
742            synchronized (mPackages) {
743                mIntentFilterVerificationStates.append(verificationId, ivs);
744                mCurrentIntentFilterVerifications.add(verificationId);
745            }
746            return ivs;
747        }
748    }
749
750    private static boolean hasValidDomains(ActivityIntentInfo filter) {
751        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
752                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
753        if (!hasHTTPorHTTPS) {
754            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
755                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
756            return false;
757        }
758        return true;
759    }
760
761    private IntentFilterVerifier mIntentFilterVerifier;
762
763    // Set of pending broadcasts for aggregating enable/disable of components.
764    static class PendingPackageBroadcasts {
765        // for each user id, a map of <package name -> components within that package>
766        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
767
768        public PendingPackageBroadcasts() {
769            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
770        }
771
772        public ArrayList<String> get(int userId, String packageName) {
773            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
774            return packages.get(packageName);
775        }
776
777        public void put(int userId, String packageName, ArrayList<String> components) {
778            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
779            packages.put(packageName, components);
780        }
781
782        public void remove(int userId, String packageName) {
783            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
784            if (packages != null) {
785                packages.remove(packageName);
786            }
787        }
788
789        public void remove(int userId) {
790            mUidMap.remove(userId);
791        }
792
793        public int userIdCount() {
794            return mUidMap.size();
795        }
796
797        public int userIdAt(int n) {
798            return mUidMap.keyAt(n);
799        }
800
801        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
802            return mUidMap.get(userId);
803        }
804
805        public int size() {
806            // total number of pending broadcast entries across all userIds
807            int num = 0;
808            for (int i = 0; i< mUidMap.size(); i++) {
809                num += mUidMap.valueAt(i).size();
810            }
811            return num;
812        }
813
814        public void clear() {
815            mUidMap.clear();
816        }
817
818        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
819            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
820            if (map == null) {
821                map = new ArrayMap<String, ArrayList<String>>();
822                mUidMap.put(userId, map);
823            }
824            return map;
825        }
826    }
827    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
828
829    // Service Connection to remote media container service to copy
830    // package uri's from external media onto secure containers
831    // or internal storage.
832    private IMediaContainerService mContainerService = null;
833
834    static final int SEND_PENDING_BROADCAST = 1;
835    static final int MCS_BOUND = 3;
836    static final int END_COPY = 4;
837    static final int INIT_COPY = 5;
838    static final int MCS_UNBIND = 6;
839    static final int START_CLEANING_PACKAGE = 7;
840    static final int FIND_INSTALL_LOC = 8;
841    static final int POST_INSTALL = 9;
842    static final int MCS_RECONNECT = 10;
843    static final int MCS_GIVE_UP = 11;
844    static final int UPDATED_MEDIA_STATUS = 12;
845    static final int WRITE_SETTINGS = 13;
846    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
847    static final int PACKAGE_VERIFIED = 15;
848    static final int CHECK_PENDING_VERIFICATION = 16;
849    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
850    static final int INTENT_FILTER_VERIFIED = 18;
851
852    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
853
854    // Delay time in millisecs
855    static final int BROADCAST_DELAY = 10 * 1000;
856
857    static UserManagerService sUserManager;
858
859    // Stores a list of users whose package restrictions file needs to be updated
860    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
861
862    final private DefaultContainerConnection mDefContainerConn =
863            new DefaultContainerConnection();
864    class DefaultContainerConnection implements ServiceConnection {
865        public void onServiceConnected(ComponentName name, IBinder service) {
866            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
867            IMediaContainerService imcs =
868                IMediaContainerService.Stub.asInterface(service);
869            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
870        }
871
872        public void onServiceDisconnected(ComponentName name) {
873            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
874        }
875    }
876
877    // Recordkeeping of restore-after-install operations that are currently in flight
878    // between the Package Manager and the Backup Manager
879    class PostInstallData {
880        public InstallArgs args;
881        public PackageInstalledInfo res;
882
883        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
884            args = _a;
885            res = _r;
886        }
887    }
888
889    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
890    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
891
892    // backup/restore of preferred activity state
893    private static final String TAG_PREFERRED_BACKUP = "pa";
894
895    private final String mRequiredVerifierPackage;
896
897    private final PackageUsage mPackageUsage = new PackageUsage();
898
899    private class PackageUsage {
900        private static final int WRITE_INTERVAL
901            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
902
903        private final Object mFileLock = new Object();
904        private final AtomicLong mLastWritten = new AtomicLong(0);
905        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
906
907        private boolean mIsHistoricalPackageUsageAvailable = true;
908
909        boolean isHistoricalPackageUsageAvailable() {
910            return mIsHistoricalPackageUsageAvailable;
911        }
912
913        void write(boolean force) {
914            if (force) {
915                writeInternal();
916                return;
917            }
918            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
919                && !DEBUG_DEXOPT) {
920                return;
921            }
922            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
923                new Thread("PackageUsage_DiskWriter") {
924                    @Override
925                    public void run() {
926                        try {
927                            writeInternal();
928                        } finally {
929                            mBackgroundWriteRunning.set(false);
930                        }
931                    }
932                }.start();
933            }
934        }
935
936        private void writeInternal() {
937            synchronized (mPackages) {
938                synchronized (mFileLock) {
939                    AtomicFile file = getFile();
940                    FileOutputStream f = null;
941                    try {
942                        f = file.startWrite();
943                        BufferedOutputStream out = new BufferedOutputStream(f);
944                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
945                        StringBuilder sb = new StringBuilder();
946                        for (PackageParser.Package pkg : mPackages.values()) {
947                            if (pkg.mLastPackageUsageTimeInMills == 0) {
948                                continue;
949                            }
950                            sb.setLength(0);
951                            sb.append(pkg.packageName);
952                            sb.append(' ');
953                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
954                            sb.append('\n');
955                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
956                        }
957                        out.flush();
958                        file.finishWrite(f);
959                    } catch (IOException e) {
960                        if (f != null) {
961                            file.failWrite(f);
962                        }
963                        Log.e(TAG, "Failed to write package usage times", e);
964                    }
965                }
966            }
967            mLastWritten.set(SystemClock.elapsedRealtime());
968        }
969
970        void readLP() {
971            synchronized (mFileLock) {
972                AtomicFile file = getFile();
973                BufferedInputStream in = null;
974                try {
975                    in = new BufferedInputStream(file.openRead());
976                    StringBuffer sb = new StringBuffer();
977                    while (true) {
978                        String packageName = readToken(in, sb, ' ');
979                        if (packageName == null) {
980                            break;
981                        }
982                        String timeInMillisString = readToken(in, sb, '\n');
983                        if (timeInMillisString == null) {
984                            throw new IOException("Failed to find last usage time for package "
985                                                  + packageName);
986                        }
987                        PackageParser.Package pkg = mPackages.get(packageName);
988                        if (pkg == null) {
989                            continue;
990                        }
991                        long timeInMillis;
992                        try {
993                            timeInMillis = Long.parseLong(timeInMillisString.toString());
994                        } catch (NumberFormatException e) {
995                            throw new IOException("Failed to parse " + timeInMillisString
996                                                  + " as a long.", e);
997                        }
998                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
999                    }
1000                } catch (FileNotFoundException expected) {
1001                    mIsHistoricalPackageUsageAvailable = false;
1002                } catch (IOException e) {
1003                    Log.w(TAG, "Failed to read package usage times", e);
1004                } finally {
1005                    IoUtils.closeQuietly(in);
1006                }
1007            }
1008            mLastWritten.set(SystemClock.elapsedRealtime());
1009        }
1010
1011        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1012                throws IOException {
1013            sb.setLength(0);
1014            while (true) {
1015                int ch = in.read();
1016                if (ch == -1) {
1017                    if (sb.length() == 0) {
1018                        return null;
1019                    }
1020                    throw new IOException("Unexpected EOF");
1021                }
1022                if (ch == endOfToken) {
1023                    return sb.toString();
1024                }
1025                sb.append((char)ch);
1026            }
1027        }
1028
1029        private AtomicFile getFile() {
1030            File dataDir = Environment.getDataDirectory();
1031            File systemDir = new File(dataDir, "system");
1032            File fname = new File(systemDir, "package-usage.list");
1033            return new AtomicFile(fname);
1034        }
1035    }
1036
1037    class PackageHandler extends Handler {
1038        private boolean mBound = false;
1039        final ArrayList<HandlerParams> mPendingInstalls =
1040            new ArrayList<HandlerParams>();
1041
1042        private boolean connectToService() {
1043            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1044                    " DefaultContainerService");
1045            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1046            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1047            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1048                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1049                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1050                mBound = true;
1051                return true;
1052            }
1053            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1054            return false;
1055        }
1056
1057        private void disconnectService() {
1058            mContainerService = null;
1059            mBound = false;
1060            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1061            mContext.unbindService(mDefContainerConn);
1062            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1063        }
1064
1065        PackageHandler(Looper looper) {
1066            super(looper);
1067        }
1068
1069        public void handleMessage(Message msg) {
1070            try {
1071                doHandleMessage(msg);
1072            } finally {
1073                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1074            }
1075        }
1076
1077        void doHandleMessage(Message msg) {
1078            switch (msg.what) {
1079                case INIT_COPY: {
1080                    HandlerParams params = (HandlerParams) msg.obj;
1081                    int idx = mPendingInstalls.size();
1082                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1083                    // If a bind was already initiated we dont really
1084                    // need to do anything. The pending install
1085                    // will be processed later on.
1086                    if (!mBound) {
1087                        // If this is the only one pending we might
1088                        // have to bind to the service again.
1089                        if (!connectToService()) {
1090                            Slog.e(TAG, "Failed to bind to media container service");
1091                            params.serviceError();
1092                            return;
1093                        } else {
1094                            // Once we bind to the service, the first
1095                            // pending request will be processed.
1096                            mPendingInstalls.add(idx, params);
1097                        }
1098                    } else {
1099                        mPendingInstalls.add(idx, params);
1100                        // Already bound to the service. Just make
1101                        // sure we trigger off processing the first request.
1102                        if (idx == 0) {
1103                            mHandler.sendEmptyMessage(MCS_BOUND);
1104                        }
1105                    }
1106                    break;
1107                }
1108                case MCS_BOUND: {
1109                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1110                    if (msg.obj != null) {
1111                        mContainerService = (IMediaContainerService) msg.obj;
1112                    }
1113                    if (mContainerService == null) {
1114                        if (!mBound) {
1115                            // Something seriously wrong since we are not bound and we are not
1116                            // waiting for connection. Bail out.
1117                            Slog.e(TAG, "Cannot bind to media container service");
1118                            for (HandlerParams params : mPendingInstalls) {
1119                                // Indicate service bind error
1120                                params.serviceError();
1121                            }
1122                            mPendingInstalls.clear();
1123                        } else {
1124                            Slog.w(TAG, "Waiting to connect to media container service");
1125                        }
1126                    } else if (mPendingInstalls.size() > 0) {
1127                        HandlerParams params = mPendingInstalls.get(0);
1128                        if (params != null) {
1129                            if (params.startCopy()) {
1130                                // We are done...  look for more work or to
1131                                // go idle.
1132                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1133                                        "Checking for more work or unbind...");
1134                                // Delete pending install
1135                                if (mPendingInstalls.size() > 0) {
1136                                    mPendingInstalls.remove(0);
1137                                }
1138                                if (mPendingInstalls.size() == 0) {
1139                                    if (mBound) {
1140                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1141                                                "Posting delayed MCS_UNBIND");
1142                                        removeMessages(MCS_UNBIND);
1143                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1144                                        // Unbind after a little delay, to avoid
1145                                        // continual thrashing.
1146                                        sendMessageDelayed(ubmsg, 10000);
1147                                    }
1148                                } else {
1149                                    // There are more pending requests in queue.
1150                                    // Just post MCS_BOUND message to trigger processing
1151                                    // of next pending install.
1152                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1153                                            "Posting MCS_BOUND for next work");
1154                                    mHandler.sendEmptyMessage(MCS_BOUND);
1155                                }
1156                            }
1157                        }
1158                    } else {
1159                        // Should never happen ideally.
1160                        Slog.w(TAG, "Empty queue");
1161                    }
1162                    break;
1163                }
1164                case MCS_RECONNECT: {
1165                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1166                    if (mPendingInstalls.size() > 0) {
1167                        if (mBound) {
1168                            disconnectService();
1169                        }
1170                        if (!connectToService()) {
1171                            Slog.e(TAG, "Failed to bind to media container service");
1172                            for (HandlerParams params : mPendingInstalls) {
1173                                // Indicate service bind error
1174                                params.serviceError();
1175                            }
1176                            mPendingInstalls.clear();
1177                        }
1178                    }
1179                    break;
1180                }
1181                case MCS_UNBIND: {
1182                    // If there is no actual work left, then time to unbind.
1183                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1184
1185                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1186                        if (mBound) {
1187                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1188
1189                            disconnectService();
1190                        }
1191                    } else if (mPendingInstalls.size() > 0) {
1192                        // There are more pending requests in queue.
1193                        // Just post MCS_BOUND message to trigger processing
1194                        // of next pending install.
1195                        mHandler.sendEmptyMessage(MCS_BOUND);
1196                    }
1197
1198                    break;
1199                }
1200                case MCS_GIVE_UP: {
1201                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1202                    mPendingInstalls.remove(0);
1203                    break;
1204                }
1205                case SEND_PENDING_BROADCAST: {
1206                    String packages[];
1207                    ArrayList<String> components[];
1208                    int size = 0;
1209                    int uids[];
1210                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1211                    synchronized (mPackages) {
1212                        if (mPendingBroadcasts == null) {
1213                            return;
1214                        }
1215                        size = mPendingBroadcasts.size();
1216                        if (size <= 0) {
1217                            // Nothing to be done. Just return
1218                            return;
1219                        }
1220                        packages = new String[size];
1221                        components = new ArrayList[size];
1222                        uids = new int[size];
1223                        int i = 0;  // filling out the above arrays
1224
1225                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1226                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1227                            Iterator<Map.Entry<String, ArrayList<String>>> it
1228                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1229                                            .entrySet().iterator();
1230                            while (it.hasNext() && i < size) {
1231                                Map.Entry<String, ArrayList<String>> ent = it.next();
1232                                packages[i] = ent.getKey();
1233                                components[i] = ent.getValue();
1234                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1235                                uids[i] = (ps != null)
1236                                        ? UserHandle.getUid(packageUserId, ps.appId)
1237                                        : -1;
1238                                i++;
1239                            }
1240                        }
1241                        size = i;
1242                        mPendingBroadcasts.clear();
1243                    }
1244                    // Send broadcasts
1245                    for (int i = 0; i < size; i++) {
1246                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1247                    }
1248                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1249                    break;
1250                }
1251                case START_CLEANING_PACKAGE: {
1252                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1253                    final String packageName = (String)msg.obj;
1254                    final int userId = msg.arg1;
1255                    final boolean andCode = msg.arg2 != 0;
1256                    synchronized (mPackages) {
1257                        if (userId == UserHandle.USER_ALL) {
1258                            int[] users = sUserManager.getUserIds();
1259                            for (int user : users) {
1260                                mSettings.addPackageToCleanLPw(
1261                                        new PackageCleanItem(user, packageName, andCode));
1262                            }
1263                        } else {
1264                            mSettings.addPackageToCleanLPw(
1265                                    new PackageCleanItem(userId, packageName, andCode));
1266                        }
1267                    }
1268                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1269                    startCleaningPackages();
1270                } break;
1271                case POST_INSTALL: {
1272                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1273                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1274                    mRunningInstalls.delete(msg.arg1);
1275                    boolean deleteOld = false;
1276
1277                    if (data != null) {
1278                        InstallArgs args = data.args;
1279                        PackageInstalledInfo res = data.res;
1280
1281                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1282                            res.removedInfo.sendBroadcast(false, true, false);
1283                            Bundle extras = new Bundle(1);
1284                            extras.putInt(Intent.EXTRA_UID, res.uid);
1285
1286                            // Now that we successfully installed the package, grant runtime
1287                            // permissions if requested before broadcasting the install.
1288                            if ((args.installFlags
1289                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1290                                grantRequestedRuntimePermissions(res.pkg,
1291                                        args.user.getIdentifier());
1292                            }
1293
1294                            // Determine the set of users who are adding this
1295                            // package for the first time vs. those who are seeing
1296                            // an update.
1297                            int[] firstUsers;
1298                            int[] updateUsers = new int[0];
1299                            if (res.origUsers == null || res.origUsers.length == 0) {
1300                                firstUsers = res.newUsers;
1301                            } else {
1302                                firstUsers = new int[0];
1303                                for (int i=0; i<res.newUsers.length; i++) {
1304                                    int user = res.newUsers[i];
1305                                    boolean isNew = true;
1306                                    for (int j=0; j<res.origUsers.length; j++) {
1307                                        if (res.origUsers[j] == user) {
1308                                            isNew = false;
1309                                            break;
1310                                        }
1311                                    }
1312                                    if (isNew) {
1313                                        int[] newFirst = new int[firstUsers.length+1];
1314                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1315                                                firstUsers.length);
1316                                        newFirst[firstUsers.length] = user;
1317                                        firstUsers = newFirst;
1318                                    } else {
1319                                        int[] newUpdate = new int[updateUsers.length+1];
1320                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1321                                                updateUsers.length);
1322                                        newUpdate[updateUsers.length] = user;
1323                                        updateUsers = newUpdate;
1324                                    }
1325                                }
1326                            }
1327                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1328                                    res.pkg.applicationInfo.packageName,
1329                                    extras, null, null, firstUsers);
1330                            final boolean update = res.removedInfo.removedPackage != null;
1331                            if (update) {
1332                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1333                            }
1334                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1335                                    res.pkg.applicationInfo.packageName,
1336                                    extras, null, null, updateUsers);
1337                            if (update) {
1338                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1339                                        res.pkg.applicationInfo.packageName,
1340                                        extras, null, null, updateUsers);
1341                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1342                                        null, null,
1343                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1344
1345                                // treat asec-hosted packages like removable media on upgrade
1346                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1347                                    if (DEBUG_INSTALL) {
1348                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1349                                                + " is ASEC-hosted -> AVAILABLE");
1350                                    }
1351                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1352                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1353                                    pkgList.add(res.pkg.applicationInfo.packageName);
1354                                    sendResourcesChangedBroadcast(true, true,
1355                                            pkgList,uidArray, null);
1356                                }
1357                            }
1358                            if (res.removedInfo.args != null) {
1359                                // Remove the replaced package's older resources safely now
1360                                deleteOld = true;
1361                            }
1362
1363                            // Log current value of "unknown sources" setting
1364                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1365                                getUnknownSourcesSettings());
1366                        }
1367                        // Force a gc to clear up things
1368                        Runtime.getRuntime().gc();
1369                        // We delete after a gc for applications  on sdcard.
1370                        if (deleteOld) {
1371                            synchronized (mInstallLock) {
1372                                res.removedInfo.args.doPostDeleteLI(true);
1373                            }
1374                        }
1375                        if (args.observer != null) {
1376                            try {
1377                                Bundle extras = extrasForInstallResult(res);
1378                                args.observer.onPackageInstalled(res.name, res.returnCode,
1379                                        res.returnMsg, extras);
1380                            } catch (RemoteException e) {
1381                                Slog.i(TAG, "Observer no longer exists.");
1382                            }
1383                        }
1384                    } else {
1385                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1386                    }
1387                } break;
1388                case UPDATED_MEDIA_STATUS: {
1389                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1390                    boolean reportStatus = msg.arg1 == 1;
1391                    boolean doGc = msg.arg2 == 1;
1392                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1393                    if (doGc) {
1394                        // Force a gc to clear up stale containers.
1395                        Runtime.getRuntime().gc();
1396                    }
1397                    if (msg.obj != null) {
1398                        @SuppressWarnings("unchecked")
1399                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1400                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1401                        // Unload containers
1402                        unloadAllContainers(args);
1403                    }
1404                    if (reportStatus) {
1405                        try {
1406                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1407                            PackageHelper.getMountService().finishMediaUpdate();
1408                        } catch (RemoteException e) {
1409                            Log.e(TAG, "MountService not running?");
1410                        }
1411                    }
1412                } break;
1413                case WRITE_SETTINGS: {
1414                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1415                    synchronized (mPackages) {
1416                        removeMessages(WRITE_SETTINGS);
1417                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1418                        mSettings.writeLPr();
1419                        mDirtyUsers.clear();
1420                    }
1421                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422                } break;
1423                case WRITE_PACKAGE_RESTRICTIONS: {
1424                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1425                    synchronized (mPackages) {
1426                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1427                        for (int userId : mDirtyUsers) {
1428                            mSettings.writePackageRestrictionsLPr(userId);
1429                        }
1430                        mDirtyUsers.clear();
1431                    }
1432                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433                } break;
1434                case CHECK_PENDING_VERIFICATION: {
1435                    final int verificationId = msg.arg1;
1436                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1437
1438                    if ((state != null) && !state.timeoutExtended()) {
1439                        final InstallArgs args = state.getInstallArgs();
1440                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1441
1442                        Slog.i(TAG, "Verification timed out for " + originUri);
1443                        mPendingVerification.remove(verificationId);
1444
1445                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1446
1447                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1448                            Slog.i(TAG, "Continuing with installation of " + originUri);
1449                            state.setVerifierResponse(Binder.getCallingUid(),
1450                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1451                            broadcastPackageVerified(verificationId, originUri,
1452                                    PackageManager.VERIFICATION_ALLOW,
1453                                    state.getInstallArgs().getUser());
1454                            try {
1455                                ret = args.copyApk(mContainerService, true);
1456                            } catch (RemoteException e) {
1457                                Slog.e(TAG, "Could not contact the ContainerService");
1458                            }
1459                        } else {
1460                            broadcastPackageVerified(verificationId, originUri,
1461                                    PackageManager.VERIFICATION_REJECT,
1462                                    state.getInstallArgs().getUser());
1463                        }
1464
1465                        processPendingInstall(args, ret);
1466                        mHandler.sendEmptyMessage(MCS_UNBIND);
1467                    }
1468                    break;
1469                }
1470                case PACKAGE_VERIFIED: {
1471                    final int verificationId = msg.arg1;
1472
1473                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1474                    if (state == null) {
1475                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1476                        break;
1477                    }
1478
1479                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1480
1481                    state.setVerifierResponse(response.callerUid, response.code);
1482
1483                    if (state.isVerificationComplete()) {
1484                        mPendingVerification.remove(verificationId);
1485
1486                        final InstallArgs args = state.getInstallArgs();
1487                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1488
1489                        int ret;
1490                        if (state.isInstallAllowed()) {
1491                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1492                            broadcastPackageVerified(verificationId, originUri,
1493                                    response.code, state.getInstallArgs().getUser());
1494                            try {
1495                                ret = args.copyApk(mContainerService, true);
1496                            } catch (RemoteException e) {
1497                                Slog.e(TAG, "Could not contact the ContainerService");
1498                            }
1499                        } else {
1500                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1501                        }
1502
1503                        processPendingInstall(args, ret);
1504
1505                        mHandler.sendEmptyMessage(MCS_UNBIND);
1506                    }
1507
1508                    break;
1509                }
1510                case START_INTENT_FILTER_VERIFICATIONS: {
1511                    int userId = msg.arg1;
1512                    int verifierUid = msg.arg2;
1513                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1514
1515                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1516                    break;
1517                }
1518                case INTENT_FILTER_VERIFIED: {
1519                    final int verificationId = msg.arg1;
1520
1521                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1522                            verificationId);
1523                    if (state == null) {
1524                        Slog.w(TAG, "Invalid IntentFilter verification token "
1525                                + verificationId + " received");
1526                        break;
1527                    }
1528
1529                    final int userId = state.getUserId();
1530
1531                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1532                            "Processing IntentFilter verification with token:"
1533                            + verificationId + " and userId:" + userId);
1534
1535                    final IntentFilterVerificationResponse response =
1536                            (IntentFilterVerificationResponse) msg.obj;
1537
1538                    state.setVerifierResponse(response.callerUid, response.code);
1539
1540                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1541                            "IntentFilter verification with token:" + verificationId
1542                            + " and userId:" + userId
1543                            + " is settings verifier response with response code:"
1544                            + response.code);
1545
1546                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1547                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1548                                + response.getFailedDomainsString());
1549                    }
1550
1551                    if (state.isVerificationComplete()) {
1552                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1553                    } else {
1554                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1555                                "IntentFilter verification with token:" + verificationId
1556                                + " was not said to be complete");
1557                    }
1558
1559                    break;
1560                }
1561            }
1562        }
1563    }
1564
1565    private StorageEventListener mStorageListener = new StorageEventListener() {
1566        @Override
1567        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1568            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1569                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1570                    // TODO: ensure that private directories exist for all active users
1571                    // TODO: remove user data whose serial number doesn't match
1572                    loadPrivatePackages(vol);
1573                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1574                    unloadPrivatePackages(vol);
1575                }
1576            }
1577
1578            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1579                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1580                    updateExternalMediaStatus(true, false);
1581                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1582                    updateExternalMediaStatus(false, false);
1583                }
1584            }
1585        }
1586
1587        @Override
1588        public void onVolumeForgotten(String fsUuid) {
1589            // TODO: remove all packages hosted on this uuid
1590        }
1591    };
1592
1593    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1594        if (userId >= UserHandle.USER_OWNER) {
1595            grantRequestedRuntimePermissionsForUser(pkg, userId);
1596        } else if (userId == UserHandle.USER_ALL) {
1597            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1598                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1599            }
1600        }
1601
1602        // We could have touched GID membership, so flush out packages.list
1603        synchronized (mPackages) {
1604            mSettings.writePackageListLPr();
1605        }
1606    }
1607
1608    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1609        SettingBase sb = (SettingBase) pkg.mExtras;
1610        if (sb == null) {
1611            return;
1612        }
1613
1614        PermissionsState permissionsState = sb.getPermissionsState();
1615
1616        for (String permission : pkg.requestedPermissions) {
1617            BasePermission bp = mSettings.mPermissions.get(permission);
1618            if (bp != null && bp.isRuntime()) {
1619                permissionsState.grantRuntimePermission(bp, userId);
1620            }
1621        }
1622    }
1623
1624    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1625        Bundle extras = null;
1626        switch (res.returnCode) {
1627            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1628                extras = new Bundle();
1629                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1630                        res.origPermission);
1631                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1632                        res.origPackage);
1633                break;
1634            }
1635            case PackageManager.INSTALL_SUCCEEDED: {
1636                extras = new Bundle();
1637                extras.putBoolean(Intent.EXTRA_REPLACING,
1638                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1639                break;
1640            }
1641        }
1642        return extras;
1643    }
1644
1645    void scheduleWriteSettingsLocked() {
1646        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1647            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1648        }
1649    }
1650
1651    void scheduleWritePackageRestrictionsLocked(int userId) {
1652        if (!sUserManager.exists(userId)) return;
1653        mDirtyUsers.add(userId);
1654        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1655            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1656        }
1657    }
1658
1659    public static PackageManagerService main(Context context, Installer installer,
1660            boolean factoryTest, boolean onlyCore) {
1661        PackageManagerService m = new PackageManagerService(context, installer,
1662                factoryTest, onlyCore);
1663        ServiceManager.addService("package", m);
1664        return m;
1665    }
1666
1667    static String[] splitString(String str, char sep) {
1668        int count = 1;
1669        int i = 0;
1670        while ((i=str.indexOf(sep, i)) >= 0) {
1671            count++;
1672            i++;
1673        }
1674
1675        String[] res = new String[count];
1676        i=0;
1677        count = 0;
1678        int lastI=0;
1679        while ((i=str.indexOf(sep, i)) >= 0) {
1680            res[count] = str.substring(lastI, i);
1681            count++;
1682            i++;
1683            lastI = i;
1684        }
1685        res[count] = str.substring(lastI, str.length());
1686        return res;
1687    }
1688
1689    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1690        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1691                Context.DISPLAY_SERVICE);
1692        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1693    }
1694
1695    public PackageManagerService(Context context, Installer installer,
1696            boolean factoryTest, boolean onlyCore) {
1697        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1698                SystemClock.uptimeMillis());
1699
1700        if (mSdkVersion <= 0) {
1701            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1702        }
1703
1704        mContext = context;
1705        mFactoryTest = factoryTest;
1706        mOnlyCore = onlyCore;
1707        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1708        mMetrics = new DisplayMetrics();
1709        mSettings = new Settings(mPackages);
1710        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1711                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1712        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1713                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1714        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1715                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1716        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1717                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1718        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1719                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1720        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1721                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1722
1723        // TODO: add a property to control this?
1724        long dexOptLRUThresholdInMinutes;
1725        if (mLazyDexOpt) {
1726            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1727        } else {
1728            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1729        }
1730        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1731
1732        String separateProcesses = SystemProperties.get("debug.separate_processes");
1733        if (separateProcesses != null && separateProcesses.length() > 0) {
1734            if ("*".equals(separateProcesses)) {
1735                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1736                mSeparateProcesses = null;
1737                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1738            } else {
1739                mDefParseFlags = 0;
1740                mSeparateProcesses = separateProcesses.split(",");
1741                Slog.w(TAG, "Running with debug.separate_processes: "
1742                        + separateProcesses);
1743            }
1744        } else {
1745            mDefParseFlags = 0;
1746            mSeparateProcesses = null;
1747        }
1748
1749        mInstaller = installer;
1750        mPackageDexOptimizer = new PackageDexOptimizer(this);
1751        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1752
1753        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1754                FgThread.get().getLooper());
1755
1756        getDefaultDisplayMetrics(context, mMetrics);
1757
1758        SystemConfig systemConfig = SystemConfig.getInstance();
1759        mGlobalGids = systemConfig.getGlobalGids();
1760        mSystemPermissions = systemConfig.getSystemPermissions();
1761        mAvailableFeatures = systemConfig.getAvailableFeatures();
1762
1763        synchronized (mInstallLock) {
1764        // writer
1765        synchronized (mPackages) {
1766            mHandlerThread = new ServiceThread(TAG,
1767                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1768            mHandlerThread.start();
1769            mHandler = new PackageHandler(mHandlerThread.getLooper());
1770            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1771
1772            File dataDir = Environment.getDataDirectory();
1773            mAppDataDir = new File(dataDir, "data");
1774            mAppInstallDir = new File(dataDir, "app");
1775            mAppLib32InstallDir = new File(dataDir, "app-lib");
1776            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1777            mUserAppDataDir = new File(dataDir, "user");
1778            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1779
1780            sUserManager = new UserManagerService(context, this,
1781                    mInstallLock, mPackages);
1782
1783            // Propagate permission configuration in to package manager.
1784            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1785                    = systemConfig.getPermissions();
1786            for (int i=0; i<permConfig.size(); i++) {
1787                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1788                BasePermission bp = mSettings.mPermissions.get(perm.name);
1789                if (bp == null) {
1790                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1791                    mSettings.mPermissions.put(perm.name, bp);
1792                }
1793                if (perm.gids != null) {
1794                    bp.setGids(perm.gids, perm.perUser);
1795                }
1796            }
1797
1798            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1799            for (int i=0; i<libConfig.size(); i++) {
1800                mSharedLibraries.put(libConfig.keyAt(i),
1801                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1802            }
1803
1804            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1805
1806            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1807                    mSdkVersion, mOnlyCore);
1808
1809            String customResolverActivity = Resources.getSystem().getString(
1810                    R.string.config_customResolverActivity);
1811            if (TextUtils.isEmpty(customResolverActivity)) {
1812                customResolverActivity = null;
1813            } else {
1814                mCustomResolverComponentName = ComponentName.unflattenFromString(
1815                        customResolverActivity);
1816            }
1817
1818            long startTime = SystemClock.uptimeMillis();
1819
1820            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1821                    startTime);
1822
1823            // Set flag to monitor and not change apk file paths when
1824            // scanning install directories.
1825            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1826
1827            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1828
1829            /**
1830             * Add everything in the in the boot class path to the
1831             * list of process files because dexopt will have been run
1832             * if necessary during zygote startup.
1833             */
1834            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1835            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1836
1837            if (bootClassPath != null) {
1838                String[] bootClassPathElements = splitString(bootClassPath, ':');
1839                for (String element : bootClassPathElements) {
1840                    alreadyDexOpted.add(element);
1841                }
1842            } else {
1843                Slog.w(TAG, "No BOOTCLASSPATH found!");
1844            }
1845
1846            if (systemServerClassPath != null) {
1847                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1848                for (String element : systemServerClassPathElements) {
1849                    alreadyDexOpted.add(element);
1850                }
1851            } else {
1852                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1853            }
1854
1855            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1856            final String[] dexCodeInstructionSets =
1857                    getDexCodeInstructionSets(
1858                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1859
1860            /**
1861             * Ensure all external libraries have had dexopt run on them.
1862             */
1863            if (mSharedLibraries.size() > 0) {
1864                // NOTE: For now, we're compiling these system "shared libraries"
1865                // (and framework jars) into all available architectures. It's possible
1866                // to compile them only when we come across an app that uses them (there's
1867                // already logic for that in scanPackageLI) but that adds some complexity.
1868                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1869                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1870                        final String lib = libEntry.path;
1871                        if (lib == null) {
1872                            continue;
1873                        }
1874
1875                        try {
1876                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1877                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1878                                alreadyDexOpted.add(lib);
1879                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1880                            }
1881                        } catch (FileNotFoundException e) {
1882                            Slog.w(TAG, "Library not found: " + lib);
1883                        } catch (IOException e) {
1884                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1885                                    + e.getMessage());
1886                        }
1887                    }
1888                }
1889            }
1890
1891            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1892
1893            // Gross hack for now: we know this file doesn't contain any
1894            // code, so don't dexopt it to avoid the resulting log spew.
1895            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1896
1897            // Gross hack for now: we know this file is only part of
1898            // the boot class path for art, so don't dexopt it to
1899            // avoid the resulting log spew.
1900            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1901
1902            /**
1903             * There are a number of commands implemented in Java, which
1904             * we currently need to do the dexopt on so that they can be
1905             * run from a non-root shell.
1906             */
1907            String[] frameworkFiles = frameworkDir.list();
1908            if (frameworkFiles != null) {
1909                // TODO: We could compile these only for the most preferred ABI. We should
1910                // first double check that the dex files for these commands are not referenced
1911                // by other system apps.
1912                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1913                    for (int i=0; i<frameworkFiles.length; i++) {
1914                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1915                        String path = libPath.getPath();
1916                        // Skip the file if we already did it.
1917                        if (alreadyDexOpted.contains(path)) {
1918                            continue;
1919                        }
1920                        // Skip the file if it is not a type we want to dexopt.
1921                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1922                            continue;
1923                        }
1924                        try {
1925                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1926                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1927                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1928                            }
1929                        } catch (FileNotFoundException e) {
1930                            Slog.w(TAG, "Jar not found: " + path);
1931                        } catch (IOException e) {
1932                            Slog.w(TAG, "Exception reading jar: " + path, e);
1933                        }
1934                    }
1935                }
1936            }
1937
1938            // Collect vendor overlay packages.
1939            // (Do this before scanning any apps.)
1940            // For security and version matching reason, only consider
1941            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1942            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1943            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1944                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1945
1946            // Find base frameworks (resource packages without code).
1947            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1948                    | PackageParser.PARSE_IS_SYSTEM_DIR
1949                    | PackageParser.PARSE_IS_PRIVILEGED,
1950                    scanFlags | SCAN_NO_DEX, 0);
1951
1952            // Collected privileged system packages.
1953            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1954            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1955                    | PackageParser.PARSE_IS_SYSTEM_DIR
1956                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1957
1958            // Collect ordinary system packages.
1959            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1960            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1961                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1962
1963            // Collect all vendor packages.
1964            File vendorAppDir = new File("/vendor/app");
1965            try {
1966                vendorAppDir = vendorAppDir.getCanonicalFile();
1967            } catch (IOException e) {
1968                // failed to look up canonical path, continue with original one
1969            }
1970            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1971                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1972
1973            // Collect all OEM packages.
1974            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1975            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1976                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1977
1978            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1979            mInstaller.moveFiles();
1980
1981            // Prune any system packages that no longer exist.
1982            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1983            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1984            if (!mOnlyCore) {
1985                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1986                while (psit.hasNext()) {
1987                    PackageSetting ps = psit.next();
1988
1989                    /*
1990                     * If this is not a system app, it can't be a
1991                     * disable system app.
1992                     */
1993                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1994                        continue;
1995                    }
1996
1997                    /*
1998                     * If the package is scanned, it's not erased.
1999                     */
2000                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2001                    if (scannedPkg != null) {
2002                        /*
2003                         * If the system app is both scanned and in the
2004                         * disabled packages list, then it must have been
2005                         * added via OTA. Remove it from the currently
2006                         * scanned package so the previously user-installed
2007                         * application can be scanned.
2008                         */
2009                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2010                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2011                                    + ps.name + "; removing system app.  Last known codePath="
2012                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2013                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2014                                    + scannedPkg.mVersionCode);
2015                            removePackageLI(ps, true);
2016                            expectingBetter.put(ps.name, ps.codePath);
2017                        }
2018
2019                        continue;
2020                    }
2021
2022                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2023                        psit.remove();
2024                        logCriticalInfo(Log.WARN, "System package " + ps.name
2025                                + " no longer exists; wiping its data");
2026                        removeDataDirsLI(null, ps.name);
2027                    } else {
2028                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2029                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2030                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2031                        }
2032                    }
2033                }
2034            }
2035
2036            //look for any incomplete package installations
2037            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2038            //clean up list
2039            for(int i = 0; i < deletePkgsList.size(); i++) {
2040                //clean up here
2041                cleanupInstallFailedPackage(deletePkgsList.get(i));
2042            }
2043            //delete tmp files
2044            deleteTempPackageFiles();
2045
2046            // Remove any shared userIDs that have no associated packages
2047            mSettings.pruneSharedUsersLPw();
2048
2049            if (!mOnlyCore) {
2050                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2051                        SystemClock.uptimeMillis());
2052                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2053
2054                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2055                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2056
2057                /**
2058                 * Remove disable package settings for any updated system
2059                 * apps that were removed via an OTA. If they're not a
2060                 * previously-updated app, remove them completely.
2061                 * Otherwise, just revoke their system-level permissions.
2062                 */
2063                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2064                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2065                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2066
2067                    String msg;
2068                    if (deletedPkg == null) {
2069                        msg = "Updated system package " + deletedAppName
2070                                + " no longer exists; wiping its data";
2071                        removeDataDirsLI(null, deletedAppName);
2072                    } else {
2073                        msg = "Updated system app + " + deletedAppName
2074                                + " no longer present; removing system privileges for "
2075                                + deletedAppName;
2076
2077                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2078
2079                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2080                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2081                    }
2082                    logCriticalInfo(Log.WARN, msg);
2083                }
2084
2085                /**
2086                 * Make sure all system apps that we expected to appear on
2087                 * the userdata partition actually showed up. If they never
2088                 * appeared, crawl back and revive the system version.
2089                 */
2090                for (int i = 0; i < expectingBetter.size(); i++) {
2091                    final String packageName = expectingBetter.keyAt(i);
2092                    if (!mPackages.containsKey(packageName)) {
2093                        final File scanFile = expectingBetter.valueAt(i);
2094
2095                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2096                                + " but never showed up; reverting to system");
2097
2098                        final int reparseFlags;
2099                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2100                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2101                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2102                                    | PackageParser.PARSE_IS_PRIVILEGED;
2103                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2104                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2105                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2106                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2107                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2108                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2109                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2110                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2111                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2112                        } else {
2113                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2114                            continue;
2115                        }
2116
2117                        mSettings.enableSystemPackageLPw(packageName);
2118
2119                        try {
2120                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2121                        } catch (PackageManagerException e) {
2122                            Slog.e(TAG, "Failed to parse original system package: "
2123                                    + e.getMessage());
2124                        }
2125                    }
2126                }
2127            }
2128
2129            // Now that we know all of the shared libraries, update all clients to have
2130            // the correct library paths.
2131            updateAllSharedLibrariesLPw();
2132
2133            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2134                // NOTE: We ignore potential failures here during a system scan (like
2135                // the rest of the commands above) because there's precious little we
2136                // can do about it. A settings error is reported, though.
2137                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2138                        false /* force dexopt */, false /* defer dexopt */);
2139            }
2140
2141            // Now that we know all the packages we are keeping,
2142            // read and update their last usage times.
2143            mPackageUsage.readLP();
2144
2145            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2146                    SystemClock.uptimeMillis());
2147            Slog.i(TAG, "Time to scan packages: "
2148                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2149                    + " seconds");
2150
2151            // If the platform SDK has changed since the last time we booted,
2152            // we need to re-grant app permission to catch any new ones that
2153            // appear.  This is really a hack, and means that apps can in some
2154            // cases get permissions that the user didn't initially explicitly
2155            // allow...  it would be nice to have some better way to handle
2156            // this situation.
2157            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2158                    != mSdkVersion;
2159            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2160                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2161                    + "; regranting permissions for internal storage");
2162            mSettings.mInternalSdkPlatform = mSdkVersion;
2163
2164            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2165                    | (regrantPermissions
2166                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2167                            : 0));
2168
2169            // If this is the first boot, and it is a normal boot, then
2170            // we need to initialize the default preferred apps.
2171            if (!mRestoredSettings && !onlyCore) {
2172                mSettings.readDefaultPreferredAppsLPw(this, 0);
2173            }
2174
2175            // If this is first boot after an OTA, and a normal boot, then
2176            // we need to clear code cache directories.
2177            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2178            if (mIsUpgrade && !onlyCore) {
2179                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2180                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2181                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2182                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2183                }
2184                mSettings.mFingerprint = Build.FINGERPRINT;
2185            }
2186
2187            primeDomainVerificationsLPw();
2188            checkDefaultBrowser();
2189
2190            // All the changes are done during package scanning.
2191            mSettings.updateInternalDatabaseVersion();
2192
2193            // can downgrade to reader
2194            mSettings.writeLPr();
2195
2196            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2197                    SystemClock.uptimeMillis());
2198
2199            mRequiredVerifierPackage = getRequiredVerifierLPr();
2200
2201            mInstallerService = new PackageInstallerService(context, this);
2202
2203            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2204            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2205                    mIntentFilterVerifierComponent);
2206
2207        } // synchronized (mPackages)
2208        } // synchronized (mInstallLock)
2209
2210        // Now after opening every single application zip, make sure they
2211        // are all flushed.  Not really needed, but keeps things nice and
2212        // tidy.
2213        Runtime.getRuntime().gc();
2214
2215        // Expose private service for system components to use.
2216        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2217    }
2218
2219    @Override
2220    public boolean isFirstBoot() {
2221        return !mRestoredSettings;
2222    }
2223
2224    @Override
2225    public boolean isOnlyCoreApps() {
2226        return mOnlyCore;
2227    }
2228
2229    @Override
2230    public boolean isUpgrade() {
2231        return mIsUpgrade;
2232    }
2233
2234    private String getRequiredVerifierLPr() {
2235        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2236        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2237                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2238
2239        String requiredVerifier = null;
2240
2241        final int N = receivers.size();
2242        for (int i = 0; i < N; i++) {
2243            final ResolveInfo info = receivers.get(i);
2244
2245            if (info.activityInfo == null) {
2246                continue;
2247            }
2248
2249            final String packageName = info.activityInfo.packageName;
2250
2251            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2252                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2253                continue;
2254            }
2255
2256            if (requiredVerifier != null) {
2257                throw new RuntimeException("There can be only one required verifier");
2258            }
2259
2260            requiredVerifier = packageName;
2261        }
2262
2263        return requiredVerifier;
2264    }
2265
2266    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2267        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2268        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2269                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2270
2271        ComponentName verifierComponentName = null;
2272
2273        int priority = -1000;
2274        final int N = receivers.size();
2275        for (int i = 0; i < N; i++) {
2276            final ResolveInfo info = receivers.get(i);
2277
2278            if (info.activityInfo == null) {
2279                continue;
2280            }
2281
2282            final String packageName = info.activityInfo.packageName;
2283
2284            final PackageSetting ps = mSettings.mPackages.get(packageName);
2285            if (ps == null) {
2286                continue;
2287            }
2288
2289            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2290                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2291                continue;
2292            }
2293
2294            // Select the IntentFilterVerifier with the highest priority
2295            if (priority < info.priority) {
2296                priority = info.priority;
2297                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2298                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2299                        + verifierComponentName + " with priority: " + info.priority);
2300            }
2301        }
2302
2303        return verifierComponentName;
2304    }
2305
2306    private void primeDomainVerificationsLPw() {
2307        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2308        boolean updated = false;
2309        ArraySet<String> allHostsSet = new ArraySet<>();
2310        for (PackageParser.Package pkg : mPackages.values()) {
2311            final String packageName = pkg.packageName;
2312            if (!hasDomainURLs(pkg)) {
2313                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2314                            "package with no domain URLs: " + packageName);
2315                continue;
2316            }
2317            if (!pkg.isSystemApp()) {
2318                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2319                        "No priming domain verifications for a non system package : " +
2320                                packageName);
2321                continue;
2322            }
2323            for (PackageParser.Activity a : pkg.activities) {
2324                for (ActivityIntentInfo filter : a.intents) {
2325                    if (hasValidDomains(filter)) {
2326                        allHostsSet.addAll(filter.getHostsList());
2327                    }
2328                }
2329            }
2330            if (allHostsSet.size() == 0) {
2331                allHostsSet.add("*");
2332            }
2333            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2334            IntentFilterVerificationInfo ivi =
2335                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2336            if (ivi != null) {
2337                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2338                        "Priming domain verifications for package: " + packageName +
2339                        " with hosts:" + ivi.getDomainsString());
2340                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2341                updated = true;
2342            }
2343            else {
2344                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2345                        "No priming domain verifications for package: " + packageName);
2346            }
2347            allHostsSet.clear();
2348        }
2349        if (updated) {
2350            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2351                    "Will need to write primed domain verifications");
2352        }
2353        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2354    }
2355
2356    private void checkDefaultBrowser() {
2357        final int myUserId = UserHandle.myUserId();
2358        final String packageName = getDefaultBrowserPackageName(myUserId);
2359        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2360        if (info == null) {
2361            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2362                    packageName);
2363            setDefaultBrowserPackageName(null, myUserId);
2364        }
2365    }
2366
2367    @Override
2368    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2369            throws RemoteException {
2370        try {
2371            return super.onTransact(code, data, reply, flags);
2372        } catch (RuntimeException e) {
2373            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2374                Slog.wtf(TAG, "Package Manager Crash", e);
2375            }
2376            throw e;
2377        }
2378    }
2379
2380    void cleanupInstallFailedPackage(PackageSetting ps) {
2381        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2382
2383        removeDataDirsLI(ps.volumeUuid, ps.name);
2384        if (ps.codePath != null) {
2385            if (ps.codePath.isDirectory()) {
2386                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2387            } else {
2388                ps.codePath.delete();
2389            }
2390        }
2391        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2392            if (ps.resourcePath.isDirectory()) {
2393                FileUtils.deleteContents(ps.resourcePath);
2394            }
2395            ps.resourcePath.delete();
2396        }
2397        mSettings.removePackageLPw(ps.name);
2398    }
2399
2400    static int[] appendInts(int[] cur, int[] add) {
2401        if (add == null) return cur;
2402        if (cur == null) return add;
2403        final int N = add.length;
2404        for (int i=0; i<N; i++) {
2405            cur = appendInt(cur, add[i]);
2406        }
2407        return cur;
2408    }
2409
2410    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2411        if (!sUserManager.exists(userId)) return null;
2412        final PackageSetting ps = (PackageSetting) p.mExtras;
2413        if (ps == null) {
2414            return null;
2415        }
2416
2417        final PermissionsState permissionsState = ps.getPermissionsState();
2418
2419        final int[] gids = permissionsState.computeGids(userId);
2420        final Set<String> permissions = permissionsState.getPermissions(userId);
2421        final PackageUserState state = ps.readUserState(userId);
2422
2423        return PackageParser.generatePackageInfo(p, gids, flags,
2424                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2425    }
2426
2427    @Override
2428    public boolean isPackageFrozen(String packageName) {
2429        synchronized (mPackages) {
2430            final PackageSetting ps = mSettings.mPackages.get(packageName);
2431            if (ps != null) {
2432                return ps.frozen;
2433            }
2434        }
2435        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2436        return true;
2437    }
2438
2439    @Override
2440    public boolean isPackageAvailable(String packageName, int userId) {
2441        if (!sUserManager.exists(userId)) return false;
2442        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2443        synchronized (mPackages) {
2444            PackageParser.Package p = mPackages.get(packageName);
2445            if (p != null) {
2446                final PackageSetting ps = (PackageSetting) p.mExtras;
2447                if (ps != null) {
2448                    final PackageUserState state = ps.readUserState(userId);
2449                    if (state != null) {
2450                        return PackageParser.isAvailable(state);
2451                    }
2452                }
2453            }
2454        }
2455        return false;
2456    }
2457
2458    @Override
2459    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2460        if (!sUserManager.exists(userId)) return null;
2461        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2462        // reader
2463        synchronized (mPackages) {
2464            PackageParser.Package p = mPackages.get(packageName);
2465            if (DEBUG_PACKAGE_INFO)
2466                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2467            if (p != null) {
2468                return generatePackageInfo(p, flags, userId);
2469            }
2470            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2471                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2472            }
2473        }
2474        return null;
2475    }
2476
2477    @Override
2478    public String[] currentToCanonicalPackageNames(String[] names) {
2479        String[] out = new String[names.length];
2480        // reader
2481        synchronized (mPackages) {
2482            for (int i=names.length-1; i>=0; i--) {
2483                PackageSetting ps = mSettings.mPackages.get(names[i]);
2484                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2485            }
2486        }
2487        return out;
2488    }
2489
2490    @Override
2491    public String[] canonicalToCurrentPackageNames(String[] names) {
2492        String[] out = new String[names.length];
2493        // reader
2494        synchronized (mPackages) {
2495            for (int i=names.length-1; i>=0; i--) {
2496                String cur = mSettings.mRenamedPackages.get(names[i]);
2497                out[i] = cur != null ? cur : names[i];
2498            }
2499        }
2500        return out;
2501    }
2502
2503    @Override
2504    public int getPackageUid(String packageName, int userId) {
2505        if (!sUserManager.exists(userId)) return -1;
2506        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2507
2508        // reader
2509        synchronized (mPackages) {
2510            PackageParser.Package p = mPackages.get(packageName);
2511            if(p != null) {
2512                return UserHandle.getUid(userId, p.applicationInfo.uid);
2513            }
2514            PackageSetting ps = mSettings.mPackages.get(packageName);
2515            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2516                return -1;
2517            }
2518            p = ps.pkg;
2519            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2520        }
2521    }
2522
2523    @Override
2524    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2525        if (!sUserManager.exists(userId)) {
2526            return null;
2527        }
2528
2529        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2530                "getPackageGids");
2531
2532        // reader
2533        synchronized (mPackages) {
2534            PackageParser.Package p = mPackages.get(packageName);
2535            if (DEBUG_PACKAGE_INFO) {
2536                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2537            }
2538            if (p != null) {
2539                PackageSetting ps = (PackageSetting) p.mExtras;
2540                return ps.getPermissionsState().computeGids(userId);
2541            }
2542        }
2543
2544        return null;
2545    }
2546
2547    static PermissionInfo generatePermissionInfo(
2548            BasePermission bp, int flags) {
2549        if (bp.perm != null) {
2550            return PackageParser.generatePermissionInfo(bp.perm, flags);
2551        }
2552        PermissionInfo pi = new PermissionInfo();
2553        pi.name = bp.name;
2554        pi.packageName = bp.sourcePackage;
2555        pi.nonLocalizedLabel = bp.name;
2556        pi.protectionLevel = bp.protectionLevel;
2557        return pi;
2558    }
2559
2560    @Override
2561    public PermissionInfo getPermissionInfo(String name, int flags) {
2562        // reader
2563        synchronized (mPackages) {
2564            final BasePermission p = mSettings.mPermissions.get(name);
2565            if (p != null) {
2566                return generatePermissionInfo(p, flags);
2567            }
2568            return null;
2569        }
2570    }
2571
2572    @Override
2573    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2574        // reader
2575        synchronized (mPackages) {
2576            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2577            for (BasePermission p : mSettings.mPermissions.values()) {
2578                if (group == null) {
2579                    if (p.perm == null || p.perm.info.group == null) {
2580                        out.add(generatePermissionInfo(p, flags));
2581                    }
2582                } else {
2583                    if (p.perm != null && group.equals(p.perm.info.group)) {
2584                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2585                    }
2586                }
2587            }
2588
2589            if (out.size() > 0) {
2590                return out;
2591            }
2592            return mPermissionGroups.containsKey(group) ? out : null;
2593        }
2594    }
2595
2596    @Override
2597    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2598        // reader
2599        synchronized (mPackages) {
2600            return PackageParser.generatePermissionGroupInfo(
2601                    mPermissionGroups.get(name), flags);
2602        }
2603    }
2604
2605    @Override
2606    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2607        // reader
2608        synchronized (mPackages) {
2609            final int N = mPermissionGroups.size();
2610            ArrayList<PermissionGroupInfo> out
2611                    = new ArrayList<PermissionGroupInfo>(N);
2612            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2613                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2614            }
2615            return out;
2616        }
2617    }
2618
2619    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2620            int userId) {
2621        if (!sUserManager.exists(userId)) return null;
2622        PackageSetting ps = mSettings.mPackages.get(packageName);
2623        if (ps != null) {
2624            if (ps.pkg == null) {
2625                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2626                        flags, userId);
2627                if (pInfo != null) {
2628                    return pInfo.applicationInfo;
2629                }
2630                return null;
2631            }
2632            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2633                    ps.readUserState(userId), userId);
2634        }
2635        return null;
2636    }
2637
2638    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2639            int userId) {
2640        if (!sUserManager.exists(userId)) return null;
2641        PackageSetting ps = mSettings.mPackages.get(packageName);
2642        if (ps != null) {
2643            PackageParser.Package pkg = ps.pkg;
2644            if (pkg == null) {
2645                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2646                    return null;
2647                }
2648                // Only data remains, so we aren't worried about code paths
2649                pkg = new PackageParser.Package(packageName);
2650                pkg.applicationInfo.packageName = packageName;
2651                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2652                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2653                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2654                        packageName, userId).getAbsolutePath();
2655                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2656                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2657            }
2658            return generatePackageInfo(pkg, flags, userId);
2659        }
2660        return null;
2661    }
2662
2663    @Override
2664    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2665        if (!sUserManager.exists(userId)) return null;
2666        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2667        // writer
2668        synchronized (mPackages) {
2669            PackageParser.Package p = mPackages.get(packageName);
2670            if (DEBUG_PACKAGE_INFO) Log.v(
2671                    TAG, "getApplicationInfo " + packageName
2672                    + ": " + p);
2673            if (p != null) {
2674                PackageSetting ps = mSettings.mPackages.get(packageName);
2675                if (ps == null) return null;
2676                // Note: isEnabledLP() does not apply here - always return info
2677                return PackageParser.generateApplicationInfo(
2678                        p, flags, ps.readUserState(userId), userId);
2679            }
2680            if ("android".equals(packageName)||"system".equals(packageName)) {
2681                return mAndroidApplication;
2682            }
2683            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2684                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2685            }
2686        }
2687        return null;
2688    }
2689
2690    @Override
2691    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2692            final IPackageDataObserver observer) {
2693        mContext.enforceCallingOrSelfPermission(
2694                android.Manifest.permission.CLEAR_APP_CACHE, null);
2695        // Queue up an async operation since clearing cache may take a little while.
2696        mHandler.post(new Runnable() {
2697            public void run() {
2698                mHandler.removeCallbacks(this);
2699                int retCode = -1;
2700                synchronized (mInstallLock) {
2701                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2702                    if (retCode < 0) {
2703                        Slog.w(TAG, "Couldn't clear application caches");
2704                    }
2705                }
2706                if (observer != null) {
2707                    try {
2708                        observer.onRemoveCompleted(null, (retCode >= 0));
2709                    } catch (RemoteException e) {
2710                        Slog.w(TAG, "RemoveException when invoking call back");
2711                    }
2712                }
2713            }
2714        });
2715    }
2716
2717    @Override
2718    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2719            final IntentSender pi) {
2720        mContext.enforceCallingOrSelfPermission(
2721                android.Manifest.permission.CLEAR_APP_CACHE, null);
2722        // Queue up an async operation since clearing cache may take a little while.
2723        mHandler.post(new Runnable() {
2724            public void run() {
2725                mHandler.removeCallbacks(this);
2726                int retCode = -1;
2727                synchronized (mInstallLock) {
2728                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2729                    if (retCode < 0) {
2730                        Slog.w(TAG, "Couldn't clear application caches");
2731                    }
2732                }
2733                if(pi != null) {
2734                    try {
2735                        // Callback via pending intent
2736                        int code = (retCode >= 0) ? 1 : 0;
2737                        pi.sendIntent(null, code, null,
2738                                null, null);
2739                    } catch (SendIntentException e1) {
2740                        Slog.i(TAG, "Failed to send pending intent");
2741                    }
2742                }
2743            }
2744        });
2745    }
2746
2747    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2748        synchronized (mInstallLock) {
2749            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2750                throw new IOException("Failed to free enough space");
2751            }
2752        }
2753    }
2754
2755    @Override
2756    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2757        if (!sUserManager.exists(userId)) return null;
2758        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2759        synchronized (mPackages) {
2760            PackageParser.Activity a = mActivities.mActivities.get(component);
2761
2762            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2763            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2764                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2765                if (ps == null) return null;
2766                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2767                        userId);
2768            }
2769            if (mResolveComponentName.equals(component)) {
2770                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2771                        new PackageUserState(), userId);
2772            }
2773        }
2774        return null;
2775    }
2776
2777    @Override
2778    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2779            String resolvedType) {
2780        synchronized (mPackages) {
2781            PackageParser.Activity a = mActivities.mActivities.get(component);
2782            if (a == null) {
2783                return false;
2784            }
2785            for (int i=0; i<a.intents.size(); i++) {
2786                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2787                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2788                    return true;
2789                }
2790            }
2791            return false;
2792        }
2793    }
2794
2795    @Override
2796    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2797        if (!sUserManager.exists(userId)) return null;
2798        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2799        synchronized (mPackages) {
2800            PackageParser.Activity a = mReceivers.mActivities.get(component);
2801            if (DEBUG_PACKAGE_INFO) Log.v(
2802                TAG, "getReceiverInfo " + component + ": " + a);
2803            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2804                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2805                if (ps == null) return null;
2806                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2807                        userId);
2808            }
2809        }
2810        return null;
2811    }
2812
2813    @Override
2814    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2815        if (!sUserManager.exists(userId)) return null;
2816        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2817        synchronized (mPackages) {
2818            PackageParser.Service s = mServices.mServices.get(component);
2819            if (DEBUG_PACKAGE_INFO) Log.v(
2820                TAG, "getServiceInfo " + component + ": " + s);
2821            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2822                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2823                if (ps == null) return null;
2824                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2825                        userId);
2826            }
2827        }
2828        return null;
2829    }
2830
2831    @Override
2832    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2833        if (!sUserManager.exists(userId)) return null;
2834        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2835        synchronized (mPackages) {
2836            PackageParser.Provider p = mProviders.mProviders.get(component);
2837            if (DEBUG_PACKAGE_INFO) Log.v(
2838                TAG, "getProviderInfo " + component + ": " + p);
2839            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2840                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2841                if (ps == null) return null;
2842                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2843                        userId);
2844            }
2845        }
2846        return null;
2847    }
2848
2849    @Override
2850    public String[] getSystemSharedLibraryNames() {
2851        Set<String> libSet;
2852        synchronized (mPackages) {
2853            libSet = mSharedLibraries.keySet();
2854            int size = libSet.size();
2855            if (size > 0) {
2856                String[] libs = new String[size];
2857                libSet.toArray(libs);
2858                return libs;
2859            }
2860        }
2861        return null;
2862    }
2863
2864    /**
2865     * @hide
2866     */
2867    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2868        synchronized (mPackages) {
2869            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2870            if (lib != null && lib.apk != null) {
2871                return mPackages.get(lib.apk);
2872            }
2873        }
2874        return null;
2875    }
2876
2877    @Override
2878    public FeatureInfo[] getSystemAvailableFeatures() {
2879        Collection<FeatureInfo> featSet;
2880        synchronized (mPackages) {
2881            featSet = mAvailableFeatures.values();
2882            int size = featSet.size();
2883            if (size > 0) {
2884                FeatureInfo[] features = new FeatureInfo[size+1];
2885                featSet.toArray(features);
2886                FeatureInfo fi = new FeatureInfo();
2887                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2888                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2889                features[size] = fi;
2890                return features;
2891            }
2892        }
2893        return null;
2894    }
2895
2896    @Override
2897    public boolean hasSystemFeature(String name) {
2898        synchronized (mPackages) {
2899            return mAvailableFeatures.containsKey(name);
2900        }
2901    }
2902
2903    private void checkValidCaller(int uid, int userId) {
2904        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2905            return;
2906
2907        throw new SecurityException("Caller uid=" + uid
2908                + " is not privileged to communicate with user=" + userId);
2909    }
2910
2911    @Override
2912    public int checkPermission(String permName, String pkgName, int userId) {
2913        if (!sUserManager.exists(userId)) {
2914            return PackageManager.PERMISSION_DENIED;
2915        }
2916
2917        synchronized (mPackages) {
2918            final PackageParser.Package p = mPackages.get(pkgName);
2919            if (p != null && p.mExtras != null) {
2920                final PackageSetting ps = (PackageSetting) p.mExtras;
2921                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2922                    return PackageManager.PERMISSION_GRANTED;
2923                }
2924            }
2925        }
2926
2927        return PackageManager.PERMISSION_DENIED;
2928    }
2929
2930    @Override
2931    public int checkUidPermission(String permName, int uid) {
2932        final int userId = UserHandle.getUserId(uid);
2933
2934        if (!sUserManager.exists(userId)) {
2935            return PackageManager.PERMISSION_DENIED;
2936        }
2937
2938        synchronized (mPackages) {
2939            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2940            if (obj != null) {
2941                final SettingBase ps = (SettingBase) obj;
2942                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2943                    return PackageManager.PERMISSION_GRANTED;
2944                }
2945            } else {
2946                ArraySet<String> perms = mSystemPermissions.get(uid);
2947                if (perms != null && perms.contains(permName)) {
2948                    return PackageManager.PERMISSION_GRANTED;
2949                }
2950            }
2951        }
2952
2953        return PackageManager.PERMISSION_DENIED;
2954    }
2955
2956    /**
2957     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2958     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2959     * @param checkShell TODO(yamasani):
2960     * @param message the message to log on security exception
2961     */
2962    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2963            boolean checkShell, String message) {
2964        if (userId < 0) {
2965            throw new IllegalArgumentException("Invalid userId " + userId);
2966        }
2967        if (checkShell) {
2968            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2969        }
2970        if (userId == UserHandle.getUserId(callingUid)) return;
2971        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2972            if (requireFullPermission) {
2973                mContext.enforceCallingOrSelfPermission(
2974                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2975            } else {
2976                try {
2977                    mContext.enforceCallingOrSelfPermission(
2978                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2979                } catch (SecurityException se) {
2980                    mContext.enforceCallingOrSelfPermission(
2981                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2982                }
2983            }
2984        }
2985    }
2986
2987    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2988        if (callingUid == Process.SHELL_UID) {
2989            if (userHandle >= 0
2990                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2991                throw new SecurityException("Shell does not have permission to access user "
2992                        + userHandle);
2993            } else if (userHandle < 0) {
2994                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2995                        + Debug.getCallers(3));
2996            }
2997        }
2998    }
2999
3000    private BasePermission findPermissionTreeLP(String permName) {
3001        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3002            if (permName.startsWith(bp.name) &&
3003                    permName.length() > bp.name.length() &&
3004                    permName.charAt(bp.name.length()) == '.') {
3005                return bp;
3006            }
3007        }
3008        return null;
3009    }
3010
3011    private BasePermission checkPermissionTreeLP(String permName) {
3012        if (permName != null) {
3013            BasePermission bp = findPermissionTreeLP(permName);
3014            if (bp != null) {
3015                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3016                    return bp;
3017                }
3018                throw new SecurityException("Calling uid "
3019                        + Binder.getCallingUid()
3020                        + " is not allowed to add to permission tree "
3021                        + bp.name + " owned by uid " + bp.uid);
3022            }
3023        }
3024        throw new SecurityException("No permission tree found for " + permName);
3025    }
3026
3027    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3028        if (s1 == null) {
3029            return s2 == null;
3030        }
3031        if (s2 == null) {
3032            return false;
3033        }
3034        if (s1.getClass() != s2.getClass()) {
3035            return false;
3036        }
3037        return s1.equals(s2);
3038    }
3039
3040    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3041        if (pi1.icon != pi2.icon) return false;
3042        if (pi1.logo != pi2.logo) return false;
3043        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3044        if (!compareStrings(pi1.name, pi2.name)) return false;
3045        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3046        // We'll take care of setting this one.
3047        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3048        // These are not currently stored in settings.
3049        //if (!compareStrings(pi1.group, pi2.group)) return false;
3050        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3051        //if (pi1.labelRes != pi2.labelRes) return false;
3052        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3053        return true;
3054    }
3055
3056    int permissionInfoFootprint(PermissionInfo info) {
3057        int size = info.name.length();
3058        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3059        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3060        return size;
3061    }
3062
3063    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3064        int size = 0;
3065        for (BasePermission perm : mSettings.mPermissions.values()) {
3066            if (perm.uid == tree.uid) {
3067                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3068            }
3069        }
3070        return size;
3071    }
3072
3073    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3074        // We calculate the max size of permissions defined by this uid and throw
3075        // if that plus the size of 'info' would exceed our stated maximum.
3076        if (tree.uid != Process.SYSTEM_UID) {
3077            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3078            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3079                throw new SecurityException("Permission tree size cap exceeded");
3080            }
3081        }
3082    }
3083
3084    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3085        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3086            throw new SecurityException("Label must be specified in permission");
3087        }
3088        BasePermission tree = checkPermissionTreeLP(info.name);
3089        BasePermission bp = mSettings.mPermissions.get(info.name);
3090        boolean added = bp == null;
3091        boolean changed = true;
3092        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3093        if (added) {
3094            enforcePermissionCapLocked(info, tree);
3095            bp = new BasePermission(info.name, tree.sourcePackage,
3096                    BasePermission.TYPE_DYNAMIC);
3097        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3098            throw new SecurityException(
3099                    "Not allowed to modify non-dynamic permission "
3100                    + info.name);
3101        } else {
3102            if (bp.protectionLevel == fixedLevel
3103                    && bp.perm.owner.equals(tree.perm.owner)
3104                    && bp.uid == tree.uid
3105                    && comparePermissionInfos(bp.perm.info, info)) {
3106                changed = false;
3107            }
3108        }
3109        bp.protectionLevel = fixedLevel;
3110        info = new PermissionInfo(info);
3111        info.protectionLevel = fixedLevel;
3112        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3113        bp.perm.info.packageName = tree.perm.info.packageName;
3114        bp.uid = tree.uid;
3115        if (added) {
3116            mSettings.mPermissions.put(info.name, bp);
3117        }
3118        if (changed) {
3119            if (!async) {
3120                mSettings.writeLPr();
3121            } else {
3122                scheduleWriteSettingsLocked();
3123            }
3124        }
3125        return added;
3126    }
3127
3128    @Override
3129    public boolean addPermission(PermissionInfo info) {
3130        synchronized (mPackages) {
3131            return addPermissionLocked(info, false);
3132        }
3133    }
3134
3135    @Override
3136    public boolean addPermissionAsync(PermissionInfo info) {
3137        synchronized (mPackages) {
3138            return addPermissionLocked(info, true);
3139        }
3140    }
3141
3142    @Override
3143    public void removePermission(String name) {
3144        synchronized (mPackages) {
3145            checkPermissionTreeLP(name);
3146            BasePermission bp = mSettings.mPermissions.get(name);
3147            if (bp != null) {
3148                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3149                    throw new SecurityException(
3150                            "Not allowed to modify non-dynamic permission "
3151                            + name);
3152                }
3153                mSettings.mPermissions.remove(name);
3154                mSettings.writeLPr();
3155            }
3156        }
3157    }
3158
3159    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3160            BasePermission bp) {
3161        int index = pkg.requestedPermissions.indexOf(bp.name);
3162        if (index == -1) {
3163            throw new SecurityException("Package " + pkg.packageName
3164                    + " has not requested permission " + bp.name);
3165        }
3166        if (!bp.isRuntime()) {
3167            throw new SecurityException("Permission " + bp.name
3168                    + " is not a changeable permission type");
3169        }
3170    }
3171
3172    @Override
3173    public void grantRuntimePermission(String packageName, String name, final int userId) {
3174        if (!sUserManager.exists(userId)) {
3175            Log.e(TAG, "No such user:" + userId);
3176            return;
3177        }
3178
3179        mContext.enforceCallingOrSelfPermission(
3180                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3181                "grantRuntimePermission");
3182
3183        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3184                "grantRuntimePermission");
3185
3186        final SettingBase sb;
3187
3188        synchronized (mPackages) {
3189            final PackageParser.Package pkg = mPackages.get(packageName);
3190            if (pkg == null) {
3191                throw new IllegalArgumentException("Unknown package: " + packageName);
3192            }
3193
3194            final BasePermission bp = mSettings.mPermissions.get(name);
3195            if (bp == null) {
3196                throw new IllegalArgumentException("Unknown permission: " + name);
3197            }
3198
3199            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3200
3201            sb = (SettingBase) pkg.mExtras;
3202            if (sb == null) {
3203                throw new IllegalArgumentException("Unknown package: " + packageName);
3204            }
3205
3206            final PermissionsState permissionsState = sb.getPermissionsState();
3207
3208            final int flags = permissionsState.getPermissionFlags(name, userId);
3209            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3210                throw new SecurityException("Cannot grant system fixed permission: "
3211                        + name + " for package: " + packageName);
3212            }
3213
3214            final int result = permissionsState.grantRuntimePermission(bp, userId);
3215            switch (result) {
3216                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3217                    return;
3218                }
3219
3220                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3221                    mHandler.post(new Runnable() {
3222                        @Override
3223                        public void run() {
3224                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3225                        }
3226                    });
3227                } break;
3228            }
3229
3230            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3231
3232            // Not critical if that is lost - app has to request again.
3233            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3234        }
3235    }
3236
3237    @Override
3238    public void revokeRuntimePermission(String packageName, String name, int userId) {
3239        if (!sUserManager.exists(userId)) {
3240            Log.e(TAG, "No such user:" + userId);
3241            return;
3242        }
3243
3244        mContext.enforceCallingOrSelfPermission(
3245                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3246                "revokeRuntimePermission");
3247
3248        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3249                "revokeRuntimePermission");
3250
3251        final SettingBase sb;
3252
3253        synchronized (mPackages) {
3254            final PackageParser.Package pkg = mPackages.get(packageName);
3255            if (pkg == null) {
3256                throw new IllegalArgumentException("Unknown package: " + packageName);
3257            }
3258
3259            final BasePermission bp = mSettings.mPermissions.get(name);
3260            if (bp == null) {
3261                throw new IllegalArgumentException("Unknown permission: " + name);
3262            }
3263
3264            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3265
3266            sb = (SettingBase) pkg.mExtras;
3267            if (sb == null) {
3268                throw new IllegalArgumentException("Unknown package: " + packageName);
3269            }
3270
3271            final PermissionsState permissionsState = sb.getPermissionsState();
3272
3273            final int flags = permissionsState.getPermissionFlags(name, userId);
3274            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3275                throw new SecurityException("Cannot revoke system fixed permission: "
3276                        + name + " for package: " + packageName);
3277            }
3278
3279            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3280                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3281                return;
3282            }
3283
3284            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3285
3286            // Critical, after this call app should never have the permission.
3287            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3288        }
3289
3290        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3291    }
3292
3293    @Override
3294    public int getPermissionFlags(String name, String packageName, int userId) {
3295        if (!sUserManager.exists(userId)) {
3296            return 0;
3297        }
3298
3299        mContext.enforceCallingOrSelfPermission(
3300                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3301                "getPermissionFlags");
3302
3303        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3304                "getPermissionFlags");
3305
3306        synchronized (mPackages) {
3307            final PackageParser.Package pkg = mPackages.get(packageName);
3308            if (pkg == null) {
3309                throw new IllegalArgumentException("Unknown package: " + packageName);
3310            }
3311
3312            final BasePermission bp = mSettings.mPermissions.get(name);
3313            if (bp == null) {
3314                throw new IllegalArgumentException("Unknown permission: " + name);
3315            }
3316
3317            SettingBase sb = (SettingBase) pkg.mExtras;
3318            if (sb == null) {
3319                throw new IllegalArgumentException("Unknown package: " + packageName);
3320            }
3321
3322            PermissionsState permissionsState = sb.getPermissionsState();
3323            return permissionsState.getPermissionFlags(name, userId);
3324        }
3325    }
3326
3327    @Override
3328    public void updatePermissionFlags(String name, String packageName, int flagMask,
3329            int flagValues, int userId) {
3330        if (!sUserManager.exists(userId)) {
3331            return;
3332        }
3333
3334        mContext.enforceCallingOrSelfPermission(
3335                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3336                "updatePermissionFlags");
3337
3338        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3339                "updatePermissionFlags");
3340
3341        // Only the system can change policy and system fixed flags.
3342        if (getCallingUid() != Process.SYSTEM_UID) {
3343            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3344            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3345
3346            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3347            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3348        }
3349
3350        synchronized (mPackages) {
3351            final PackageParser.Package pkg = mPackages.get(packageName);
3352            if (pkg == null) {
3353                throw new IllegalArgumentException("Unknown package: " + packageName);
3354            }
3355
3356            final BasePermission bp = mSettings.mPermissions.get(name);
3357            if (bp == null) {
3358                throw new IllegalArgumentException("Unknown permission: " + name);
3359            }
3360
3361            SettingBase sb = (SettingBase) pkg.mExtras;
3362            if (sb == null) {
3363                throw new IllegalArgumentException("Unknown package: " + packageName);
3364            }
3365
3366            PermissionsState permissionsState = sb.getPermissionsState();
3367
3368            // Only the package manager can change flags for system component permissions.
3369            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3370            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3371                return;
3372            }
3373
3374            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3375                // Install and runtime permissions are stored in different places,
3376                // so figure out what permission changed and persist the change.
3377                if (permissionsState.getInstallPermissionState(name) != null) {
3378                    scheduleWriteSettingsLocked();
3379                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3380                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3381                }
3382            }
3383        }
3384    }
3385
3386    @Override
3387    public boolean shouldShowRequestPermissionRationale(String permissionName,
3388            String packageName, int userId) {
3389        if (UserHandle.getCallingUserId() != userId) {
3390            mContext.enforceCallingPermission(
3391                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3392                    "canShowRequestPermissionRationale for user " + userId);
3393        }
3394
3395        final int uid = getPackageUid(packageName, userId);
3396        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3397            return false;
3398        }
3399
3400        if (checkPermission(permissionName, packageName, userId)
3401                == PackageManager.PERMISSION_GRANTED) {
3402            return false;
3403        }
3404
3405        final int flags;
3406
3407        final long identity = Binder.clearCallingIdentity();
3408        try {
3409            flags = getPermissionFlags(permissionName,
3410                    packageName, userId);
3411        } finally {
3412            Binder.restoreCallingIdentity(identity);
3413        }
3414
3415        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3416                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3417                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3418
3419        if ((flags & fixedFlags) != 0) {
3420            return false;
3421        }
3422
3423        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3424    }
3425
3426    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3427        BasePermission bp = mSettings.mPermissions.get(permission);
3428        if (bp == null) {
3429            throw new SecurityException("Missing " + permission + " permission");
3430        }
3431
3432        SettingBase sb = (SettingBase) pkg.mExtras;
3433        PermissionsState permissionsState = sb.getPermissionsState();
3434
3435        if (permissionsState.grantInstallPermission(bp) !=
3436                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3437            scheduleWriteSettingsLocked();
3438        }
3439    }
3440
3441    @Override
3442    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3443        mContext.enforceCallingOrSelfPermission(
3444                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3445                "addOnPermissionsChangeListener");
3446
3447        synchronized (mPackages) {
3448            mOnPermissionChangeListeners.addListenerLocked(listener);
3449        }
3450    }
3451
3452    @Override
3453    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3454        synchronized (mPackages) {
3455            mOnPermissionChangeListeners.removeListenerLocked(listener);
3456        }
3457    }
3458
3459    @Override
3460    public boolean isProtectedBroadcast(String actionName) {
3461        synchronized (mPackages) {
3462            return mProtectedBroadcasts.contains(actionName);
3463        }
3464    }
3465
3466    @Override
3467    public int checkSignatures(String pkg1, String pkg2) {
3468        synchronized (mPackages) {
3469            final PackageParser.Package p1 = mPackages.get(pkg1);
3470            final PackageParser.Package p2 = mPackages.get(pkg2);
3471            if (p1 == null || p1.mExtras == null
3472                    || p2 == null || p2.mExtras == null) {
3473                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3474            }
3475            return compareSignatures(p1.mSignatures, p2.mSignatures);
3476        }
3477    }
3478
3479    @Override
3480    public int checkUidSignatures(int uid1, int uid2) {
3481        // Map to base uids.
3482        uid1 = UserHandle.getAppId(uid1);
3483        uid2 = UserHandle.getAppId(uid2);
3484        // reader
3485        synchronized (mPackages) {
3486            Signature[] s1;
3487            Signature[] s2;
3488            Object obj = mSettings.getUserIdLPr(uid1);
3489            if (obj != null) {
3490                if (obj instanceof SharedUserSetting) {
3491                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3492                } else if (obj instanceof PackageSetting) {
3493                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3494                } else {
3495                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3496                }
3497            } else {
3498                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3499            }
3500            obj = mSettings.getUserIdLPr(uid2);
3501            if (obj != null) {
3502                if (obj instanceof SharedUserSetting) {
3503                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3504                } else if (obj instanceof PackageSetting) {
3505                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3506                } else {
3507                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3508                }
3509            } else {
3510                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3511            }
3512            return compareSignatures(s1, s2);
3513        }
3514    }
3515
3516    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3517        final long identity = Binder.clearCallingIdentity();
3518        try {
3519            if (sb instanceof SharedUserSetting) {
3520                SharedUserSetting sus = (SharedUserSetting) sb;
3521                final int packageCount = sus.packages.size();
3522                for (int i = 0; i < packageCount; i++) {
3523                    PackageSetting susPs = sus.packages.valueAt(i);
3524                    if (userId == UserHandle.USER_ALL) {
3525                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3526                    } else {
3527                        final int uid = UserHandle.getUid(userId, susPs.appId);
3528                        killUid(uid, reason);
3529                    }
3530                }
3531            } else if (sb instanceof PackageSetting) {
3532                PackageSetting ps = (PackageSetting) sb;
3533                if (userId == UserHandle.USER_ALL) {
3534                    killApplication(ps.pkg.packageName, ps.appId, reason);
3535                } else {
3536                    final int uid = UserHandle.getUid(userId, ps.appId);
3537                    killUid(uid, reason);
3538                }
3539            }
3540        } finally {
3541            Binder.restoreCallingIdentity(identity);
3542        }
3543    }
3544
3545    private static void killUid(int uid, String reason) {
3546        IActivityManager am = ActivityManagerNative.getDefault();
3547        if (am != null) {
3548            try {
3549                am.killUid(uid, reason);
3550            } catch (RemoteException e) {
3551                /* ignore - same process */
3552            }
3553        }
3554    }
3555
3556    /**
3557     * Compares two sets of signatures. Returns:
3558     * <br />
3559     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3560     * <br />
3561     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3562     * <br />
3563     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3564     * <br />
3565     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3566     * <br />
3567     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3568     */
3569    static int compareSignatures(Signature[] s1, Signature[] s2) {
3570        if (s1 == null) {
3571            return s2 == null
3572                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3573                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3574        }
3575
3576        if (s2 == null) {
3577            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3578        }
3579
3580        if (s1.length != s2.length) {
3581            return PackageManager.SIGNATURE_NO_MATCH;
3582        }
3583
3584        // Since both signature sets are of size 1, we can compare without HashSets.
3585        if (s1.length == 1) {
3586            return s1[0].equals(s2[0]) ?
3587                    PackageManager.SIGNATURE_MATCH :
3588                    PackageManager.SIGNATURE_NO_MATCH;
3589        }
3590
3591        ArraySet<Signature> set1 = new ArraySet<Signature>();
3592        for (Signature sig : s1) {
3593            set1.add(sig);
3594        }
3595        ArraySet<Signature> set2 = new ArraySet<Signature>();
3596        for (Signature sig : s2) {
3597            set2.add(sig);
3598        }
3599        // Make sure s2 contains all signatures in s1.
3600        if (set1.equals(set2)) {
3601            return PackageManager.SIGNATURE_MATCH;
3602        }
3603        return PackageManager.SIGNATURE_NO_MATCH;
3604    }
3605
3606    /**
3607     * If the database version for this type of package (internal storage or
3608     * external storage) is less than the version where package signatures
3609     * were updated, return true.
3610     */
3611    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3612        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3613                DatabaseVersion.SIGNATURE_END_ENTITY))
3614                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3615                        DatabaseVersion.SIGNATURE_END_ENTITY));
3616    }
3617
3618    /**
3619     * Used for backward compatibility to make sure any packages with
3620     * certificate chains get upgraded to the new style. {@code existingSigs}
3621     * will be in the old format (since they were stored on disk from before the
3622     * system upgrade) and {@code scannedSigs} will be in the newer format.
3623     */
3624    private int compareSignaturesCompat(PackageSignatures existingSigs,
3625            PackageParser.Package scannedPkg) {
3626        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3627            return PackageManager.SIGNATURE_NO_MATCH;
3628        }
3629
3630        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3631        for (Signature sig : existingSigs.mSignatures) {
3632            existingSet.add(sig);
3633        }
3634        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3635        for (Signature sig : scannedPkg.mSignatures) {
3636            try {
3637                Signature[] chainSignatures = sig.getChainSignatures();
3638                for (Signature chainSig : chainSignatures) {
3639                    scannedCompatSet.add(chainSig);
3640                }
3641            } catch (CertificateEncodingException e) {
3642                scannedCompatSet.add(sig);
3643            }
3644        }
3645        /*
3646         * Make sure the expanded scanned set contains all signatures in the
3647         * existing one.
3648         */
3649        if (scannedCompatSet.equals(existingSet)) {
3650            // Migrate the old signatures to the new scheme.
3651            existingSigs.assignSignatures(scannedPkg.mSignatures);
3652            // The new KeySets will be re-added later in the scanning process.
3653            synchronized (mPackages) {
3654                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3655            }
3656            return PackageManager.SIGNATURE_MATCH;
3657        }
3658        return PackageManager.SIGNATURE_NO_MATCH;
3659    }
3660
3661    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3662        if (isExternal(scannedPkg)) {
3663            return mSettings.isExternalDatabaseVersionOlderThan(
3664                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3665        } else {
3666            return mSettings.isInternalDatabaseVersionOlderThan(
3667                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3668        }
3669    }
3670
3671    private int compareSignaturesRecover(PackageSignatures existingSigs,
3672            PackageParser.Package scannedPkg) {
3673        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3674            return PackageManager.SIGNATURE_NO_MATCH;
3675        }
3676
3677        String msg = null;
3678        try {
3679            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3680                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3681                        + scannedPkg.packageName);
3682                return PackageManager.SIGNATURE_MATCH;
3683            }
3684        } catch (CertificateException e) {
3685            msg = e.getMessage();
3686        }
3687
3688        logCriticalInfo(Log.INFO,
3689                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3690        return PackageManager.SIGNATURE_NO_MATCH;
3691    }
3692
3693    @Override
3694    public String[] getPackagesForUid(int uid) {
3695        uid = UserHandle.getAppId(uid);
3696        // reader
3697        synchronized (mPackages) {
3698            Object obj = mSettings.getUserIdLPr(uid);
3699            if (obj instanceof SharedUserSetting) {
3700                final SharedUserSetting sus = (SharedUserSetting) obj;
3701                final int N = sus.packages.size();
3702                final String[] res = new String[N];
3703                final Iterator<PackageSetting> it = sus.packages.iterator();
3704                int i = 0;
3705                while (it.hasNext()) {
3706                    res[i++] = it.next().name;
3707                }
3708                return res;
3709            } else if (obj instanceof PackageSetting) {
3710                final PackageSetting ps = (PackageSetting) obj;
3711                return new String[] { ps.name };
3712            }
3713        }
3714        return null;
3715    }
3716
3717    @Override
3718    public String getNameForUid(int uid) {
3719        // reader
3720        synchronized (mPackages) {
3721            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3722            if (obj instanceof SharedUserSetting) {
3723                final SharedUserSetting sus = (SharedUserSetting) obj;
3724                return sus.name + ":" + sus.userId;
3725            } else if (obj instanceof PackageSetting) {
3726                final PackageSetting ps = (PackageSetting) obj;
3727                return ps.name;
3728            }
3729        }
3730        return null;
3731    }
3732
3733    @Override
3734    public int getUidForSharedUser(String sharedUserName) {
3735        if(sharedUserName == null) {
3736            return -1;
3737        }
3738        // reader
3739        synchronized (mPackages) {
3740            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3741            if (suid == null) {
3742                return -1;
3743            }
3744            return suid.userId;
3745        }
3746    }
3747
3748    @Override
3749    public int getFlagsForUid(int uid) {
3750        synchronized (mPackages) {
3751            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3752            if (obj instanceof SharedUserSetting) {
3753                final SharedUserSetting sus = (SharedUserSetting) obj;
3754                return sus.pkgFlags;
3755            } else if (obj instanceof PackageSetting) {
3756                final PackageSetting ps = (PackageSetting) obj;
3757                return ps.pkgFlags;
3758            }
3759        }
3760        return 0;
3761    }
3762
3763    @Override
3764    public int getPrivateFlagsForUid(int uid) {
3765        synchronized (mPackages) {
3766            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3767            if (obj instanceof SharedUserSetting) {
3768                final SharedUserSetting sus = (SharedUserSetting) obj;
3769                return sus.pkgPrivateFlags;
3770            } else if (obj instanceof PackageSetting) {
3771                final PackageSetting ps = (PackageSetting) obj;
3772                return ps.pkgPrivateFlags;
3773            }
3774        }
3775        return 0;
3776    }
3777
3778    @Override
3779    public boolean isUidPrivileged(int uid) {
3780        uid = UserHandle.getAppId(uid);
3781        // reader
3782        synchronized (mPackages) {
3783            Object obj = mSettings.getUserIdLPr(uid);
3784            if (obj instanceof SharedUserSetting) {
3785                final SharedUserSetting sus = (SharedUserSetting) obj;
3786                final Iterator<PackageSetting> it = sus.packages.iterator();
3787                while (it.hasNext()) {
3788                    if (it.next().isPrivileged()) {
3789                        return true;
3790                    }
3791                }
3792            } else if (obj instanceof PackageSetting) {
3793                final PackageSetting ps = (PackageSetting) obj;
3794                return ps.isPrivileged();
3795            }
3796        }
3797        return false;
3798    }
3799
3800    @Override
3801    public String[] getAppOpPermissionPackages(String permissionName) {
3802        synchronized (mPackages) {
3803            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3804            if (pkgs == null) {
3805                return null;
3806            }
3807            return pkgs.toArray(new String[pkgs.size()]);
3808        }
3809    }
3810
3811    @Override
3812    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3813            int flags, int userId) {
3814        if (!sUserManager.exists(userId)) return null;
3815        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3816        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3817        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3818    }
3819
3820    @Override
3821    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3822            IntentFilter filter, int match, ComponentName activity) {
3823        final int userId = UserHandle.getCallingUserId();
3824        if (DEBUG_PREFERRED) {
3825            Log.v(TAG, "setLastChosenActivity intent=" + intent
3826                + " resolvedType=" + resolvedType
3827                + " flags=" + flags
3828                + " filter=" + filter
3829                + " match=" + match
3830                + " activity=" + activity);
3831            filter.dump(new PrintStreamPrinter(System.out), "    ");
3832        }
3833        intent.setComponent(null);
3834        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3835        // Find any earlier preferred or last chosen entries and nuke them
3836        findPreferredActivity(intent, resolvedType,
3837                flags, query, 0, false, true, false, userId);
3838        // Add the new activity as the last chosen for this filter
3839        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3840                "Setting last chosen");
3841    }
3842
3843    @Override
3844    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3845        final int userId = UserHandle.getCallingUserId();
3846        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3847        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3848        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3849                false, false, false, userId);
3850    }
3851
3852    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3853            int flags, List<ResolveInfo> query, int userId) {
3854        if (query != null) {
3855            final int N = query.size();
3856            if (N == 1) {
3857                return query.get(0);
3858            } else if (N > 1) {
3859                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3860                // If there is more than one activity with the same priority,
3861                // then let the user decide between them.
3862                ResolveInfo r0 = query.get(0);
3863                ResolveInfo r1 = query.get(1);
3864                if (DEBUG_INTENT_MATCHING || debug) {
3865                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3866                            + r1.activityInfo.name + "=" + r1.priority);
3867                }
3868                // If the first activity has a higher priority, or a different
3869                // default, then it is always desireable to pick it.
3870                if (r0.priority != r1.priority
3871                        || r0.preferredOrder != r1.preferredOrder
3872                        || r0.isDefault != r1.isDefault) {
3873                    return query.get(0);
3874                }
3875                // If we have saved a preference for a preferred activity for
3876                // this Intent, use that.
3877                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3878                        flags, query, r0.priority, true, false, debug, userId);
3879                if (ri != null) {
3880                    return ri;
3881                }
3882                if (userId != 0) {
3883                    ri = new ResolveInfo(mResolveInfo);
3884                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3885                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3886                            ri.activityInfo.applicationInfo);
3887                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3888                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3889                    return ri;
3890                }
3891                return mResolveInfo;
3892            }
3893        }
3894        return null;
3895    }
3896
3897    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3898            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3899        final int N = query.size();
3900        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3901                .get(userId);
3902        // Get the list of persistent preferred activities that handle the intent
3903        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3904        List<PersistentPreferredActivity> pprefs = ppir != null
3905                ? ppir.queryIntent(intent, resolvedType,
3906                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3907                : null;
3908        if (pprefs != null && pprefs.size() > 0) {
3909            final int M = pprefs.size();
3910            for (int i=0; i<M; i++) {
3911                final PersistentPreferredActivity ppa = pprefs.get(i);
3912                if (DEBUG_PREFERRED || debug) {
3913                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3914                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3915                            + "\n  component=" + ppa.mComponent);
3916                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3917                }
3918                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3919                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3920                if (DEBUG_PREFERRED || debug) {
3921                    Slog.v(TAG, "Found persistent preferred activity:");
3922                    if (ai != null) {
3923                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3924                    } else {
3925                        Slog.v(TAG, "  null");
3926                    }
3927                }
3928                if (ai == null) {
3929                    // This previously registered persistent preferred activity
3930                    // component is no longer known. Ignore it and do NOT remove it.
3931                    continue;
3932                }
3933                for (int j=0; j<N; j++) {
3934                    final ResolveInfo ri = query.get(j);
3935                    if (!ri.activityInfo.applicationInfo.packageName
3936                            .equals(ai.applicationInfo.packageName)) {
3937                        continue;
3938                    }
3939                    if (!ri.activityInfo.name.equals(ai.name)) {
3940                        continue;
3941                    }
3942                    //  Found a persistent preference that can handle the intent.
3943                    if (DEBUG_PREFERRED || debug) {
3944                        Slog.v(TAG, "Returning persistent preferred activity: " +
3945                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3946                    }
3947                    return ri;
3948                }
3949            }
3950        }
3951        return null;
3952    }
3953
3954    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3955            List<ResolveInfo> query, int priority, boolean always,
3956            boolean removeMatches, boolean debug, int userId) {
3957        if (!sUserManager.exists(userId)) return null;
3958        // writer
3959        synchronized (mPackages) {
3960            if (intent.getSelector() != null) {
3961                intent = intent.getSelector();
3962            }
3963            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3964
3965            // Try to find a matching persistent preferred activity.
3966            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3967                    debug, userId);
3968
3969            // If a persistent preferred activity matched, use it.
3970            if (pri != null) {
3971                return pri;
3972            }
3973
3974            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3975            // Get the list of preferred activities that handle the intent
3976            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3977            List<PreferredActivity> prefs = pir != null
3978                    ? pir.queryIntent(intent, resolvedType,
3979                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3980                    : null;
3981            if (prefs != null && prefs.size() > 0) {
3982                boolean changed = false;
3983                try {
3984                    // First figure out how good the original match set is.
3985                    // We will only allow preferred activities that came
3986                    // from the same match quality.
3987                    int match = 0;
3988
3989                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3990
3991                    final int N = query.size();
3992                    for (int j=0; j<N; j++) {
3993                        final ResolveInfo ri = query.get(j);
3994                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3995                                + ": 0x" + Integer.toHexString(match));
3996                        if (ri.match > match) {
3997                            match = ri.match;
3998                        }
3999                    }
4000
4001                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4002                            + Integer.toHexString(match));
4003
4004                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4005                    final int M = prefs.size();
4006                    for (int i=0; i<M; i++) {
4007                        final PreferredActivity pa = prefs.get(i);
4008                        if (DEBUG_PREFERRED || debug) {
4009                            Slog.v(TAG, "Checking PreferredActivity ds="
4010                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4011                                    + "\n  component=" + pa.mPref.mComponent);
4012                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4013                        }
4014                        if (pa.mPref.mMatch != match) {
4015                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4016                                    + Integer.toHexString(pa.mPref.mMatch));
4017                            continue;
4018                        }
4019                        // If it's not an "always" type preferred activity and that's what we're
4020                        // looking for, skip it.
4021                        if (always && !pa.mPref.mAlways) {
4022                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4023                            continue;
4024                        }
4025                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4026                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4027                        if (DEBUG_PREFERRED || debug) {
4028                            Slog.v(TAG, "Found preferred activity:");
4029                            if (ai != null) {
4030                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4031                            } else {
4032                                Slog.v(TAG, "  null");
4033                            }
4034                        }
4035                        if (ai == null) {
4036                            // This previously registered preferred activity
4037                            // component is no longer known.  Most likely an update
4038                            // to the app was installed and in the new version this
4039                            // component no longer exists.  Clean it up by removing
4040                            // it from the preferred activities list, and skip it.
4041                            Slog.w(TAG, "Removing dangling preferred activity: "
4042                                    + pa.mPref.mComponent);
4043                            pir.removeFilter(pa);
4044                            changed = true;
4045                            continue;
4046                        }
4047                        for (int j=0; j<N; j++) {
4048                            final ResolveInfo ri = query.get(j);
4049                            if (!ri.activityInfo.applicationInfo.packageName
4050                                    .equals(ai.applicationInfo.packageName)) {
4051                                continue;
4052                            }
4053                            if (!ri.activityInfo.name.equals(ai.name)) {
4054                                continue;
4055                            }
4056
4057                            if (removeMatches) {
4058                                pir.removeFilter(pa);
4059                                changed = true;
4060                                if (DEBUG_PREFERRED) {
4061                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4062                                }
4063                                break;
4064                            }
4065
4066                            // Okay we found a previously set preferred or last chosen app.
4067                            // If the result set is different from when this
4068                            // was created, we need to clear it and re-ask the
4069                            // user their preference, if we're looking for an "always" type entry.
4070                            if (always && !pa.mPref.sameSet(query)) {
4071                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4072                                        + intent + " type " + resolvedType);
4073                                if (DEBUG_PREFERRED) {
4074                                    Slog.v(TAG, "Removing preferred activity since set changed "
4075                                            + pa.mPref.mComponent);
4076                                }
4077                                pir.removeFilter(pa);
4078                                // Re-add the filter as a "last chosen" entry (!always)
4079                                PreferredActivity lastChosen = new PreferredActivity(
4080                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4081                                pir.addFilter(lastChosen);
4082                                changed = true;
4083                                return null;
4084                            }
4085
4086                            // Yay! Either the set matched or we're looking for the last chosen
4087                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4088                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4089                            return ri;
4090                        }
4091                    }
4092                } finally {
4093                    if (changed) {
4094                        if (DEBUG_PREFERRED) {
4095                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4096                        }
4097                        scheduleWritePackageRestrictionsLocked(userId);
4098                    }
4099                }
4100            }
4101        }
4102        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4103        return null;
4104    }
4105
4106    /*
4107     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4108     */
4109    @Override
4110    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4111            int targetUserId) {
4112        mContext.enforceCallingOrSelfPermission(
4113                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4114        List<CrossProfileIntentFilter> matches =
4115                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4116        if (matches != null) {
4117            int size = matches.size();
4118            for (int i = 0; i < size; i++) {
4119                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4120            }
4121        }
4122        if (hasWebURI(intent)) {
4123            // cross-profile app linking works only towards the parent.
4124            final UserInfo parent = getProfileParent(sourceUserId);
4125            synchronized(mPackages) {
4126                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4127                        parent.id) != null;
4128            }
4129        }
4130        return false;
4131    }
4132
4133    private UserInfo getProfileParent(int userId) {
4134        final long identity = Binder.clearCallingIdentity();
4135        try {
4136            return sUserManager.getProfileParent(userId);
4137        } finally {
4138            Binder.restoreCallingIdentity(identity);
4139        }
4140    }
4141
4142    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4143            String resolvedType, int userId) {
4144        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4145        if (resolver != null) {
4146            return resolver.queryIntent(intent, resolvedType, false, userId);
4147        }
4148        return null;
4149    }
4150
4151    @Override
4152    public List<ResolveInfo> queryIntentActivities(Intent intent,
4153            String resolvedType, int flags, int userId) {
4154        if (!sUserManager.exists(userId)) return Collections.emptyList();
4155        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4156        ComponentName comp = intent.getComponent();
4157        if (comp == null) {
4158            if (intent.getSelector() != null) {
4159                intent = intent.getSelector();
4160                comp = intent.getComponent();
4161            }
4162        }
4163
4164        if (comp != null) {
4165            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4166            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4167            if (ai != null) {
4168                final ResolveInfo ri = new ResolveInfo();
4169                ri.activityInfo = ai;
4170                list.add(ri);
4171            }
4172            return list;
4173        }
4174
4175        // reader
4176        synchronized (mPackages) {
4177            final String pkgName = intent.getPackage();
4178            if (pkgName == null) {
4179                List<CrossProfileIntentFilter> matchingFilters =
4180                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4181                // Check for results that need to skip the current profile.
4182                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4183                        resolvedType, flags, userId);
4184                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4185                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4186                    result.add(xpResolveInfo);
4187                    return filterIfNotPrimaryUser(result, userId);
4188                }
4189
4190                // Check for results in the current profile.
4191                List<ResolveInfo> result = mActivities.queryIntent(
4192                        intent, resolvedType, flags, userId);
4193
4194                // Check for cross profile results.
4195                xpResolveInfo = queryCrossProfileIntents(
4196                        matchingFilters, intent, resolvedType, flags, userId);
4197                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4198                    result.add(xpResolveInfo);
4199                    Collections.sort(result, mResolvePrioritySorter);
4200                }
4201                result = filterIfNotPrimaryUser(result, userId);
4202                if (hasWebURI(intent)) {
4203                    CrossProfileDomainInfo xpDomainInfo = null;
4204                    final UserInfo parent = getProfileParent(userId);
4205                    if (parent != null) {
4206                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4207                                flags, userId, parent.id);
4208                    }
4209                    if (xpDomainInfo != null) {
4210                        if (xpResolveInfo != null) {
4211                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4212                            // in the result.
4213                            result.remove(xpResolveInfo);
4214                        }
4215                        if (result.size() == 0) {
4216                            result.add(xpDomainInfo.resolveInfo);
4217                            return result;
4218                        }
4219                    } else if (result.size() <= 1) {
4220                        return result;
4221                    }
4222                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4223                            xpDomainInfo);
4224                    Collections.sort(result, mResolvePrioritySorter);
4225                }
4226                return result;
4227            }
4228            final PackageParser.Package pkg = mPackages.get(pkgName);
4229            if (pkg != null) {
4230                return filterIfNotPrimaryUser(
4231                        mActivities.queryIntentForPackage(
4232                                intent, resolvedType, flags, pkg.activities, userId),
4233                        userId);
4234            }
4235            return new ArrayList<ResolveInfo>();
4236        }
4237    }
4238
4239    private static class CrossProfileDomainInfo {
4240        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4241        ResolveInfo resolveInfo;
4242        /* Best domain verification status of the activities found in the other profile */
4243        int bestDomainVerificationStatus;
4244    }
4245
4246    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4247            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4248        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING,
4249                sourceUserId)) {
4250            return null;
4251        }
4252        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4253                resolvedType, flags, parentUserId);
4254
4255        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4256            return null;
4257        }
4258        CrossProfileDomainInfo result = null;
4259        int size = resultTargetUser.size();
4260        for (int i = 0; i < size; i++) {
4261            ResolveInfo riTargetUser = resultTargetUser.get(i);
4262            // Intent filter verification is only for filters that specify a host. So don't return
4263            // those that handle all web uris.
4264            if (riTargetUser.handleAllWebDataURI) {
4265                continue;
4266            }
4267            String packageName = riTargetUser.activityInfo.packageName;
4268            PackageSetting ps = mSettings.mPackages.get(packageName);
4269            if (ps == null) {
4270                continue;
4271            }
4272            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4273            if (result == null) {
4274                result = new CrossProfileDomainInfo();
4275                result.resolveInfo =
4276                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4277                result.bestDomainVerificationStatus = status;
4278            } else {
4279                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4280                        result.bestDomainVerificationStatus);
4281            }
4282        }
4283        return result;
4284    }
4285
4286    /**
4287     * Verification statuses are ordered from the worse to the best, except for
4288     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4289     */
4290    private int bestDomainVerificationStatus(int status1, int status2) {
4291        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4292            return status2;
4293        }
4294        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4295            return status1;
4296        }
4297        return (int) MathUtils.max(status1, status2);
4298    }
4299
4300    private boolean isUserEnabled(int userId) {
4301        long callingId = Binder.clearCallingIdentity();
4302        try {
4303            UserInfo userInfo = sUserManager.getUserInfo(userId);
4304            return userInfo != null && userInfo.isEnabled();
4305        } finally {
4306            Binder.restoreCallingIdentity(callingId);
4307        }
4308    }
4309
4310    /**
4311     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4312     *
4313     * @return filtered list
4314     */
4315    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4316        if (userId == UserHandle.USER_OWNER) {
4317            return resolveInfos;
4318        }
4319        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4320            ResolveInfo info = resolveInfos.get(i);
4321            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4322                resolveInfos.remove(i);
4323            }
4324        }
4325        return resolveInfos;
4326    }
4327
4328    private static boolean hasWebURI(Intent intent) {
4329        if (intent.getData() == null) {
4330            return false;
4331        }
4332        final String scheme = intent.getScheme();
4333        if (TextUtils.isEmpty(scheme)) {
4334            return false;
4335        }
4336        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4337    }
4338
4339    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4340            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4341        if (DEBUG_PREFERRED) {
4342            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4343                    candidates.size());
4344        }
4345
4346        final int userId = UserHandle.getCallingUserId();
4347        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4348        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4349        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4350        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4351        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4352
4353        synchronized (mPackages) {
4354            final int count = candidates.size();
4355            // First, try to use the domain prefered App. Partition the candidates into four lists:
4356            // one for the final results, one for the "do not use ever", one for "undefined status"
4357            // and finally one for "Browser App type".
4358            for (int n=0; n<count; n++) {
4359                ResolveInfo info = candidates.get(n);
4360                String packageName = info.activityInfo.packageName;
4361                PackageSetting ps = mSettings.mPackages.get(packageName);
4362                if (ps != null) {
4363                    // Add to the special match all list (Browser use case)
4364                    if (info.handleAllWebDataURI) {
4365                        matchAllList.add(info);
4366                        continue;
4367                    }
4368                    // Try to get the status from User settings first
4369                    int status = getDomainVerificationStatusLPr(ps, userId);
4370                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4371                        alwaysList.add(info);
4372                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4373                        neverList.add(info);
4374                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4375                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4376                        undefinedList.add(info);
4377                    }
4378                }
4379            }
4380            // First try to add the "always" resolution for the current user if there is any
4381            if (alwaysList.size() > 0) {
4382                result.addAll(alwaysList);
4383            // if there is an "always" for the parent user, add it.
4384            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4385                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4386                result.add(xpDomainInfo.resolveInfo);
4387            } else {
4388                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4389                result.addAll(undefinedList);
4390                if (xpDomainInfo != null && (
4391                        xpDomainInfo.bestDomainVerificationStatus
4392                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4393                        || xpDomainInfo.bestDomainVerificationStatus
4394                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4395                    result.add(xpDomainInfo.resolveInfo);
4396                }
4397                // Also add Browsers (all of them or only the default one)
4398                if ((flags & MATCH_ALL) != 0) {
4399                    result.addAll(matchAllList);
4400                } else {
4401                    // Try to add the Default Browser if we can
4402                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4403                            UserHandle.myUserId());
4404                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4405                        boolean defaultBrowserFound = false;
4406                        final int browserCount = matchAllList.size();
4407                        for (int n=0; n<browserCount; n++) {
4408                            ResolveInfo browser = matchAllList.get(n);
4409                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4410                                result.add(browser);
4411                                defaultBrowserFound = true;
4412                                break;
4413                            }
4414                        }
4415                        if (!defaultBrowserFound) {
4416                            result.addAll(matchAllList);
4417                        }
4418                    } else {
4419                        result.addAll(matchAllList);
4420                    }
4421                }
4422
4423                // If there is nothing selected, add all candidates and remove the ones that the User
4424                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4425                if (result.size() == 0) {
4426                    result.addAll(candidates);
4427                    result.removeAll(neverList);
4428                }
4429            }
4430        }
4431        if (DEBUG_PREFERRED) {
4432            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4433                    result.size());
4434        }
4435        return result;
4436    }
4437
4438    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4439        int status = ps.getDomainVerificationStatusForUser(userId);
4440        // if none available, get the master status
4441        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4442            if (ps.getIntentFilterVerificationInfo() != null) {
4443                status = ps.getIntentFilterVerificationInfo().getStatus();
4444            }
4445        }
4446        return status;
4447    }
4448
4449    private ResolveInfo querySkipCurrentProfileIntents(
4450            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4451            int flags, int sourceUserId) {
4452        if (matchingFilters != null) {
4453            int size = matchingFilters.size();
4454            for (int i = 0; i < size; i ++) {
4455                CrossProfileIntentFilter filter = matchingFilters.get(i);
4456                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4457                    // Checking if there are activities in the target user that can handle the
4458                    // intent.
4459                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4460                            flags, sourceUserId);
4461                    if (resolveInfo != null) {
4462                        return resolveInfo;
4463                    }
4464                }
4465            }
4466        }
4467        return null;
4468    }
4469
4470    // Return matching ResolveInfo if any for skip current profile intent filters.
4471    private ResolveInfo queryCrossProfileIntents(
4472            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4473            int flags, int sourceUserId) {
4474        if (matchingFilters != null) {
4475            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4476            // match the same intent. For performance reasons, it is better not to
4477            // run queryIntent twice for the same userId
4478            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4479            int size = matchingFilters.size();
4480            for (int i = 0; i < size; i++) {
4481                CrossProfileIntentFilter filter = matchingFilters.get(i);
4482                int targetUserId = filter.getTargetUserId();
4483                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4484                        && !alreadyTriedUserIds.get(targetUserId)) {
4485                    // Checking if there are activities in the target user that can handle the
4486                    // intent.
4487                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4488                            flags, sourceUserId);
4489                    if (resolveInfo != null) return resolveInfo;
4490                    alreadyTriedUserIds.put(targetUserId, true);
4491                }
4492            }
4493        }
4494        return null;
4495    }
4496
4497    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4498            String resolvedType, int flags, int sourceUserId) {
4499        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4500                resolvedType, flags, filter.getTargetUserId());
4501        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4502            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4503        }
4504        return null;
4505    }
4506
4507    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4508            int sourceUserId, int targetUserId) {
4509        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4510        String className;
4511        if (targetUserId == UserHandle.USER_OWNER) {
4512            className = FORWARD_INTENT_TO_USER_OWNER;
4513        } else {
4514            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4515        }
4516        ComponentName forwardingActivityComponentName = new ComponentName(
4517                mAndroidApplication.packageName, className);
4518        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4519                sourceUserId);
4520        if (targetUserId == UserHandle.USER_OWNER) {
4521            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4522            forwardingResolveInfo.noResourceId = true;
4523        }
4524        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4525        forwardingResolveInfo.priority = 0;
4526        forwardingResolveInfo.preferredOrder = 0;
4527        forwardingResolveInfo.match = 0;
4528        forwardingResolveInfo.isDefault = true;
4529        forwardingResolveInfo.filter = filter;
4530        forwardingResolveInfo.targetUserId = targetUserId;
4531        return forwardingResolveInfo;
4532    }
4533
4534    @Override
4535    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4536            Intent[] specifics, String[] specificTypes, Intent intent,
4537            String resolvedType, int flags, int userId) {
4538        if (!sUserManager.exists(userId)) return Collections.emptyList();
4539        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4540                false, "query intent activity options");
4541        final String resultsAction = intent.getAction();
4542
4543        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4544                | PackageManager.GET_RESOLVED_FILTER, userId);
4545
4546        if (DEBUG_INTENT_MATCHING) {
4547            Log.v(TAG, "Query " + intent + ": " + results);
4548        }
4549
4550        int specificsPos = 0;
4551        int N;
4552
4553        // todo: note that the algorithm used here is O(N^2).  This
4554        // isn't a problem in our current environment, but if we start running
4555        // into situations where we have more than 5 or 10 matches then this
4556        // should probably be changed to something smarter...
4557
4558        // First we go through and resolve each of the specific items
4559        // that were supplied, taking care of removing any corresponding
4560        // duplicate items in the generic resolve list.
4561        if (specifics != null) {
4562            for (int i=0; i<specifics.length; i++) {
4563                final Intent sintent = specifics[i];
4564                if (sintent == null) {
4565                    continue;
4566                }
4567
4568                if (DEBUG_INTENT_MATCHING) {
4569                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4570                }
4571
4572                String action = sintent.getAction();
4573                if (resultsAction != null && resultsAction.equals(action)) {
4574                    // If this action was explicitly requested, then don't
4575                    // remove things that have it.
4576                    action = null;
4577                }
4578
4579                ResolveInfo ri = null;
4580                ActivityInfo ai = null;
4581
4582                ComponentName comp = sintent.getComponent();
4583                if (comp == null) {
4584                    ri = resolveIntent(
4585                        sintent,
4586                        specificTypes != null ? specificTypes[i] : null,
4587                            flags, userId);
4588                    if (ri == null) {
4589                        continue;
4590                    }
4591                    if (ri == mResolveInfo) {
4592                        // ACK!  Must do something better with this.
4593                    }
4594                    ai = ri.activityInfo;
4595                    comp = new ComponentName(ai.applicationInfo.packageName,
4596                            ai.name);
4597                } else {
4598                    ai = getActivityInfo(comp, flags, userId);
4599                    if (ai == null) {
4600                        continue;
4601                    }
4602                }
4603
4604                // Look for any generic query activities that are duplicates
4605                // of this specific one, and remove them from the results.
4606                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4607                N = results.size();
4608                int j;
4609                for (j=specificsPos; j<N; j++) {
4610                    ResolveInfo sri = results.get(j);
4611                    if ((sri.activityInfo.name.equals(comp.getClassName())
4612                            && sri.activityInfo.applicationInfo.packageName.equals(
4613                                    comp.getPackageName()))
4614                        || (action != null && sri.filter.matchAction(action))) {
4615                        results.remove(j);
4616                        if (DEBUG_INTENT_MATCHING) Log.v(
4617                            TAG, "Removing duplicate item from " + j
4618                            + " due to specific " + specificsPos);
4619                        if (ri == null) {
4620                            ri = sri;
4621                        }
4622                        j--;
4623                        N--;
4624                    }
4625                }
4626
4627                // Add this specific item to its proper place.
4628                if (ri == null) {
4629                    ri = new ResolveInfo();
4630                    ri.activityInfo = ai;
4631                }
4632                results.add(specificsPos, ri);
4633                ri.specificIndex = i;
4634                specificsPos++;
4635            }
4636        }
4637
4638        // Now we go through the remaining generic results and remove any
4639        // duplicate actions that are found here.
4640        N = results.size();
4641        for (int i=specificsPos; i<N-1; i++) {
4642            final ResolveInfo rii = results.get(i);
4643            if (rii.filter == null) {
4644                continue;
4645            }
4646
4647            // Iterate over all of the actions of this result's intent
4648            // filter...  typically this should be just one.
4649            final Iterator<String> it = rii.filter.actionsIterator();
4650            if (it == null) {
4651                continue;
4652            }
4653            while (it.hasNext()) {
4654                final String action = it.next();
4655                if (resultsAction != null && resultsAction.equals(action)) {
4656                    // If this action was explicitly requested, then don't
4657                    // remove things that have it.
4658                    continue;
4659                }
4660                for (int j=i+1; j<N; j++) {
4661                    final ResolveInfo rij = results.get(j);
4662                    if (rij.filter != null && rij.filter.hasAction(action)) {
4663                        results.remove(j);
4664                        if (DEBUG_INTENT_MATCHING) Log.v(
4665                            TAG, "Removing duplicate item from " + j
4666                            + " due to action " + action + " at " + i);
4667                        j--;
4668                        N--;
4669                    }
4670                }
4671            }
4672
4673            // If the caller didn't request filter information, drop it now
4674            // so we don't have to marshall/unmarshall it.
4675            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4676                rii.filter = null;
4677            }
4678        }
4679
4680        // Filter out the caller activity if so requested.
4681        if (caller != null) {
4682            N = results.size();
4683            for (int i=0; i<N; i++) {
4684                ActivityInfo ainfo = results.get(i).activityInfo;
4685                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4686                        && caller.getClassName().equals(ainfo.name)) {
4687                    results.remove(i);
4688                    break;
4689                }
4690            }
4691        }
4692
4693        // If the caller didn't request filter information,
4694        // drop them now so we don't have to
4695        // marshall/unmarshall it.
4696        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4697            N = results.size();
4698            for (int i=0; i<N; i++) {
4699                results.get(i).filter = null;
4700            }
4701        }
4702
4703        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4704        return results;
4705    }
4706
4707    @Override
4708    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4709            int userId) {
4710        if (!sUserManager.exists(userId)) return Collections.emptyList();
4711        ComponentName comp = intent.getComponent();
4712        if (comp == null) {
4713            if (intent.getSelector() != null) {
4714                intent = intent.getSelector();
4715                comp = intent.getComponent();
4716            }
4717        }
4718        if (comp != null) {
4719            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4720            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4721            if (ai != null) {
4722                ResolveInfo ri = new ResolveInfo();
4723                ri.activityInfo = ai;
4724                list.add(ri);
4725            }
4726            return list;
4727        }
4728
4729        // reader
4730        synchronized (mPackages) {
4731            String pkgName = intent.getPackage();
4732            if (pkgName == null) {
4733                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4734            }
4735            final PackageParser.Package pkg = mPackages.get(pkgName);
4736            if (pkg != null) {
4737                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4738                        userId);
4739            }
4740            return null;
4741        }
4742    }
4743
4744    @Override
4745    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4746        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4747        if (!sUserManager.exists(userId)) return null;
4748        if (query != null) {
4749            if (query.size() >= 1) {
4750                // If there is more than one service with the same priority,
4751                // just arbitrarily pick the first one.
4752                return query.get(0);
4753            }
4754        }
4755        return null;
4756    }
4757
4758    @Override
4759    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4760            int userId) {
4761        if (!sUserManager.exists(userId)) return Collections.emptyList();
4762        ComponentName comp = intent.getComponent();
4763        if (comp == null) {
4764            if (intent.getSelector() != null) {
4765                intent = intent.getSelector();
4766                comp = intent.getComponent();
4767            }
4768        }
4769        if (comp != null) {
4770            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4771            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4772            if (si != null) {
4773                final ResolveInfo ri = new ResolveInfo();
4774                ri.serviceInfo = si;
4775                list.add(ri);
4776            }
4777            return list;
4778        }
4779
4780        // reader
4781        synchronized (mPackages) {
4782            String pkgName = intent.getPackage();
4783            if (pkgName == null) {
4784                return mServices.queryIntent(intent, resolvedType, flags, userId);
4785            }
4786            final PackageParser.Package pkg = mPackages.get(pkgName);
4787            if (pkg != null) {
4788                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4789                        userId);
4790            }
4791            return null;
4792        }
4793    }
4794
4795    @Override
4796    public List<ResolveInfo> queryIntentContentProviders(
4797            Intent intent, String resolvedType, int flags, int userId) {
4798        if (!sUserManager.exists(userId)) return Collections.emptyList();
4799        ComponentName comp = intent.getComponent();
4800        if (comp == null) {
4801            if (intent.getSelector() != null) {
4802                intent = intent.getSelector();
4803                comp = intent.getComponent();
4804            }
4805        }
4806        if (comp != null) {
4807            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4808            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4809            if (pi != null) {
4810                final ResolveInfo ri = new ResolveInfo();
4811                ri.providerInfo = pi;
4812                list.add(ri);
4813            }
4814            return list;
4815        }
4816
4817        // reader
4818        synchronized (mPackages) {
4819            String pkgName = intent.getPackage();
4820            if (pkgName == null) {
4821                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4822            }
4823            final PackageParser.Package pkg = mPackages.get(pkgName);
4824            if (pkg != null) {
4825                return mProviders.queryIntentForPackage(
4826                        intent, resolvedType, flags, pkg.providers, userId);
4827            }
4828            return null;
4829        }
4830    }
4831
4832    @Override
4833    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4834        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4835
4836        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4837
4838        // writer
4839        synchronized (mPackages) {
4840            ArrayList<PackageInfo> list;
4841            if (listUninstalled) {
4842                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4843                for (PackageSetting ps : mSettings.mPackages.values()) {
4844                    PackageInfo pi;
4845                    if (ps.pkg != null) {
4846                        pi = generatePackageInfo(ps.pkg, flags, userId);
4847                    } else {
4848                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4849                    }
4850                    if (pi != null) {
4851                        list.add(pi);
4852                    }
4853                }
4854            } else {
4855                list = new ArrayList<PackageInfo>(mPackages.size());
4856                for (PackageParser.Package p : mPackages.values()) {
4857                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4858                    if (pi != null) {
4859                        list.add(pi);
4860                    }
4861                }
4862            }
4863
4864            return new ParceledListSlice<PackageInfo>(list);
4865        }
4866    }
4867
4868    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4869            String[] permissions, boolean[] tmp, int flags, int userId) {
4870        int numMatch = 0;
4871        final PermissionsState permissionsState = ps.getPermissionsState();
4872        for (int i=0; i<permissions.length; i++) {
4873            final String permission = permissions[i];
4874            if (permissionsState.hasPermission(permission, userId)) {
4875                tmp[i] = true;
4876                numMatch++;
4877            } else {
4878                tmp[i] = false;
4879            }
4880        }
4881        if (numMatch == 0) {
4882            return;
4883        }
4884        PackageInfo pi;
4885        if (ps.pkg != null) {
4886            pi = generatePackageInfo(ps.pkg, flags, userId);
4887        } else {
4888            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4889        }
4890        // The above might return null in cases of uninstalled apps or install-state
4891        // skew across users/profiles.
4892        if (pi != null) {
4893            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4894                if (numMatch == permissions.length) {
4895                    pi.requestedPermissions = permissions;
4896                } else {
4897                    pi.requestedPermissions = new String[numMatch];
4898                    numMatch = 0;
4899                    for (int i=0; i<permissions.length; i++) {
4900                        if (tmp[i]) {
4901                            pi.requestedPermissions[numMatch] = permissions[i];
4902                            numMatch++;
4903                        }
4904                    }
4905                }
4906            }
4907            list.add(pi);
4908        }
4909    }
4910
4911    @Override
4912    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4913            String[] permissions, int flags, int userId) {
4914        if (!sUserManager.exists(userId)) return null;
4915        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4916
4917        // writer
4918        synchronized (mPackages) {
4919            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4920            boolean[] tmpBools = new boolean[permissions.length];
4921            if (listUninstalled) {
4922                for (PackageSetting ps : mSettings.mPackages.values()) {
4923                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4924                }
4925            } else {
4926                for (PackageParser.Package pkg : mPackages.values()) {
4927                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4928                    if (ps != null) {
4929                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4930                                userId);
4931                    }
4932                }
4933            }
4934
4935            return new ParceledListSlice<PackageInfo>(list);
4936        }
4937    }
4938
4939    @Override
4940    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4941        if (!sUserManager.exists(userId)) return null;
4942        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4943
4944        // writer
4945        synchronized (mPackages) {
4946            ArrayList<ApplicationInfo> list;
4947            if (listUninstalled) {
4948                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4949                for (PackageSetting ps : mSettings.mPackages.values()) {
4950                    ApplicationInfo ai;
4951                    if (ps.pkg != null) {
4952                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4953                                ps.readUserState(userId), userId);
4954                    } else {
4955                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4956                    }
4957                    if (ai != null) {
4958                        list.add(ai);
4959                    }
4960                }
4961            } else {
4962                list = new ArrayList<ApplicationInfo>(mPackages.size());
4963                for (PackageParser.Package p : mPackages.values()) {
4964                    if (p.mExtras != null) {
4965                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4966                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4967                        if (ai != null) {
4968                            list.add(ai);
4969                        }
4970                    }
4971                }
4972            }
4973
4974            return new ParceledListSlice<ApplicationInfo>(list);
4975        }
4976    }
4977
4978    public List<ApplicationInfo> getPersistentApplications(int flags) {
4979        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4980
4981        // reader
4982        synchronized (mPackages) {
4983            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4984            final int userId = UserHandle.getCallingUserId();
4985            while (i.hasNext()) {
4986                final PackageParser.Package p = i.next();
4987                if (p.applicationInfo != null
4988                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4989                        && (!mSafeMode || isSystemApp(p))) {
4990                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4991                    if (ps != null) {
4992                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4993                                ps.readUserState(userId), userId);
4994                        if (ai != null) {
4995                            finalList.add(ai);
4996                        }
4997                    }
4998                }
4999            }
5000        }
5001
5002        return finalList;
5003    }
5004
5005    @Override
5006    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5007        if (!sUserManager.exists(userId)) return null;
5008        // reader
5009        synchronized (mPackages) {
5010            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5011            PackageSetting ps = provider != null
5012                    ? mSettings.mPackages.get(provider.owner.packageName)
5013                    : null;
5014            return ps != null
5015                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5016                    && (!mSafeMode || (provider.info.applicationInfo.flags
5017                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5018                    ? PackageParser.generateProviderInfo(provider, flags,
5019                            ps.readUserState(userId), userId)
5020                    : null;
5021        }
5022    }
5023
5024    /**
5025     * @deprecated
5026     */
5027    @Deprecated
5028    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5029        // reader
5030        synchronized (mPackages) {
5031            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5032                    .entrySet().iterator();
5033            final int userId = UserHandle.getCallingUserId();
5034            while (i.hasNext()) {
5035                Map.Entry<String, PackageParser.Provider> entry = i.next();
5036                PackageParser.Provider p = entry.getValue();
5037                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5038
5039                if (ps != null && p.syncable
5040                        && (!mSafeMode || (p.info.applicationInfo.flags
5041                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5042                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5043                            ps.readUserState(userId), userId);
5044                    if (info != null) {
5045                        outNames.add(entry.getKey());
5046                        outInfo.add(info);
5047                    }
5048                }
5049            }
5050        }
5051    }
5052
5053    @Override
5054    public List<ProviderInfo> queryContentProviders(String processName,
5055            int uid, int flags) {
5056        ArrayList<ProviderInfo> finalList = null;
5057        // reader
5058        synchronized (mPackages) {
5059            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5060            final int userId = processName != null ?
5061                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5062            while (i.hasNext()) {
5063                final PackageParser.Provider p = i.next();
5064                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5065                if (ps != null && p.info.authority != null
5066                        && (processName == null
5067                                || (p.info.processName.equals(processName)
5068                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5069                        && mSettings.isEnabledLPr(p.info, flags, userId)
5070                        && (!mSafeMode
5071                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5072                    if (finalList == null) {
5073                        finalList = new ArrayList<ProviderInfo>(3);
5074                    }
5075                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5076                            ps.readUserState(userId), userId);
5077                    if (info != null) {
5078                        finalList.add(info);
5079                    }
5080                }
5081            }
5082        }
5083
5084        if (finalList != null) {
5085            Collections.sort(finalList, mProviderInitOrderSorter);
5086        }
5087
5088        return finalList;
5089    }
5090
5091    @Override
5092    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5093            int flags) {
5094        // reader
5095        synchronized (mPackages) {
5096            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5097            return PackageParser.generateInstrumentationInfo(i, flags);
5098        }
5099    }
5100
5101    @Override
5102    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5103            int flags) {
5104        ArrayList<InstrumentationInfo> finalList =
5105            new ArrayList<InstrumentationInfo>();
5106
5107        // reader
5108        synchronized (mPackages) {
5109            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5110            while (i.hasNext()) {
5111                final PackageParser.Instrumentation p = i.next();
5112                if (targetPackage == null
5113                        || targetPackage.equals(p.info.targetPackage)) {
5114                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5115                            flags);
5116                    if (ii != null) {
5117                        finalList.add(ii);
5118                    }
5119                }
5120            }
5121        }
5122
5123        return finalList;
5124    }
5125
5126    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5127        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5128        if (overlays == null) {
5129            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5130            return;
5131        }
5132        for (PackageParser.Package opkg : overlays.values()) {
5133            // Not much to do if idmap fails: we already logged the error
5134            // and we certainly don't want to abort installation of pkg simply
5135            // because an overlay didn't fit properly. For these reasons,
5136            // ignore the return value of createIdmapForPackagePairLI.
5137            createIdmapForPackagePairLI(pkg, opkg);
5138        }
5139    }
5140
5141    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5142            PackageParser.Package opkg) {
5143        if (!opkg.mTrustedOverlay) {
5144            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5145                    opkg.baseCodePath + ": overlay not trusted");
5146            return false;
5147        }
5148        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5149        if (overlaySet == null) {
5150            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5151                    opkg.baseCodePath + " but target package has no known overlays");
5152            return false;
5153        }
5154        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5155        // TODO: generate idmap for split APKs
5156        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5157            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5158                    + opkg.baseCodePath);
5159            return false;
5160        }
5161        PackageParser.Package[] overlayArray =
5162            overlaySet.values().toArray(new PackageParser.Package[0]);
5163        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5164            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5165                return p1.mOverlayPriority - p2.mOverlayPriority;
5166            }
5167        };
5168        Arrays.sort(overlayArray, cmp);
5169
5170        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5171        int i = 0;
5172        for (PackageParser.Package p : overlayArray) {
5173            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5174        }
5175        return true;
5176    }
5177
5178    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5179        final File[] files = dir.listFiles();
5180        if (ArrayUtils.isEmpty(files)) {
5181            Log.d(TAG, "No files in app dir " + dir);
5182            return;
5183        }
5184
5185        if (DEBUG_PACKAGE_SCANNING) {
5186            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5187                    + " flags=0x" + Integer.toHexString(parseFlags));
5188        }
5189
5190        for (File file : files) {
5191            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5192                    && !PackageInstallerService.isStageName(file.getName());
5193            if (!isPackage) {
5194                // Ignore entries which are not packages
5195                continue;
5196            }
5197            try {
5198                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5199                        scanFlags, currentTime, null);
5200            } catch (PackageManagerException e) {
5201                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5202
5203                // Delete invalid userdata apps
5204                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5205                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5206                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5207                    if (file.isDirectory()) {
5208                        mInstaller.rmPackageDir(file.getAbsolutePath());
5209                    } else {
5210                        file.delete();
5211                    }
5212                }
5213            }
5214        }
5215    }
5216
5217    private static File getSettingsProblemFile() {
5218        File dataDir = Environment.getDataDirectory();
5219        File systemDir = new File(dataDir, "system");
5220        File fname = new File(systemDir, "uiderrors.txt");
5221        return fname;
5222    }
5223
5224    static void reportSettingsProblem(int priority, String msg) {
5225        logCriticalInfo(priority, msg);
5226    }
5227
5228    static void logCriticalInfo(int priority, String msg) {
5229        Slog.println(priority, TAG, msg);
5230        EventLogTags.writePmCriticalInfo(msg);
5231        try {
5232            File fname = getSettingsProblemFile();
5233            FileOutputStream out = new FileOutputStream(fname, true);
5234            PrintWriter pw = new FastPrintWriter(out);
5235            SimpleDateFormat formatter = new SimpleDateFormat();
5236            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5237            pw.println(dateString + ": " + msg);
5238            pw.close();
5239            FileUtils.setPermissions(
5240                    fname.toString(),
5241                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5242                    -1, -1);
5243        } catch (java.io.IOException e) {
5244        }
5245    }
5246
5247    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5248            PackageParser.Package pkg, File srcFile, int parseFlags)
5249            throws PackageManagerException {
5250        if (ps != null
5251                && ps.codePath.equals(srcFile)
5252                && ps.timeStamp == srcFile.lastModified()
5253                && !isCompatSignatureUpdateNeeded(pkg)
5254                && !isRecoverSignatureUpdateNeeded(pkg)) {
5255            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5256            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5257            ArraySet<PublicKey> signingKs;
5258            synchronized (mPackages) {
5259                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5260            }
5261            if (ps.signatures.mSignatures != null
5262                    && ps.signatures.mSignatures.length != 0
5263                    && signingKs != null) {
5264                // Optimization: reuse the existing cached certificates
5265                // if the package appears to be unchanged.
5266                pkg.mSignatures = ps.signatures.mSignatures;
5267                pkg.mSigningKeys = signingKs;
5268                return;
5269            }
5270
5271            Slog.w(TAG, "PackageSetting for " + ps.name
5272                    + " is missing signatures.  Collecting certs again to recover them.");
5273        } else {
5274            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5275        }
5276
5277        try {
5278            pp.collectCertificates(pkg, parseFlags);
5279            pp.collectManifestDigest(pkg);
5280        } catch (PackageParserException e) {
5281            throw PackageManagerException.from(e);
5282        }
5283    }
5284
5285    /*
5286     *  Scan a package and return the newly parsed package.
5287     *  Returns null in case of errors and the error code is stored in mLastScanError
5288     */
5289    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5290            long currentTime, UserHandle user) throws PackageManagerException {
5291        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5292        parseFlags |= mDefParseFlags;
5293        PackageParser pp = new PackageParser();
5294        pp.setSeparateProcesses(mSeparateProcesses);
5295        pp.setOnlyCoreApps(mOnlyCore);
5296        pp.setDisplayMetrics(mMetrics);
5297
5298        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5299            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5300        }
5301
5302        final PackageParser.Package pkg;
5303        try {
5304            pkg = pp.parsePackage(scanFile, parseFlags);
5305        } catch (PackageParserException e) {
5306            throw PackageManagerException.from(e);
5307        }
5308
5309        PackageSetting ps = null;
5310        PackageSetting updatedPkg;
5311        // reader
5312        synchronized (mPackages) {
5313            // Look to see if we already know about this package.
5314            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5315            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5316                // This package has been renamed to its original name.  Let's
5317                // use that.
5318                ps = mSettings.peekPackageLPr(oldName);
5319            }
5320            // If there was no original package, see one for the real package name.
5321            if (ps == null) {
5322                ps = mSettings.peekPackageLPr(pkg.packageName);
5323            }
5324            // Check to see if this package could be hiding/updating a system
5325            // package.  Must look for it either under the original or real
5326            // package name depending on our state.
5327            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5328            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5329        }
5330        boolean updatedPkgBetter = false;
5331        // First check if this is a system package that may involve an update
5332        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5333            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5334            // it needs to drop FLAG_PRIVILEGED.
5335            if (locationIsPrivileged(scanFile)) {
5336                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5337            } else {
5338                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5339            }
5340
5341            if (ps != null && !ps.codePath.equals(scanFile)) {
5342                // The path has changed from what was last scanned...  check the
5343                // version of the new path against what we have stored to determine
5344                // what to do.
5345                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5346                if (pkg.mVersionCode <= ps.versionCode) {
5347                    // The system package has been updated and the code path does not match
5348                    // Ignore entry. Skip it.
5349                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5350                            + " ignored: updated version " + ps.versionCode
5351                            + " better than this " + pkg.mVersionCode);
5352                    if (!updatedPkg.codePath.equals(scanFile)) {
5353                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5354                                + ps.name + " changing from " + updatedPkg.codePathString
5355                                + " to " + scanFile);
5356                        updatedPkg.codePath = scanFile;
5357                        updatedPkg.codePathString = scanFile.toString();
5358                        updatedPkg.resourcePath = scanFile;
5359                        updatedPkg.resourcePathString = scanFile.toString();
5360                    }
5361                    updatedPkg.pkg = pkg;
5362                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5363                } else {
5364                    // The current app on the system partition is better than
5365                    // what we have updated to on the data partition; switch
5366                    // back to the system partition version.
5367                    // At this point, its safely assumed that package installation for
5368                    // apps in system partition will go through. If not there won't be a working
5369                    // version of the app
5370                    // writer
5371                    synchronized (mPackages) {
5372                        // Just remove the loaded entries from package lists.
5373                        mPackages.remove(ps.name);
5374                    }
5375
5376                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5377                            + " reverting from " + ps.codePathString
5378                            + ": new version " + pkg.mVersionCode
5379                            + " better than installed " + ps.versionCode);
5380
5381                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5382                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5383                    synchronized (mInstallLock) {
5384                        args.cleanUpResourcesLI();
5385                    }
5386                    synchronized (mPackages) {
5387                        mSettings.enableSystemPackageLPw(ps.name);
5388                    }
5389                    updatedPkgBetter = true;
5390                }
5391            }
5392        }
5393
5394        if (updatedPkg != null) {
5395            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5396            // initially
5397            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5398
5399            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5400            // flag set initially
5401            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5402                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5403            }
5404        }
5405
5406        // Verify certificates against what was last scanned
5407        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5408
5409        /*
5410         * A new system app appeared, but we already had a non-system one of the
5411         * same name installed earlier.
5412         */
5413        boolean shouldHideSystemApp = false;
5414        if (updatedPkg == null && ps != null
5415                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5416            /*
5417             * Check to make sure the signatures match first. If they don't,
5418             * wipe the installed application and its data.
5419             */
5420            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5421                    != PackageManager.SIGNATURE_MATCH) {
5422                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5423                        + " signatures don't match existing userdata copy; removing");
5424                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5425                ps = null;
5426            } else {
5427                /*
5428                 * If the newly-added system app is an older version than the
5429                 * already installed version, hide it. It will be scanned later
5430                 * and re-added like an update.
5431                 */
5432                if (pkg.mVersionCode <= ps.versionCode) {
5433                    shouldHideSystemApp = true;
5434                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5435                            + " but new version " + pkg.mVersionCode + " better than installed "
5436                            + ps.versionCode + "; hiding system");
5437                } else {
5438                    /*
5439                     * The newly found system app is a newer version that the
5440                     * one previously installed. Simply remove the
5441                     * already-installed application and replace it with our own
5442                     * while keeping the application data.
5443                     */
5444                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5445                            + " reverting from " + ps.codePathString + ": new version "
5446                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5447                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5448                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5449                    synchronized (mInstallLock) {
5450                        args.cleanUpResourcesLI();
5451                    }
5452                }
5453            }
5454        }
5455
5456        // The apk is forward locked (not public) if its code and resources
5457        // are kept in different files. (except for app in either system or
5458        // vendor path).
5459        // TODO grab this value from PackageSettings
5460        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5461            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5462                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5463            }
5464        }
5465
5466        // TODO: extend to support forward-locked splits
5467        String resourcePath = null;
5468        String baseResourcePath = null;
5469        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5470            if (ps != null && ps.resourcePathString != null) {
5471                resourcePath = ps.resourcePathString;
5472                baseResourcePath = ps.resourcePathString;
5473            } else {
5474                // Should not happen at all. Just log an error.
5475                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5476            }
5477        } else {
5478            resourcePath = pkg.codePath;
5479            baseResourcePath = pkg.baseCodePath;
5480        }
5481
5482        // Set application objects path explicitly.
5483        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5484        pkg.applicationInfo.setCodePath(pkg.codePath);
5485        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5486        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5487        pkg.applicationInfo.setResourcePath(resourcePath);
5488        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5489        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5490
5491        // Note that we invoke the following method only if we are about to unpack an application
5492        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5493                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5494
5495        /*
5496         * If the system app should be overridden by a previously installed
5497         * data, hide the system app now and let the /data/app scan pick it up
5498         * again.
5499         */
5500        if (shouldHideSystemApp) {
5501            synchronized (mPackages) {
5502                /*
5503                 * We have to grant systems permissions before we hide, because
5504                 * grantPermissions will assume the package update is trying to
5505                 * expand its permissions.
5506                 */
5507                grantPermissionsLPw(pkg, true, pkg.packageName);
5508                mSettings.disableSystemPackageLPw(pkg.packageName);
5509            }
5510        }
5511
5512        return scannedPkg;
5513    }
5514
5515    private static String fixProcessName(String defProcessName,
5516            String processName, int uid) {
5517        if (processName == null) {
5518            return defProcessName;
5519        }
5520        return processName;
5521    }
5522
5523    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5524            throws PackageManagerException {
5525        if (pkgSetting.signatures.mSignatures != null) {
5526            // Already existing package. Make sure signatures match
5527            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5528                    == PackageManager.SIGNATURE_MATCH;
5529            if (!match) {
5530                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5531                        == PackageManager.SIGNATURE_MATCH;
5532            }
5533            if (!match) {
5534                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5535                        == PackageManager.SIGNATURE_MATCH;
5536            }
5537            if (!match) {
5538                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5539                        + pkg.packageName + " signatures do not match the "
5540                        + "previously installed version; ignoring!");
5541            }
5542        }
5543
5544        // Check for shared user signatures
5545        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5546            // Already existing package. Make sure signatures match
5547            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5548                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5549            if (!match) {
5550                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5551                        == PackageManager.SIGNATURE_MATCH;
5552            }
5553            if (!match) {
5554                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5555                        == PackageManager.SIGNATURE_MATCH;
5556            }
5557            if (!match) {
5558                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5559                        "Package " + pkg.packageName
5560                        + " has no signatures that match those in shared user "
5561                        + pkgSetting.sharedUser.name + "; ignoring!");
5562            }
5563        }
5564    }
5565
5566    /**
5567     * Enforces that only the system UID or root's UID can call a method exposed
5568     * via Binder.
5569     *
5570     * @param message used as message if SecurityException is thrown
5571     * @throws SecurityException if the caller is not system or root
5572     */
5573    private static final void enforceSystemOrRoot(String message) {
5574        final int uid = Binder.getCallingUid();
5575        if (uid != Process.SYSTEM_UID && uid != 0) {
5576            throw new SecurityException(message);
5577        }
5578    }
5579
5580    @Override
5581    public void performBootDexOpt() {
5582        enforceSystemOrRoot("Only the system can request dexopt be performed");
5583
5584        // Before everything else, see whether we need to fstrim.
5585        try {
5586            IMountService ms = PackageHelper.getMountService();
5587            if (ms != null) {
5588                final boolean isUpgrade = isUpgrade();
5589                boolean doTrim = isUpgrade;
5590                if (doTrim) {
5591                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5592                } else {
5593                    final long interval = android.provider.Settings.Global.getLong(
5594                            mContext.getContentResolver(),
5595                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5596                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5597                    if (interval > 0) {
5598                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5599                        if (timeSinceLast > interval) {
5600                            doTrim = true;
5601                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5602                                    + "; running immediately");
5603                        }
5604                    }
5605                }
5606                if (doTrim) {
5607                    if (!isFirstBoot()) {
5608                        try {
5609                            ActivityManagerNative.getDefault().showBootMessage(
5610                                    mContext.getResources().getString(
5611                                            R.string.android_upgrading_fstrim), true);
5612                        } catch (RemoteException e) {
5613                        }
5614                    }
5615                    ms.runMaintenance();
5616                }
5617            } else {
5618                Slog.e(TAG, "Mount service unavailable!");
5619            }
5620        } catch (RemoteException e) {
5621            // Can't happen; MountService is local
5622        }
5623
5624        final ArraySet<PackageParser.Package> pkgs;
5625        synchronized (mPackages) {
5626            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5627        }
5628
5629        if (pkgs != null) {
5630            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5631            // in case the device runs out of space.
5632            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5633            // Give priority to core apps.
5634            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5635                PackageParser.Package pkg = it.next();
5636                if (pkg.coreApp) {
5637                    if (DEBUG_DEXOPT) {
5638                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5639                    }
5640                    sortedPkgs.add(pkg);
5641                    it.remove();
5642                }
5643            }
5644            // Give priority to system apps that listen for pre boot complete.
5645            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5646            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5647            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5648                PackageParser.Package pkg = it.next();
5649                if (pkgNames.contains(pkg.packageName)) {
5650                    if (DEBUG_DEXOPT) {
5651                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5652                    }
5653                    sortedPkgs.add(pkg);
5654                    it.remove();
5655                }
5656            }
5657            // Give priority to system apps.
5658            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5659                PackageParser.Package pkg = it.next();
5660                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5661                    if (DEBUG_DEXOPT) {
5662                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5663                    }
5664                    sortedPkgs.add(pkg);
5665                    it.remove();
5666                }
5667            }
5668            // Give priority to updated system apps.
5669            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5670                PackageParser.Package pkg = it.next();
5671                if (pkg.isUpdatedSystemApp()) {
5672                    if (DEBUG_DEXOPT) {
5673                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5674                    }
5675                    sortedPkgs.add(pkg);
5676                    it.remove();
5677                }
5678            }
5679            // Give priority to apps that listen for boot complete.
5680            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5681            pkgNames = getPackageNamesForIntent(intent);
5682            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5683                PackageParser.Package pkg = it.next();
5684                if (pkgNames.contains(pkg.packageName)) {
5685                    if (DEBUG_DEXOPT) {
5686                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5687                    }
5688                    sortedPkgs.add(pkg);
5689                    it.remove();
5690                }
5691            }
5692            // Filter out packages that aren't recently used.
5693            filterRecentlyUsedApps(pkgs);
5694            // Add all remaining apps.
5695            for (PackageParser.Package pkg : pkgs) {
5696                if (DEBUG_DEXOPT) {
5697                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5698                }
5699                sortedPkgs.add(pkg);
5700            }
5701
5702            // If we want to be lazy, filter everything that wasn't recently used.
5703            if (mLazyDexOpt) {
5704                filterRecentlyUsedApps(sortedPkgs);
5705            }
5706
5707            int i = 0;
5708            int total = sortedPkgs.size();
5709            File dataDir = Environment.getDataDirectory();
5710            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5711            if (lowThreshold == 0) {
5712                throw new IllegalStateException("Invalid low memory threshold");
5713            }
5714            for (PackageParser.Package pkg : sortedPkgs) {
5715                long usableSpace = dataDir.getUsableSpace();
5716                if (usableSpace < lowThreshold) {
5717                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5718                    break;
5719                }
5720                performBootDexOpt(pkg, ++i, total);
5721            }
5722        }
5723    }
5724
5725    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5726        // Filter out packages that aren't recently used.
5727        //
5728        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5729        // should do a full dexopt.
5730        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5731            int total = pkgs.size();
5732            int skipped = 0;
5733            long now = System.currentTimeMillis();
5734            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5735                PackageParser.Package pkg = i.next();
5736                long then = pkg.mLastPackageUsageTimeInMills;
5737                if (then + mDexOptLRUThresholdInMills < now) {
5738                    if (DEBUG_DEXOPT) {
5739                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5740                              ((then == 0) ? "never" : new Date(then)));
5741                    }
5742                    i.remove();
5743                    skipped++;
5744                }
5745            }
5746            if (DEBUG_DEXOPT) {
5747                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5748            }
5749        }
5750    }
5751
5752    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5753        List<ResolveInfo> ris = null;
5754        try {
5755            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5756                    intent, null, 0, UserHandle.USER_OWNER);
5757        } catch (RemoteException e) {
5758        }
5759        ArraySet<String> pkgNames = new ArraySet<String>();
5760        if (ris != null) {
5761            for (ResolveInfo ri : ris) {
5762                pkgNames.add(ri.activityInfo.packageName);
5763            }
5764        }
5765        return pkgNames;
5766    }
5767
5768    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5769        if (DEBUG_DEXOPT) {
5770            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5771        }
5772        if (!isFirstBoot()) {
5773            try {
5774                ActivityManagerNative.getDefault().showBootMessage(
5775                        mContext.getResources().getString(R.string.android_upgrading_apk,
5776                                curr, total), true);
5777            } catch (RemoteException e) {
5778            }
5779        }
5780        PackageParser.Package p = pkg;
5781        synchronized (mInstallLock) {
5782            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5783                    false /* force dex */, false /* defer */, true /* include dependencies */);
5784        }
5785    }
5786
5787    @Override
5788    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5789        return performDexOpt(packageName, instructionSet, false);
5790    }
5791
5792    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5793        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5794        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5795        if (!dexopt && !updateUsage) {
5796            // We aren't going to dexopt or update usage, so bail early.
5797            return false;
5798        }
5799        PackageParser.Package p;
5800        final String targetInstructionSet;
5801        synchronized (mPackages) {
5802            p = mPackages.get(packageName);
5803            if (p == null) {
5804                return false;
5805            }
5806            if (updateUsage) {
5807                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5808            }
5809            mPackageUsage.write(false);
5810            if (!dexopt) {
5811                // We aren't going to dexopt, so bail early.
5812                return false;
5813            }
5814
5815            targetInstructionSet = instructionSet != null ? instructionSet :
5816                    getPrimaryInstructionSet(p.applicationInfo);
5817            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5818                return false;
5819            }
5820        }
5821
5822        synchronized (mInstallLock) {
5823            final String[] instructionSets = new String[] { targetInstructionSet };
5824            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5825                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5826            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5827        }
5828    }
5829
5830    public ArraySet<String> getPackagesThatNeedDexOpt() {
5831        ArraySet<String> pkgs = null;
5832        synchronized (mPackages) {
5833            for (PackageParser.Package p : mPackages.values()) {
5834                if (DEBUG_DEXOPT) {
5835                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5836                }
5837                if (!p.mDexOptPerformed.isEmpty()) {
5838                    continue;
5839                }
5840                if (pkgs == null) {
5841                    pkgs = new ArraySet<String>();
5842                }
5843                pkgs.add(p.packageName);
5844            }
5845        }
5846        return pkgs;
5847    }
5848
5849    public void shutdown() {
5850        mPackageUsage.write(true);
5851    }
5852
5853    @Override
5854    public void forceDexOpt(String packageName) {
5855        enforceSystemOrRoot("forceDexOpt");
5856
5857        PackageParser.Package pkg;
5858        synchronized (mPackages) {
5859            pkg = mPackages.get(packageName);
5860            if (pkg == null) {
5861                throw new IllegalArgumentException("Missing package: " + packageName);
5862            }
5863        }
5864
5865        synchronized (mInstallLock) {
5866            final String[] instructionSets = new String[] {
5867                    getPrimaryInstructionSet(pkg.applicationInfo) };
5868            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5869                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5870            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5871                throw new IllegalStateException("Failed to dexopt: " + res);
5872            }
5873        }
5874    }
5875
5876    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5877        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5878            Slog.w(TAG, "Unable to update from " + oldPkg.name
5879                    + " to " + newPkg.packageName
5880                    + ": old package not in system partition");
5881            return false;
5882        } else if (mPackages.get(oldPkg.name) != null) {
5883            Slog.w(TAG, "Unable to update from " + oldPkg.name
5884                    + " to " + newPkg.packageName
5885                    + ": old package still exists");
5886            return false;
5887        }
5888        return true;
5889    }
5890
5891    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5892        int[] users = sUserManager.getUserIds();
5893        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5894        if (res < 0) {
5895            return res;
5896        }
5897        for (int user : users) {
5898            if (user != 0) {
5899                res = mInstaller.createUserData(volumeUuid, packageName,
5900                        UserHandle.getUid(user, uid), user, seinfo);
5901                if (res < 0) {
5902                    return res;
5903                }
5904            }
5905        }
5906        return res;
5907    }
5908
5909    private int removeDataDirsLI(String volumeUuid, String packageName) {
5910        int[] users = sUserManager.getUserIds();
5911        int res = 0;
5912        for (int user : users) {
5913            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5914            if (resInner < 0) {
5915                res = resInner;
5916            }
5917        }
5918
5919        return res;
5920    }
5921
5922    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5923        int[] users = sUserManager.getUserIds();
5924        int res = 0;
5925        for (int user : users) {
5926            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5927            if (resInner < 0) {
5928                res = resInner;
5929            }
5930        }
5931        return res;
5932    }
5933
5934    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5935            PackageParser.Package changingLib) {
5936        if (file.path != null) {
5937            usesLibraryFiles.add(file.path);
5938            return;
5939        }
5940        PackageParser.Package p = mPackages.get(file.apk);
5941        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5942            // If we are doing this while in the middle of updating a library apk,
5943            // then we need to make sure to use that new apk for determining the
5944            // dependencies here.  (We haven't yet finished committing the new apk
5945            // to the package manager state.)
5946            if (p == null || p.packageName.equals(changingLib.packageName)) {
5947                p = changingLib;
5948            }
5949        }
5950        if (p != null) {
5951            usesLibraryFiles.addAll(p.getAllCodePaths());
5952        }
5953    }
5954
5955    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5956            PackageParser.Package changingLib) throws PackageManagerException {
5957        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5958            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5959            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5960            for (int i=0; i<N; i++) {
5961                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5962                if (file == null) {
5963                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5964                            "Package " + pkg.packageName + " requires unavailable shared library "
5965                            + pkg.usesLibraries.get(i) + "; failing!");
5966                }
5967                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5968            }
5969            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5970            for (int i=0; i<N; i++) {
5971                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5972                if (file == null) {
5973                    Slog.w(TAG, "Package " + pkg.packageName
5974                            + " desires unavailable shared library "
5975                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5976                } else {
5977                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5978                }
5979            }
5980            N = usesLibraryFiles.size();
5981            if (N > 0) {
5982                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5983            } else {
5984                pkg.usesLibraryFiles = null;
5985            }
5986        }
5987    }
5988
5989    private static boolean hasString(List<String> list, List<String> which) {
5990        if (list == null) {
5991            return false;
5992        }
5993        for (int i=list.size()-1; i>=0; i--) {
5994            for (int j=which.size()-1; j>=0; j--) {
5995                if (which.get(j).equals(list.get(i))) {
5996                    return true;
5997                }
5998            }
5999        }
6000        return false;
6001    }
6002
6003    private void updateAllSharedLibrariesLPw() {
6004        for (PackageParser.Package pkg : mPackages.values()) {
6005            try {
6006                updateSharedLibrariesLPw(pkg, null);
6007            } catch (PackageManagerException e) {
6008                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6009            }
6010        }
6011    }
6012
6013    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6014            PackageParser.Package changingPkg) {
6015        ArrayList<PackageParser.Package> res = null;
6016        for (PackageParser.Package pkg : mPackages.values()) {
6017            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6018                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6019                if (res == null) {
6020                    res = new ArrayList<PackageParser.Package>();
6021                }
6022                res.add(pkg);
6023                try {
6024                    updateSharedLibrariesLPw(pkg, changingPkg);
6025                } catch (PackageManagerException e) {
6026                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6027                }
6028            }
6029        }
6030        return res;
6031    }
6032
6033    /**
6034     * Derive the value of the {@code cpuAbiOverride} based on the provided
6035     * value and an optional stored value from the package settings.
6036     */
6037    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6038        String cpuAbiOverride = null;
6039
6040        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6041            cpuAbiOverride = null;
6042        } else if (abiOverride != null) {
6043            cpuAbiOverride = abiOverride;
6044        } else if (settings != null) {
6045            cpuAbiOverride = settings.cpuAbiOverrideString;
6046        }
6047
6048        return cpuAbiOverride;
6049    }
6050
6051    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6052            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6053        boolean success = false;
6054        try {
6055            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6056                    currentTime, user);
6057            success = true;
6058            return res;
6059        } finally {
6060            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6061                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6062            }
6063        }
6064    }
6065
6066    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6067            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6068        final File scanFile = new File(pkg.codePath);
6069        if (pkg.applicationInfo.getCodePath() == null ||
6070                pkg.applicationInfo.getResourcePath() == null) {
6071            // Bail out. The resource and code paths haven't been set.
6072            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6073                    "Code and resource paths haven't been set correctly");
6074        }
6075
6076        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6077            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6078        } else {
6079            // Only allow system apps to be flagged as core apps.
6080            pkg.coreApp = false;
6081        }
6082
6083        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6084            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6085        }
6086
6087        if (mCustomResolverComponentName != null &&
6088                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6089            setUpCustomResolverActivity(pkg);
6090        }
6091
6092        if (pkg.packageName.equals("android")) {
6093            synchronized (mPackages) {
6094                if (mAndroidApplication != null) {
6095                    Slog.w(TAG, "*************************************************");
6096                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6097                    Slog.w(TAG, " file=" + scanFile);
6098                    Slog.w(TAG, "*************************************************");
6099                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6100                            "Core android package being redefined.  Skipping.");
6101                }
6102
6103                // Set up information for our fall-back user intent resolution activity.
6104                mPlatformPackage = pkg;
6105                pkg.mVersionCode = mSdkVersion;
6106                mAndroidApplication = pkg.applicationInfo;
6107
6108                if (!mResolverReplaced) {
6109                    mResolveActivity.applicationInfo = mAndroidApplication;
6110                    mResolveActivity.name = ResolverActivity.class.getName();
6111                    mResolveActivity.packageName = mAndroidApplication.packageName;
6112                    mResolveActivity.processName = "system:ui";
6113                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6114                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6115                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6116                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6117                    mResolveActivity.exported = true;
6118                    mResolveActivity.enabled = true;
6119                    mResolveInfo.activityInfo = mResolveActivity;
6120                    mResolveInfo.priority = 0;
6121                    mResolveInfo.preferredOrder = 0;
6122                    mResolveInfo.match = 0;
6123                    mResolveComponentName = new ComponentName(
6124                            mAndroidApplication.packageName, mResolveActivity.name);
6125                }
6126            }
6127        }
6128
6129        if (DEBUG_PACKAGE_SCANNING) {
6130            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6131                Log.d(TAG, "Scanning package " + pkg.packageName);
6132        }
6133
6134        if (mPackages.containsKey(pkg.packageName)
6135                || mSharedLibraries.containsKey(pkg.packageName)) {
6136            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6137                    "Application package " + pkg.packageName
6138                    + " already installed.  Skipping duplicate.");
6139        }
6140
6141        // If we're only installing presumed-existing packages, require that the
6142        // scanned APK is both already known and at the path previously established
6143        // for it.  Previously unknown packages we pick up normally, but if we have an
6144        // a priori expectation about this package's install presence, enforce it.
6145        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6146            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6147            if (known != null) {
6148                if (DEBUG_PACKAGE_SCANNING) {
6149                    Log.d(TAG, "Examining " + pkg.codePath
6150                            + " and requiring known paths " + known.codePathString
6151                            + " & " + known.resourcePathString);
6152                }
6153                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6154                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6155                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6156                            "Application package " + pkg.packageName
6157                            + " found at " + pkg.applicationInfo.getCodePath()
6158                            + " but expected at " + known.codePathString + "; ignoring.");
6159                }
6160            }
6161        }
6162
6163        // Initialize package source and resource directories
6164        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6165        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6166
6167        SharedUserSetting suid = null;
6168        PackageSetting pkgSetting = null;
6169
6170        if (!isSystemApp(pkg)) {
6171            // Only system apps can use these features.
6172            pkg.mOriginalPackages = null;
6173            pkg.mRealPackage = null;
6174            pkg.mAdoptPermissions = null;
6175        }
6176
6177        // writer
6178        synchronized (mPackages) {
6179            if (pkg.mSharedUserId != null) {
6180                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6181                if (suid == null) {
6182                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6183                            "Creating application package " + pkg.packageName
6184                            + " for shared user failed");
6185                }
6186                if (DEBUG_PACKAGE_SCANNING) {
6187                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6188                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6189                                + "): packages=" + suid.packages);
6190                }
6191            }
6192
6193            // Check if we are renaming from an original package name.
6194            PackageSetting origPackage = null;
6195            String realName = null;
6196            if (pkg.mOriginalPackages != null) {
6197                // This package may need to be renamed to a previously
6198                // installed name.  Let's check on that...
6199                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6200                if (pkg.mOriginalPackages.contains(renamed)) {
6201                    // This package had originally been installed as the
6202                    // original name, and we have already taken care of
6203                    // transitioning to the new one.  Just update the new
6204                    // one to continue using the old name.
6205                    realName = pkg.mRealPackage;
6206                    if (!pkg.packageName.equals(renamed)) {
6207                        // Callers into this function may have already taken
6208                        // care of renaming the package; only do it here if
6209                        // it is not already done.
6210                        pkg.setPackageName(renamed);
6211                    }
6212
6213                } else {
6214                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6215                        if ((origPackage = mSettings.peekPackageLPr(
6216                                pkg.mOriginalPackages.get(i))) != null) {
6217                            // We do have the package already installed under its
6218                            // original name...  should we use it?
6219                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6220                                // New package is not compatible with original.
6221                                origPackage = null;
6222                                continue;
6223                            } else if (origPackage.sharedUser != null) {
6224                                // Make sure uid is compatible between packages.
6225                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6226                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6227                                            + " to " + pkg.packageName + ": old uid "
6228                                            + origPackage.sharedUser.name
6229                                            + " differs from " + pkg.mSharedUserId);
6230                                    origPackage = null;
6231                                    continue;
6232                                }
6233                            } else {
6234                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6235                                        + pkg.packageName + " to old name " + origPackage.name);
6236                            }
6237                            break;
6238                        }
6239                    }
6240                }
6241            }
6242
6243            if (mTransferedPackages.contains(pkg.packageName)) {
6244                Slog.w(TAG, "Package " + pkg.packageName
6245                        + " was transferred to another, but its .apk remains");
6246            }
6247
6248            // Just create the setting, don't add it yet. For already existing packages
6249            // the PkgSetting exists already and doesn't have to be created.
6250            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6251                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6252                    pkg.applicationInfo.primaryCpuAbi,
6253                    pkg.applicationInfo.secondaryCpuAbi,
6254                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6255                    user, false);
6256            if (pkgSetting == null) {
6257                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6258                        "Creating application package " + pkg.packageName + " failed");
6259            }
6260
6261            if (pkgSetting.origPackage != null) {
6262                // If we are first transitioning from an original package,
6263                // fix up the new package's name now.  We need to do this after
6264                // looking up the package under its new name, so getPackageLP
6265                // can take care of fiddling things correctly.
6266                pkg.setPackageName(origPackage.name);
6267
6268                // File a report about this.
6269                String msg = "New package " + pkgSetting.realName
6270                        + " renamed to replace old package " + pkgSetting.name;
6271                reportSettingsProblem(Log.WARN, msg);
6272
6273                // Make a note of it.
6274                mTransferedPackages.add(origPackage.name);
6275
6276                // No longer need to retain this.
6277                pkgSetting.origPackage = null;
6278            }
6279
6280            if (realName != null) {
6281                // Make a note of it.
6282                mTransferedPackages.add(pkg.packageName);
6283            }
6284
6285            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6286                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6287            }
6288
6289            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6290                // Check all shared libraries and map to their actual file path.
6291                // We only do this here for apps not on a system dir, because those
6292                // are the only ones that can fail an install due to this.  We
6293                // will take care of the system apps by updating all of their
6294                // library paths after the scan is done.
6295                updateSharedLibrariesLPw(pkg, null);
6296            }
6297
6298            if (mFoundPolicyFile) {
6299                SELinuxMMAC.assignSeinfoValue(pkg);
6300            }
6301
6302            pkg.applicationInfo.uid = pkgSetting.appId;
6303            pkg.mExtras = pkgSetting;
6304            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6305                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6306                    // We just determined the app is signed correctly, so bring
6307                    // over the latest parsed certs.
6308                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6309                } else {
6310                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6311                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6312                                "Package " + pkg.packageName + " upgrade keys do not match the "
6313                                + "previously installed version");
6314                    } else {
6315                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6316                        String msg = "System package " + pkg.packageName
6317                            + " signature changed; retaining data.";
6318                        reportSettingsProblem(Log.WARN, msg);
6319                    }
6320                }
6321            } else {
6322                try {
6323                    verifySignaturesLP(pkgSetting, pkg);
6324                    // We just determined the app is signed correctly, so bring
6325                    // over the latest parsed certs.
6326                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6327                } catch (PackageManagerException e) {
6328                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6329                        throw e;
6330                    }
6331                    // The signature has changed, but this package is in the system
6332                    // image...  let's recover!
6333                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6334                    // However...  if this package is part of a shared user, but it
6335                    // doesn't match the signature of the shared user, let's fail.
6336                    // What this means is that you can't change the signatures
6337                    // associated with an overall shared user, which doesn't seem all
6338                    // that unreasonable.
6339                    if (pkgSetting.sharedUser != null) {
6340                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6341                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6342                            throw new PackageManagerException(
6343                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6344                                            "Signature mismatch for shared user : "
6345                                            + pkgSetting.sharedUser);
6346                        }
6347                    }
6348                    // File a report about this.
6349                    String msg = "System package " + pkg.packageName
6350                        + " signature changed; retaining data.";
6351                    reportSettingsProblem(Log.WARN, msg);
6352                }
6353            }
6354            // Verify that this new package doesn't have any content providers
6355            // that conflict with existing packages.  Only do this if the
6356            // package isn't already installed, since we don't want to break
6357            // things that are installed.
6358            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6359                final int N = pkg.providers.size();
6360                int i;
6361                for (i=0; i<N; i++) {
6362                    PackageParser.Provider p = pkg.providers.get(i);
6363                    if (p.info.authority != null) {
6364                        String names[] = p.info.authority.split(";");
6365                        for (int j = 0; j < names.length; j++) {
6366                            if (mProvidersByAuthority.containsKey(names[j])) {
6367                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6368                                final String otherPackageName =
6369                                        ((other != null && other.getComponentName() != null) ?
6370                                                other.getComponentName().getPackageName() : "?");
6371                                throw new PackageManagerException(
6372                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6373                                                "Can't install because provider name " + names[j]
6374                                                + " (in package " + pkg.applicationInfo.packageName
6375                                                + ") is already used by " + otherPackageName);
6376                            }
6377                        }
6378                    }
6379                }
6380            }
6381
6382            if (pkg.mAdoptPermissions != null) {
6383                // This package wants to adopt ownership of permissions from
6384                // another package.
6385                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6386                    final String origName = pkg.mAdoptPermissions.get(i);
6387                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6388                    if (orig != null) {
6389                        if (verifyPackageUpdateLPr(orig, pkg)) {
6390                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6391                                    + pkg.packageName);
6392                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6393                        }
6394                    }
6395                }
6396            }
6397        }
6398
6399        final String pkgName = pkg.packageName;
6400
6401        final long scanFileTime = scanFile.lastModified();
6402        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6403        pkg.applicationInfo.processName = fixProcessName(
6404                pkg.applicationInfo.packageName,
6405                pkg.applicationInfo.processName,
6406                pkg.applicationInfo.uid);
6407
6408        File dataPath;
6409        if (mPlatformPackage == pkg) {
6410            // The system package is special.
6411            dataPath = new File(Environment.getDataDirectory(), "system");
6412
6413            pkg.applicationInfo.dataDir = dataPath.getPath();
6414
6415        } else {
6416            // This is a normal package, need to make its data directory.
6417            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6418                    UserHandle.USER_OWNER);
6419
6420            boolean uidError = false;
6421            if (dataPath.exists()) {
6422                int currentUid = 0;
6423                try {
6424                    StructStat stat = Os.stat(dataPath.getPath());
6425                    currentUid = stat.st_uid;
6426                } catch (ErrnoException e) {
6427                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6428                }
6429
6430                // If we have mismatched owners for the data path, we have a problem.
6431                if (currentUid != pkg.applicationInfo.uid) {
6432                    boolean recovered = false;
6433                    if (currentUid == 0) {
6434                        // The directory somehow became owned by root.  Wow.
6435                        // This is probably because the system was stopped while
6436                        // installd was in the middle of messing with its libs
6437                        // directory.  Ask installd to fix that.
6438                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6439                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6440                        if (ret >= 0) {
6441                            recovered = true;
6442                            String msg = "Package " + pkg.packageName
6443                                    + " unexpectedly changed to uid 0; recovered to " +
6444                                    + pkg.applicationInfo.uid;
6445                            reportSettingsProblem(Log.WARN, msg);
6446                        }
6447                    }
6448                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6449                            || (scanFlags&SCAN_BOOTING) != 0)) {
6450                        // If this is a system app, we can at least delete its
6451                        // current data so the application will still work.
6452                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6453                        if (ret >= 0) {
6454                            // TODO: Kill the processes first
6455                            // Old data gone!
6456                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6457                                    ? "System package " : "Third party package ";
6458                            String msg = prefix + pkg.packageName
6459                                    + " has changed from uid: "
6460                                    + currentUid + " to "
6461                                    + pkg.applicationInfo.uid + "; old data erased";
6462                            reportSettingsProblem(Log.WARN, msg);
6463                            recovered = true;
6464
6465                            // And now re-install the app.
6466                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6467                                    pkg.applicationInfo.seinfo);
6468                            if (ret == -1) {
6469                                // Ack should not happen!
6470                                msg = prefix + pkg.packageName
6471                                        + " could not have data directory re-created after delete.";
6472                                reportSettingsProblem(Log.WARN, msg);
6473                                throw new PackageManagerException(
6474                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6475                            }
6476                        }
6477                        if (!recovered) {
6478                            mHasSystemUidErrors = true;
6479                        }
6480                    } else if (!recovered) {
6481                        // If we allow this install to proceed, we will be broken.
6482                        // Abort, abort!
6483                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6484                                "scanPackageLI");
6485                    }
6486                    if (!recovered) {
6487                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6488                            + pkg.applicationInfo.uid + "/fs_"
6489                            + currentUid;
6490                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6491                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6492                        String msg = "Package " + pkg.packageName
6493                                + " has mismatched uid: "
6494                                + currentUid + " on disk, "
6495                                + pkg.applicationInfo.uid + " in settings";
6496                        // writer
6497                        synchronized (mPackages) {
6498                            mSettings.mReadMessages.append(msg);
6499                            mSettings.mReadMessages.append('\n');
6500                            uidError = true;
6501                            if (!pkgSetting.uidError) {
6502                                reportSettingsProblem(Log.ERROR, msg);
6503                            }
6504                        }
6505                    }
6506                }
6507                pkg.applicationInfo.dataDir = dataPath.getPath();
6508                if (mShouldRestoreconData) {
6509                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6510                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6511                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6512                }
6513            } else {
6514                if (DEBUG_PACKAGE_SCANNING) {
6515                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6516                        Log.v(TAG, "Want this data dir: " + dataPath);
6517                }
6518                //invoke installer to do the actual installation
6519                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6520                        pkg.applicationInfo.seinfo);
6521                if (ret < 0) {
6522                    // Error from installer
6523                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6524                            "Unable to create data dirs [errorCode=" + ret + "]");
6525                }
6526
6527                if (dataPath.exists()) {
6528                    pkg.applicationInfo.dataDir = dataPath.getPath();
6529                } else {
6530                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6531                    pkg.applicationInfo.dataDir = null;
6532                }
6533            }
6534
6535            pkgSetting.uidError = uidError;
6536        }
6537
6538        final String path = scanFile.getPath();
6539        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6540
6541        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6542            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6543
6544            // Some system apps still use directory structure for native libraries
6545            // in which case we might end up not detecting abi solely based on apk
6546            // structure. Try to detect abi based on directory structure.
6547            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6548                    pkg.applicationInfo.primaryCpuAbi == null) {
6549                setBundledAppAbisAndRoots(pkg, pkgSetting);
6550                setNativeLibraryPaths(pkg);
6551            }
6552
6553        } else {
6554            if ((scanFlags & SCAN_MOVE) != 0) {
6555                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6556                // but we already have this packages package info in the PackageSetting. We just
6557                // use that and derive the native library path based on the new codepath.
6558                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6559                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6560            }
6561
6562            // Set native library paths again. For moves, the path will be updated based on the
6563            // ABIs we've determined above. For non-moves, the path will be updated based on the
6564            // ABIs we determined during compilation, but the path will depend on the final
6565            // package path (after the rename away from the stage path).
6566            setNativeLibraryPaths(pkg);
6567        }
6568
6569        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6570        final int[] userIds = sUserManager.getUserIds();
6571        synchronized (mInstallLock) {
6572            // Create a native library symlink only if we have native libraries
6573            // and if the native libraries are 32 bit libraries. We do not provide
6574            // this symlink for 64 bit libraries.
6575            if (pkg.applicationInfo.primaryCpuAbi != null &&
6576                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6577                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6578                for (int userId : userIds) {
6579                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6580                            nativeLibPath, userId) < 0) {
6581                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6582                                "Failed linking native library dir (user=" + userId + ")");
6583                    }
6584                }
6585            }
6586        }
6587
6588        // This is a special case for the "system" package, where the ABI is
6589        // dictated by the zygote configuration (and init.rc). We should keep track
6590        // of this ABI so that we can deal with "normal" applications that run under
6591        // the same UID correctly.
6592        if (mPlatformPackage == pkg) {
6593            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6594                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6595        }
6596
6597        // If there's a mismatch between the abi-override in the package setting
6598        // and the abiOverride specified for the install. Warn about this because we
6599        // would've already compiled the app without taking the package setting into
6600        // account.
6601        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6602            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6603                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6604                        " for package: " + pkg.packageName);
6605            }
6606        }
6607
6608        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6609        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6610        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6611
6612        // Copy the derived override back to the parsed package, so that we can
6613        // update the package settings accordingly.
6614        pkg.cpuAbiOverride = cpuAbiOverride;
6615
6616        if (DEBUG_ABI_SELECTION) {
6617            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6618                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6619                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6620        }
6621
6622        // Push the derived path down into PackageSettings so we know what to
6623        // clean up at uninstall time.
6624        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6625
6626        if (DEBUG_ABI_SELECTION) {
6627            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6628                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6629                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6630        }
6631
6632        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6633            // We don't do this here during boot because we can do it all
6634            // at once after scanning all existing packages.
6635            //
6636            // We also do this *before* we perform dexopt on this package, so that
6637            // we can avoid redundant dexopts, and also to make sure we've got the
6638            // code and package path correct.
6639            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6640                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6641        }
6642
6643        if ((scanFlags & SCAN_NO_DEX) == 0) {
6644            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6645                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6646            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6647                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6648            }
6649        }
6650        if (mFactoryTest && pkg.requestedPermissions.contains(
6651                android.Manifest.permission.FACTORY_TEST)) {
6652            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6653        }
6654
6655        ArrayList<PackageParser.Package> clientLibPkgs = null;
6656
6657        // writer
6658        synchronized (mPackages) {
6659            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6660                // Only system apps can add new shared libraries.
6661                if (pkg.libraryNames != null) {
6662                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6663                        String name = pkg.libraryNames.get(i);
6664                        boolean allowed = false;
6665                        if (pkg.isUpdatedSystemApp()) {
6666                            // New library entries can only be added through the
6667                            // system image.  This is important to get rid of a lot
6668                            // of nasty edge cases: for example if we allowed a non-
6669                            // system update of the app to add a library, then uninstalling
6670                            // the update would make the library go away, and assumptions
6671                            // we made such as through app install filtering would now
6672                            // have allowed apps on the device which aren't compatible
6673                            // with it.  Better to just have the restriction here, be
6674                            // conservative, and create many fewer cases that can negatively
6675                            // impact the user experience.
6676                            final PackageSetting sysPs = mSettings
6677                                    .getDisabledSystemPkgLPr(pkg.packageName);
6678                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6679                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6680                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6681                                        allowed = true;
6682                                        allowed = true;
6683                                        break;
6684                                    }
6685                                }
6686                            }
6687                        } else {
6688                            allowed = true;
6689                        }
6690                        if (allowed) {
6691                            if (!mSharedLibraries.containsKey(name)) {
6692                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6693                            } else if (!name.equals(pkg.packageName)) {
6694                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6695                                        + name + " already exists; skipping");
6696                            }
6697                        } else {
6698                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6699                                    + name + " that is not declared on system image; skipping");
6700                        }
6701                    }
6702                    if ((scanFlags&SCAN_BOOTING) == 0) {
6703                        // If we are not booting, we need to update any applications
6704                        // that are clients of our shared library.  If we are booting,
6705                        // this will all be done once the scan is complete.
6706                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6707                    }
6708                }
6709            }
6710        }
6711
6712        // We also need to dexopt any apps that are dependent on this library.  Note that
6713        // if these fail, we should abort the install since installing the library will
6714        // result in some apps being broken.
6715        if (clientLibPkgs != null) {
6716            if ((scanFlags & SCAN_NO_DEX) == 0) {
6717                for (int i = 0; i < clientLibPkgs.size(); i++) {
6718                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6719                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6720                            null /* instruction sets */, forceDex,
6721                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6722                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6723                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6724                                "scanPackageLI failed to dexopt clientLibPkgs");
6725                    }
6726                }
6727            }
6728        }
6729
6730        // Also need to kill any apps that are dependent on the library.
6731        if (clientLibPkgs != null) {
6732            for (int i=0; i<clientLibPkgs.size(); i++) {
6733                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6734                killApplication(clientPkg.applicationInfo.packageName,
6735                        clientPkg.applicationInfo.uid, "update lib");
6736            }
6737        }
6738
6739        // Make sure we're not adding any bogus keyset info
6740        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6741        ksms.assertScannedPackageValid(pkg);
6742
6743        // writer
6744        synchronized (mPackages) {
6745            // We don't expect installation to fail beyond this point
6746
6747            // Add the new setting to mSettings
6748            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6749            // Add the new setting to mPackages
6750            mPackages.put(pkg.applicationInfo.packageName, pkg);
6751            // Make sure we don't accidentally delete its data.
6752            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6753            while (iter.hasNext()) {
6754                PackageCleanItem item = iter.next();
6755                if (pkgName.equals(item.packageName)) {
6756                    iter.remove();
6757                }
6758            }
6759
6760            // Take care of first install / last update times.
6761            if (currentTime != 0) {
6762                if (pkgSetting.firstInstallTime == 0) {
6763                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6764                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6765                    pkgSetting.lastUpdateTime = currentTime;
6766                }
6767            } else if (pkgSetting.firstInstallTime == 0) {
6768                // We need *something*.  Take time time stamp of the file.
6769                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6770            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6771                if (scanFileTime != pkgSetting.timeStamp) {
6772                    // A package on the system image has changed; consider this
6773                    // to be an update.
6774                    pkgSetting.lastUpdateTime = scanFileTime;
6775                }
6776            }
6777
6778            // Add the package's KeySets to the global KeySetManagerService
6779            ksms.addScannedPackageLPw(pkg);
6780
6781            int N = pkg.providers.size();
6782            StringBuilder r = null;
6783            int i;
6784            for (i=0; i<N; i++) {
6785                PackageParser.Provider p = pkg.providers.get(i);
6786                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6787                        p.info.processName, pkg.applicationInfo.uid);
6788                mProviders.addProvider(p);
6789                p.syncable = p.info.isSyncable;
6790                if (p.info.authority != null) {
6791                    String names[] = p.info.authority.split(";");
6792                    p.info.authority = null;
6793                    for (int j = 0; j < names.length; j++) {
6794                        if (j == 1 && p.syncable) {
6795                            // We only want the first authority for a provider to possibly be
6796                            // syncable, so if we already added this provider using a different
6797                            // authority clear the syncable flag. We copy the provider before
6798                            // changing it because the mProviders object contains a reference
6799                            // to a provider that we don't want to change.
6800                            // Only do this for the second authority since the resulting provider
6801                            // object can be the same for all future authorities for this provider.
6802                            p = new PackageParser.Provider(p);
6803                            p.syncable = false;
6804                        }
6805                        if (!mProvidersByAuthority.containsKey(names[j])) {
6806                            mProvidersByAuthority.put(names[j], p);
6807                            if (p.info.authority == null) {
6808                                p.info.authority = names[j];
6809                            } else {
6810                                p.info.authority = p.info.authority + ";" + names[j];
6811                            }
6812                            if (DEBUG_PACKAGE_SCANNING) {
6813                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6814                                    Log.d(TAG, "Registered content provider: " + names[j]
6815                                            + ", className = " + p.info.name + ", isSyncable = "
6816                                            + p.info.isSyncable);
6817                            }
6818                        } else {
6819                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6820                            Slog.w(TAG, "Skipping provider name " + names[j] +
6821                                    " (in package " + pkg.applicationInfo.packageName +
6822                                    "): name already used by "
6823                                    + ((other != null && other.getComponentName() != null)
6824                                            ? other.getComponentName().getPackageName() : "?"));
6825                        }
6826                    }
6827                }
6828                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6829                    if (r == null) {
6830                        r = new StringBuilder(256);
6831                    } else {
6832                        r.append(' ');
6833                    }
6834                    r.append(p.info.name);
6835                }
6836            }
6837            if (r != null) {
6838                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6839            }
6840
6841            N = pkg.services.size();
6842            r = null;
6843            for (i=0; i<N; i++) {
6844                PackageParser.Service s = pkg.services.get(i);
6845                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6846                        s.info.processName, pkg.applicationInfo.uid);
6847                mServices.addService(s);
6848                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6849                    if (r == null) {
6850                        r = new StringBuilder(256);
6851                    } else {
6852                        r.append(' ');
6853                    }
6854                    r.append(s.info.name);
6855                }
6856            }
6857            if (r != null) {
6858                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6859            }
6860
6861            N = pkg.receivers.size();
6862            r = null;
6863            for (i=0; i<N; i++) {
6864                PackageParser.Activity a = pkg.receivers.get(i);
6865                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6866                        a.info.processName, pkg.applicationInfo.uid);
6867                mReceivers.addActivity(a, "receiver");
6868                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6869                    if (r == null) {
6870                        r = new StringBuilder(256);
6871                    } else {
6872                        r.append(' ');
6873                    }
6874                    r.append(a.info.name);
6875                }
6876            }
6877            if (r != null) {
6878                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6879            }
6880
6881            N = pkg.activities.size();
6882            r = null;
6883            for (i=0; i<N; i++) {
6884                PackageParser.Activity a = pkg.activities.get(i);
6885                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6886                        a.info.processName, pkg.applicationInfo.uid);
6887                mActivities.addActivity(a, "activity");
6888                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6889                    if (r == null) {
6890                        r = new StringBuilder(256);
6891                    } else {
6892                        r.append(' ');
6893                    }
6894                    r.append(a.info.name);
6895                }
6896            }
6897            if (r != null) {
6898                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6899            }
6900
6901            N = pkg.permissionGroups.size();
6902            r = null;
6903            for (i=0; i<N; i++) {
6904                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6905                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6906                if (cur == null) {
6907                    mPermissionGroups.put(pg.info.name, pg);
6908                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6909                        if (r == null) {
6910                            r = new StringBuilder(256);
6911                        } else {
6912                            r.append(' ');
6913                        }
6914                        r.append(pg.info.name);
6915                    }
6916                } else {
6917                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6918                            + pg.info.packageName + " ignored: original from "
6919                            + cur.info.packageName);
6920                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6921                        if (r == null) {
6922                            r = new StringBuilder(256);
6923                        } else {
6924                            r.append(' ');
6925                        }
6926                        r.append("DUP:");
6927                        r.append(pg.info.name);
6928                    }
6929                }
6930            }
6931            if (r != null) {
6932                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6933            }
6934
6935            N = pkg.permissions.size();
6936            r = null;
6937            for (i=0; i<N; i++) {
6938                PackageParser.Permission p = pkg.permissions.get(i);
6939
6940                // Now that permission groups have a special meaning, we ignore permission
6941                // groups for legacy apps to prevent unexpected behavior. In particular,
6942                // permissions for one app being granted to someone just becuase they happen
6943                // to be in a group defined by another app (before this had no implications).
6944                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6945                    p.group = mPermissionGroups.get(p.info.group);
6946                    // Warn for a permission in an unknown group.
6947                    if (p.info.group != null && p.group == null) {
6948                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6949                                + p.info.packageName + " in an unknown group " + p.info.group);
6950                    }
6951                }
6952
6953                ArrayMap<String, BasePermission> permissionMap =
6954                        p.tree ? mSettings.mPermissionTrees
6955                                : mSettings.mPermissions;
6956                BasePermission bp = permissionMap.get(p.info.name);
6957
6958                // Allow system apps to redefine non-system permissions
6959                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6960                    final boolean currentOwnerIsSystem = (bp.perm != null
6961                            && isSystemApp(bp.perm.owner));
6962                    if (isSystemApp(p.owner)) {
6963                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6964                            // It's a built-in permission and no owner, take ownership now
6965                            bp.packageSetting = pkgSetting;
6966                            bp.perm = p;
6967                            bp.uid = pkg.applicationInfo.uid;
6968                            bp.sourcePackage = p.info.packageName;
6969                        } else if (!currentOwnerIsSystem) {
6970                            String msg = "New decl " + p.owner + " of permission  "
6971                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6972                            reportSettingsProblem(Log.WARN, msg);
6973                            bp = null;
6974                        }
6975                    }
6976                }
6977
6978                if (bp == null) {
6979                    bp = new BasePermission(p.info.name, p.info.packageName,
6980                            BasePermission.TYPE_NORMAL);
6981                    permissionMap.put(p.info.name, bp);
6982                }
6983
6984                if (bp.perm == null) {
6985                    if (bp.sourcePackage == null
6986                            || bp.sourcePackage.equals(p.info.packageName)) {
6987                        BasePermission tree = findPermissionTreeLP(p.info.name);
6988                        if (tree == null
6989                                || tree.sourcePackage.equals(p.info.packageName)) {
6990                            bp.packageSetting = pkgSetting;
6991                            bp.perm = p;
6992                            bp.uid = pkg.applicationInfo.uid;
6993                            bp.sourcePackage = p.info.packageName;
6994                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6995                                if (r == null) {
6996                                    r = new StringBuilder(256);
6997                                } else {
6998                                    r.append(' ');
6999                                }
7000                                r.append(p.info.name);
7001                            }
7002                        } else {
7003                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7004                                    + p.info.packageName + " ignored: base tree "
7005                                    + tree.name + " is from package "
7006                                    + tree.sourcePackage);
7007                        }
7008                    } else {
7009                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7010                                + p.info.packageName + " ignored: original from "
7011                                + bp.sourcePackage);
7012                    }
7013                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7014                    if (r == null) {
7015                        r = new StringBuilder(256);
7016                    } else {
7017                        r.append(' ');
7018                    }
7019                    r.append("DUP:");
7020                    r.append(p.info.name);
7021                }
7022                if (bp.perm == p) {
7023                    bp.protectionLevel = p.info.protectionLevel;
7024                }
7025            }
7026
7027            if (r != null) {
7028                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7029            }
7030
7031            N = pkg.instrumentation.size();
7032            r = null;
7033            for (i=0; i<N; i++) {
7034                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7035                a.info.packageName = pkg.applicationInfo.packageName;
7036                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7037                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7038                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7039                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7040                a.info.dataDir = pkg.applicationInfo.dataDir;
7041
7042                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7043                // need other information about the application, like the ABI and what not ?
7044                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7045                mInstrumentation.put(a.getComponentName(), a);
7046                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7047                    if (r == null) {
7048                        r = new StringBuilder(256);
7049                    } else {
7050                        r.append(' ');
7051                    }
7052                    r.append(a.info.name);
7053                }
7054            }
7055            if (r != null) {
7056                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7057            }
7058
7059            if (pkg.protectedBroadcasts != null) {
7060                N = pkg.protectedBroadcasts.size();
7061                for (i=0; i<N; i++) {
7062                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7063                }
7064            }
7065
7066            pkgSetting.setTimeStamp(scanFileTime);
7067
7068            // Create idmap files for pairs of (packages, overlay packages).
7069            // Note: "android", ie framework-res.apk, is handled by native layers.
7070            if (pkg.mOverlayTarget != null) {
7071                // This is an overlay package.
7072                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7073                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7074                        mOverlays.put(pkg.mOverlayTarget,
7075                                new ArrayMap<String, PackageParser.Package>());
7076                    }
7077                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7078                    map.put(pkg.packageName, pkg);
7079                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7080                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7081                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7082                                "scanPackageLI failed to createIdmap");
7083                    }
7084                }
7085            } else if (mOverlays.containsKey(pkg.packageName) &&
7086                    !pkg.packageName.equals("android")) {
7087                // This is a regular package, with one or more known overlay packages.
7088                createIdmapsForPackageLI(pkg);
7089            }
7090        }
7091
7092        return pkg;
7093    }
7094
7095    /**
7096     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7097     * is derived purely on the basis of the contents of {@code scanFile} and
7098     * {@code cpuAbiOverride}.
7099     *
7100     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7101     */
7102    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7103                                 String cpuAbiOverride, boolean extractLibs)
7104            throws PackageManagerException {
7105        // TODO: We can probably be smarter about this stuff. For installed apps,
7106        // we can calculate this information at install time once and for all. For
7107        // system apps, we can probably assume that this information doesn't change
7108        // after the first boot scan. As things stand, we do lots of unnecessary work.
7109
7110        // Give ourselves some initial paths; we'll come back for another
7111        // pass once we've determined ABI below.
7112        setNativeLibraryPaths(pkg);
7113
7114        // We would never need to extract libs for forward-locked and external packages,
7115        // since the container service will do it for us. We shouldn't attempt to
7116        // extract libs from system app when it was not updated.
7117        if (pkg.isForwardLocked() || isExternal(pkg) ||
7118            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7119            extractLibs = false;
7120        }
7121
7122        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7123        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7124
7125        NativeLibraryHelper.Handle handle = null;
7126        try {
7127            handle = NativeLibraryHelper.Handle.create(scanFile);
7128            // TODO(multiArch): This can be null for apps that didn't go through the
7129            // usual installation process. We can calculate it again, like we
7130            // do during install time.
7131            //
7132            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7133            // unnecessary.
7134            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7135
7136            // Null out the abis so that they can be recalculated.
7137            pkg.applicationInfo.primaryCpuAbi = null;
7138            pkg.applicationInfo.secondaryCpuAbi = null;
7139            if (isMultiArch(pkg.applicationInfo)) {
7140                // Warn if we've set an abiOverride for multi-lib packages..
7141                // By definition, we need to copy both 32 and 64 bit libraries for
7142                // such packages.
7143                if (pkg.cpuAbiOverride != null
7144                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7145                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7146                }
7147
7148                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7149                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7150                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7151                    if (extractLibs) {
7152                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7153                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7154                                useIsaSpecificSubdirs);
7155                    } else {
7156                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7157                    }
7158                }
7159
7160                maybeThrowExceptionForMultiArchCopy(
7161                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7162
7163                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7164                    if (extractLibs) {
7165                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7166                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7167                                useIsaSpecificSubdirs);
7168                    } else {
7169                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7170                    }
7171                }
7172
7173                maybeThrowExceptionForMultiArchCopy(
7174                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7175
7176                if (abi64 >= 0) {
7177                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7178                }
7179
7180                if (abi32 >= 0) {
7181                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7182                    if (abi64 >= 0) {
7183                        pkg.applicationInfo.secondaryCpuAbi = abi;
7184                    } else {
7185                        pkg.applicationInfo.primaryCpuAbi = abi;
7186                    }
7187                }
7188            } else {
7189                String[] abiList = (cpuAbiOverride != null) ?
7190                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7191
7192                // Enable gross and lame hacks for apps that are built with old
7193                // SDK tools. We must scan their APKs for renderscript bitcode and
7194                // not launch them if it's present. Don't bother checking on devices
7195                // that don't have 64 bit support.
7196                boolean needsRenderScriptOverride = false;
7197                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7198                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7199                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7200                    needsRenderScriptOverride = true;
7201                }
7202
7203                final int copyRet;
7204                if (extractLibs) {
7205                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7206                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7207                } else {
7208                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7209                }
7210
7211                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7212                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7213                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7214                }
7215
7216                if (copyRet >= 0) {
7217                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7218                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7219                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7220                } else if (needsRenderScriptOverride) {
7221                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7222                }
7223            }
7224        } catch (IOException ioe) {
7225            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7226        } finally {
7227            IoUtils.closeQuietly(handle);
7228        }
7229
7230        // Now that we've calculated the ABIs and determined if it's an internal app,
7231        // we will go ahead and populate the nativeLibraryPath.
7232        setNativeLibraryPaths(pkg);
7233    }
7234
7235    /**
7236     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7237     * i.e, so that all packages can be run inside a single process if required.
7238     *
7239     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7240     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7241     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7242     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7243     * updating a package that belongs to a shared user.
7244     *
7245     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7246     * adds unnecessary complexity.
7247     */
7248    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7249            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7250        String requiredInstructionSet = null;
7251        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7252            requiredInstructionSet = VMRuntime.getInstructionSet(
7253                     scannedPackage.applicationInfo.primaryCpuAbi);
7254        }
7255
7256        PackageSetting requirer = null;
7257        for (PackageSetting ps : packagesForUser) {
7258            // If packagesForUser contains scannedPackage, we skip it. This will happen
7259            // when scannedPackage is an update of an existing package. Without this check,
7260            // we will never be able to change the ABI of any package belonging to a shared
7261            // user, even if it's compatible with other packages.
7262            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7263                if (ps.primaryCpuAbiString == null) {
7264                    continue;
7265                }
7266
7267                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7268                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7269                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7270                    // this but there's not much we can do.
7271                    String errorMessage = "Instruction set mismatch, "
7272                            + ((requirer == null) ? "[caller]" : requirer)
7273                            + " requires " + requiredInstructionSet + " whereas " + ps
7274                            + " requires " + instructionSet;
7275                    Slog.w(TAG, errorMessage);
7276                }
7277
7278                if (requiredInstructionSet == null) {
7279                    requiredInstructionSet = instructionSet;
7280                    requirer = ps;
7281                }
7282            }
7283        }
7284
7285        if (requiredInstructionSet != null) {
7286            String adjustedAbi;
7287            if (requirer != null) {
7288                // requirer != null implies that either scannedPackage was null or that scannedPackage
7289                // did not require an ABI, in which case we have to adjust scannedPackage to match
7290                // the ABI of the set (which is the same as requirer's ABI)
7291                adjustedAbi = requirer.primaryCpuAbiString;
7292                if (scannedPackage != null) {
7293                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7294                }
7295            } else {
7296                // requirer == null implies that we're updating all ABIs in the set to
7297                // match scannedPackage.
7298                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7299            }
7300
7301            for (PackageSetting ps : packagesForUser) {
7302                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7303                    if (ps.primaryCpuAbiString != null) {
7304                        continue;
7305                    }
7306
7307                    ps.primaryCpuAbiString = adjustedAbi;
7308                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7309                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7310                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7311
7312                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7313                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7314                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7315                            ps.primaryCpuAbiString = null;
7316                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7317                            return;
7318                        } else {
7319                            mInstaller.rmdex(ps.codePathString,
7320                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7321                        }
7322                    }
7323                }
7324            }
7325        }
7326    }
7327
7328    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7329        synchronized (mPackages) {
7330            mResolverReplaced = true;
7331            // Set up information for custom user intent resolution activity.
7332            mResolveActivity.applicationInfo = pkg.applicationInfo;
7333            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7334            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7335            mResolveActivity.processName = pkg.applicationInfo.packageName;
7336            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7337            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7338                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7339            mResolveActivity.theme = 0;
7340            mResolveActivity.exported = true;
7341            mResolveActivity.enabled = true;
7342            mResolveInfo.activityInfo = mResolveActivity;
7343            mResolveInfo.priority = 0;
7344            mResolveInfo.preferredOrder = 0;
7345            mResolveInfo.match = 0;
7346            mResolveComponentName = mCustomResolverComponentName;
7347            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7348                    mResolveComponentName);
7349        }
7350    }
7351
7352    private static String calculateBundledApkRoot(final String codePathString) {
7353        final File codePath = new File(codePathString);
7354        final File codeRoot;
7355        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7356            codeRoot = Environment.getRootDirectory();
7357        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7358            codeRoot = Environment.getOemDirectory();
7359        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7360            codeRoot = Environment.getVendorDirectory();
7361        } else {
7362            // Unrecognized code path; take its top real segment as the apk root:
7363            // e.g. /something/app/blah.apk => /something
7364            try {
7365                File f = codePath.getCanonicalFile();
7366                File parent = f.getParentFile();    // non-null because codePath is a file
7367                File tmp;
7368                while ((tmp = parent.getParentFile()) != null) {
7369                    f = parent;
7370                    parent = tmp;
7371                }
7372                codeRoot = f;
7373                Slog.w(TAG, "Unrecognized code path "
7374                        + codePath + " - using " + codeRoot);
7375            } catch (IOException e) {
7376                // Can't canonicalize the code path -- shenanigans?
7377                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7378                return Environment.getRootDirectory().getPath();
7379            }
7380        }
7381        return codeRoot.getPath();
7382    }
7383
7384    /**
7385     * Derive and set the location of native libraries for the given package,
7386     * which varies depending on where and how the package was installed.
7387     */
7388    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7389        final ApplicationInfo info = pkg.applicationInfo;
7390        final String codePath = pkg.codePath;
7391        final File codeFile = new File(codePath);
7392        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7393        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7394
7395        info.nativeLibraryRootDir = null;
7396        info.nativeLibraryRootRequiresIsa = false;
7397        info.nativeLibraryDir = null;
7398        info.secondaryNativeLibraryDir = null;
7399
7400        if (isApkFile(codeFile)) {
7401            // Monolithic install
7402            if (bundledApp) {
7403                // If "/system/lib64/apkname" exists, assume that is the per-package
7404                // native library directory to use; otherwise use "/system/lib/apkname".
7405                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7406                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7407                        getPrimaryInstructionSet(info));
7408
7409                // This is a bundled system app so choose the path based on the ABI.
7410                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7411                // is just the default path.
7412                final String apkName = deriveCodePathName(codePath);
7413                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7414                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7415                        apkName).getAbsolutePath();
7416
7417                if (info.secondaryCpuAbi != null) {
7418                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7419                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7420                            secondaryLibDir, apkName).getAbsolutePath();
7421                }
7422            } else if (asecApp) {
7423                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7424                        .getAbsolutePath();
7425            } else {
7426                final String apkName = deriveCodePathName(codePath);
7427                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7428                        .getAbsolutePath();
7429            }
7430
7431            info.nativeLibraryRootRequiresIsa = false;
7432            info.nativeLibraryDir = info.nativeLibraryRootDir;
7433        } else {
7434            // Cluster install
7435            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7436            info.nativeLibraryRootRequiresIsa = true;
7437
7438            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7439                    getPrimaryInstructionSet(info)).getAbsolutePath();
7440
7441            if (info.secondaryCpuAbi != null) {
7442                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7443                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7444            }
7445        }
7446    }
7447
7448    /**
7449     * Calculate the abis and roots for a bundled app. These can uniquely
7450     * be determined from the contents of the system partition, i.e whether
7451     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7452     * of this information, and instead assume that the system was built
7453     * sensibly.
7454     */
7455    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7456                                           PackageSetting pkgSetting) {
7457        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7458
7459        // If "/system/lib64/apkname" exists, assume that is the per-package
7460        // native library directory to use; otherwise use "/system/lib/apkname".
7461        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7462        setBundledAppAbi(pkg, apkRoot, apkName);
7463        // pkgSetting might be null during rescan following uninstall of updates
7464        // to a bundled app, so accommodate that possibility.  The settings in
7465        // that case will be established later from the parsed package.
7466        //
7467        // If the settings aren't null, sync them up with what we've just derived.
7468        // note that apkRoot isn't stored in the package settings.
7469        if (pkgSetting != null) {
7470            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7471            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7472        }
7473    }
7474
7475    /**
7476     * Deduces the ABI of a bundled app and sets the relevant fields on the
7477     * parsed pkg object.
7478     *
7479     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7480     *        under which system libraries are installed.
7481     * @param apkName the name of the installed package.
7482     */
7483    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7484        final File codeFile = new File(pkg.codePath);
7485
7486        final boolean has64BitLibs;
7487        final boolean has32BitLibs;
7488        if (isApkFile(codeFile)) {
7489            // Monolithic install
7490            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7491            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7492        } else {
7493            // Cluster install
7494            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7495            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7496                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7497                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7498                has64BitLibs = (new File(rootDir, isa)).exists();
7499            } else {
7500                has64BitLibs = false;
7501            }
7502            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7503                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7504                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7505                has32BitLibs = (new File(rootDir, isa)).exists();
7506            } else {
7507                has32BitLibs = false;
7508            }
7509        }
7510
7511        if (has64BitLibs && !has32BitLibs) {
7512            // The package has 64 bit libs, but not 32 bit libs. Its primary
7513            // ABI should be 64 bit. We can safely assume here that the bundled
7514            // native libraries correspond to the most preferred ABI in the list.
7515
7516            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7517            pkg.applicationInfo.secondaryCpuAbi = null;
7518        } else if (has32BitLibs && !has64BitLibs) {
7519            // The package has 32 bit libs but not 64 bit libs. Its primary
7520            // ABI should be 32 bit.
7521
7522            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7523            pkg.applicationInfo.secondaryCpuAbi = null;
7524        } else if (has32BitLibs && has64BitLibs) {
7525            // The application has both 64 and 32 bit bundled libraries. We check
7526            // here that the app declares multiArch support, and warn if it doesn't.
7527            //
7528            // We will be lenient here and record both ABIs. The primary will be the
7529            // ABI that's higher on the list, i.e, a device that's configured to prefer
7530            // 64 bit apps will see a 64 bit primary ABI,
7531
7532            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7533                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7534            }
7535
7536            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7537                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7538                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7539            } else {
7540                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7541                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7542            }
7543        } else {
7544            pkg.applicationInfo.primaryCpuAbi = null;
7545            pkg.applicationInfo.secondaryCpuAbi = null;
7546        }
7547    }
7548
7549    private void killApplication(String pkgName, int appId, String reason) {
7550        // Request the ActivityManager to kill the process(only for existing packages)
7551        // so that we do not end up in a confused state while the user is still using the older
7552        // version of the application while the new one gets installed.
7553        IActivityManager am = ActivityManagerNative.getDefault();
7554        if (am != null) {
7555            try {
7556                am.killApplicationWithAppId(pkgName, appId, reason);
7557            } catch (RemoteException e) {
7558            }
7559        }
7560    }
7561
7562    void removePackageLI(PackageSetting ps, boolean chatty) {
7563        if (DEBUG_INSTALL) {
7564            if (chatty)
7565                Log.d(TAG, "Removing package " + ps.name);
7566        }
7567
7568        // writer
7569        synchronized (mPackages) {
7570            mPackages.remove(ps.name);
7571            final PackageParser.Package pkg = ps.pkg;
7572            if (pkg != null) {
7573                cleanPackageDataStructuresLILPw(pkg, chatty);
7574            }
7575        }
7576    }
7577
7578    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7579        if (DEBUG_INSTALL) {
7580            if (chatty)
7581                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7582        }
7583
7584        // writer
7585        synchronized (mPackages) {
7586            mPackages.remove(pkg.applicationInfo.packageName);
7587            cleanPackageDataStructuresLILPw(pkg, chatty);
7588        }
7589    }
7590
7591    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7592        int N = pkg.providers.size();
7593        StringBuilder r = null;
7594        int i;
7595        for (i=0; i<N; i++) {
7596            PackageParser.Provider p = pkg.providers.get(i);
7597            mProviders.removeProvider(p);
7598            if (p.info.authority == null) {
7599
7600                /* There was another ContentProvider with this authority when
7601                 * this app was installed so this authority is null,
7602                 * Ignore it as we don't have to unregister the provider.
7603                 */
7604                continue;
7605            }
7606            String names[] = p.info.authority.split(";");
7607            for (int j = 0; j < names.length; j++) {
7608                if (mProvidersByAuthority.get(names[j]) == p) {
7609                    mProvidersByAuthority.remove(names[j]);
7610                    if (DEBUG_REMOVE) {
7611                        if (chatty)
7612                            Log.d(TAG, "Unregistered content provider: " + names[j]
7613                                    + ", className = " + p.info.name + ", isSyncable = "
7614                                    + p.info.isSyncable);
7615                    }
7616                }
7617            }
7618            if (DEBUG_REMOVE && chatty) {
7619                if (r == null) {
7620                    r = new StringBuilder(256);
7621                } else {
7622                    r.append(' ');
7623                }
7624                r.append(p.info.name);
7625            }
7626        }
7627        if (r != null) {
7628            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7629        }
7630
7631        N = pkg.services.size();
7632        r = null;
7633        for (i=0; i<N; i++) {
7634            PackageParser.Service s = pkg.services.get(i);
7635            mServices.removeService(s);
7636            if (chatty) {
7637                if (r == null) {
7638                    r = new StringBuilder(256);
7639                } else {
7640                    r.append(' ');
7641                }
7642                r.append(s.info.name);
7643            }
7644        }
7645        if (r != null) {
7646            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7647        }
7648
7649        N = pkg.receivers.size();
7650        r = null;
7651        for (i=0; i<N; i++) {
7652            PackageParser.Activity a = pkg.receivers.get(i);
7653            mReceivers.removeActivity(a, "receiver");
7654            if (DEBUG_REMOVE && chatty) {
7655                if (r == null) {
7656                    r = new StringBuilder(256);
7657                } else {
7658                    r.append(' ');
7659                }
7660                r.append(a.info.name);
7661            }
7662        }
7663        if (r != null) {
7664            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7665        }
7666
7667        N = pkg.activities.size();
7668        r = null;
7669        for (i=0; i<N; i++) {
7670            PackageParser.Activity a = pkg.activities.get(i);
7671            mActivities.removeActivity(a, "activity");
7672            if (DEBUG_REMOVE && chatty) {
7673                if (r == null) {
7674                    r = new StringBuilder(256);
7675                } else {
7676                    r.append(' ');
7677                }
7678                r.append(a.info.name);
7679            }
7680        }
7681        if (r != null) {
7682            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7683        }
7684
7685        N = pkg.permissions.size();
7686        r = null;
7687        for (i=0; i<N; i++) {
7688            PackageParser.Permission p = pkg.permissions.get(i);
7689            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7690            if (bp == null) {
7691                bp = mSettings.mPermissionTrees.get(p.info.name);
7692            }
7693            if (bp != null && bp.perm == p) {
7694                bp.perm = null;
7695                if (DEBUG_REMOVE && chatty) {
7696                    if (r == null) {
7697                        r = new StringBuilder(256);
7698                    } else {
7699                        r.append(' ');
7700                    }
7701                    r.append(p.info.name);
7702                }
7703            }
7704            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7705                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7706                if (appOpPerms != null) {
7707                    appOpPerms.remove(pkg.packageName);
7708                }
7709            }
7710        }
7711        if (r != null) {
7712            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7713        }
7714
7715        N = pkg.requestedPermissions.size();
7716        r = null;
7717        for (i=0; i<N; i++) {
7718            String perm = pkg.requestedPermissions.get(i);
7719            BasePermission bp = mSettings.mPermissions.get(perm);
7720            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7721                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7722                if (appOpPerms != null) {
7723                    appOpPerms.remove(pkg.packageName);
7724                    if (appOpPerms.isEmpty()) {
7725                        mAppOpPermissionPackages.remove(perm);
7726                    }
7727                }
7728            }
7729        }
7730        if (r != null) {
7731            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7732        }
7733
7734        N = pkg.instrumentation.size();
7735        r = null;
7736        for (i=0; i<N; i++) {
7737            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7738            mInstrumentation.remove(a.getComponentName());
7739            if (DEBUG_REMOVE && chatty) {
7740                if (r == null) {
7741                    r = new StringBuilder(256);
7742                } else {
7743                    r.append(' ');
7744                }
7745                r.append(a.info.name);
7746            }
7747        }
7748        if (r != null) {
7749            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7750        }
7751
7752        r = null;
7753        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7754            // Only system apps can hold shared libraries.
7755            if (pkg.libraryNames != null) {
7756                for (i=0; i<pkg.libraryNames.size(); i++) {
7757                    String name = pkg.libraryNames.get(i);
7758                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7759                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7760                        mSharedLibraries.remove(name);
7761                        if (DEBUG_REMOVE && chatty) {
7762                            if (r == null) {
7763                                r = new StringBuilder(256);
7764                            } else {
7765                                r.append(' ');
7766                            }
7767                            r.append(name);
7768                        }
7769                    }
7770                }
7771            }
7772        }
7773        if (r != null) {
7774            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7775        }
7776    }
7777
7778    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7779        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7780            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7781                return true;
7782            }
7783        }
7784        return false;
7785    }
7786
7787    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7788    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7789    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7790
7791    private void updatePermissionsLPw(String changingPkg,
7792            PackageParser.Package pkgInfo, int flags) {
7793        // Make sure there are no dangling permission trees.
7794        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7795        while (it.hasNext()) {
7796            final BasePermission bp = it.next();
7797            if (bp.packageSetting == null) {
7798                // We may not yet have parsed the package, so just see if
7799                // we still know about its settings.
7800                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7801            }
7802            if (bp.packageSetting == null) {
7803                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7804                        + " from package " + bp.sourcePackage);
7805                it.remove();
7806            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7807                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7808                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7809                            + " from package " + bp.sourcePackage);
7810                    flags |= UPDATE_PERMISSIONS_ALL;
7811                    it.remove();
7812                }
7813            }
7814        }
7815
7816        // Make sure all dynamic permissions have been assigned to a package,
7817        // and make sure there are no dangling permissions.
7818        it = mSettings.mPermissions.values().iterator();
7819        while (it.hasNext()) {
7820            final BasePermission bp = it.next();
7821            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7822                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7823                        + bp.name + " pkg=" + bp.sourcePackage
7824                        + " info=" + bp.pendingInfo);
7825                if (bp.packageSetting == null && bp.pendingInfo != null) {
7826                    final BasePermission tree = findPermissionTreeLP(bp.name);
7827                    if (tree != null && tree.perm != null) {
7828                        bp.packageSetting = tree.packageSetting;
7829                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7830                                new PermissionInfo(bp.pendingInfo));
7831                        bp.perm.info.packageName = tree.perm.info.packageName;
7832                        bp.perm.info.name = bp.name;
7833                        bp.uid = tree.uid;
7834                    }
7835                }
7836            }
7837            if (bp.packageSetting == null) {
7838                // We may not yet have parsed the package, so just see if
7839                // we still know about its settings.
7840                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7841            }
7842            if (bp.packageSetting == null) {
7843                Slog.w(TAG, "Removing dangling permission: " + bp.name
7844                        + " from package " + bp.sourcePackage);
7845                it.remove();
7846            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7847                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7848                    Slog.i(TAG, "Removing old permission: " + bp.name
7849                            + " from package " + bp.sourcePackage);
7850                    flags |= UPDATE_PERMISSIONS_ALL;
7851                    it.remove();
7852                }
7853            }
7854        }
7855
7856        // Now update the permissions for all packages, in particular
7857        // replace the granted permissions of the system packages.
7858        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7859            for (PackageParser.Package pkg : mPackages.values()) {
7860                if (pkg != pkgInfo) {
7861                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7862                            changingPkg);
7863                }
7864            }
7865        }
7866
7867        if (pkgInfo != null) {
7868            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7869        }
7870    }
7871
7872    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7873            String packageOfInterest) {
7874        // IMPORTANT: There are two types of permissions: install and runtime.
7875        // Install time permissions are granted when the app is installed to
7876        // all device users and users added in the future. Runtime permissions
7877        // are granted at runtime explicitly to specific users. Normal and signature
7878        // protected permissions are install time permissions. Dangerous permissions
7879        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7880        // otherwise they are runtime permissions. This function does not manage
7881        // runtime permissions except for the case an app targeting Lollipop MR1
7882        // being upgraded to target a newer SDK, in which case dangerous permissions
7883        // are transformed from install time to runtime ones.
7884
7885        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7886        if (ps == null) {
7887            return;
7888        }
7889
7890        PermissionsState permissionsState = ps.getPermissionsState();
7891        PermissionsState origPermissions = permissionsState;
7892
7893        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7894
7895        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7896
7897        boolean changedInstallPermission = false;
7898
7899        if (replace) {
7900            ps.installPermissionsFixed = false;
7901            if (!ps.isSharedUser()) {
7902                origPermissions = new PermissionsState(permissionsState);
7903                permissionsState.reset();
7904            }
7905        }
7906
7907        permissionsState.setGlobalGids(mGlobalGids);
7908
7909        final int N = pkg.requestedPermissions.size();
7910        for (int i=0; i<N; i++) {
7911            final String name = pkg.requestedPermissions.get(i);
7912            final BasePermission bp = mSettings.mPermissions.get(name);
7913
7914            if (DEBUG_INSTALL) {
7915                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7916            }
7917
7918            if (bp == null || bp.packageSetting == null) {
7919                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7920                    Slog.w(TAG, "Unknown permission " + name
7921                            + " in package " + pkg.packageName);
7922                }
7923                continue;
7924            }
7925
7926            final String perm = bp.name;
7927            boolean allowedSig = false;
7928            int grant = GRANT_DENIED;
7929
7930            // Keep track of app op permissions.
7931            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7932                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7933                if (pkgs == null) {
7934                    pkgs = new ArraySet<>();
7935                    mAppOpPermissionPackages.put(bp.name, pkgs);
7936                }
7937                pkgs.add(pkg.packageName);
7938            }
7939
7940            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7941            switch (level) {
7942                case PermissionInfo.PROTECTION_NORMAL: {
7943                    // For all apps normal permissions are install time ones.
7944                    grant = GRANT_INSTALL;
7945                } break;
7946
7947                case PermissionInfo.PROTECTION_DANGEROUS: {
7948                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7949                        // For legacy apps dangerous permissions are install time ones.
7950                        grant = GRANT_INSTALL_LEGACY;
7951                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7952                        // For legacy apps that became modern, install becomes runtime.
7953                        grant = GRANT_UPGRADE;
7954                    } else {
7955                        // For modern apps keep runtime permissions unchanged.
7956                        grant = GRANT_RUNTIME;
7957                    }
7958                } break;
7959
7960                case PermissionInfo.PROTECTION_SIGNATURE: {
7961                    // For all apps signature permissions are install time ones.
7962                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7963                    if (allowedSig) {
7964                        grant = GRANT_INSTALL;
7965                    }
7966                } break;
7967            }
7968
7969            if (DEBUG_INSTALL) {
7970                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7971            }
7972
7973            if (grant != GRANT_DENIED) {
7974                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7975                    // If this is an existing, non-system package, then
7976                    // we can't add any new permissions to it.
7977                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7978                        // Except...  if this is a permission that was added
7979                        // to the platform (note: need to only do this when
7980                        // updating the platform).
7981                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7982                            grant = GRANT_DENIED;
7983                        }
7984                    }
7985                }
7986
7987                switch (grant) {
7988                    case GRANT_INSTALL: {
7989                        // Revoke this as runtime permission to handle the case of
7990                        // a runtime permission being downgraded to an install one.
7991                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7992                            if (origPermissions.getRuntimePermissionState(
7993                                    bp.name, userId) != null) {
7994                                // Revoke the runtime permission and clear the flags.
7995                                origPermissions.revokeRuntimePermission(bp, userId);
7996                                origPermissions.updatePermissionFlags(bp, userId,
7997                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7998                                // If we revoked a permission permission, we have to write.
7999                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8000                                        changedRuntimePermissionUserIds, userId);
8001                            }
8002                        }
8003                        // Grant an install permission.
8004                        if (permissionsState.grantInstallPermission(bp) !=
8005                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8006                            changedInstallPermission = true;
8007                        }
8008                    } break;
8009
8010                    case GRANT_INSTALL_LEGACY: {
8011                        // Grant an install permission.
8012                        if (permissionsState.grantInstallPermission(bp) !=
8013                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8014                            changedInstallPermission = true;
8015                        }
8016                    } break;
8017
8018                    case GRANT_RUNTIME: {
8019                        // Grant previously granted runtime permissions.
8020                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8021                            PermissionState permissionState = origPermissions
8022                                    .getRuntimePermissionState(bp.name, userId);
8023                            final int flags = permissionState != null
8024                                    ? permissionState.getFlags() : 0;
8025                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8026                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8027                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8028                                    // If we cannot put the permission as it was, we have to write.
8029                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8030                                            changedRuntimePermissionUserIds, userId);
8031                                }
8032                            }
8033                            // Propagate the permission flags.
8034                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8035                        }
8036                    } break;
8037
8038                    case GRANT_UPGRADE: {
8039                        // Grant runtime permissions for a previously held install permission.
8040                        PermissionState permissionState = origPermissions
8041                                .getInstallPermissionState(bp.name);
8042                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8043
8044                        if (origPermissions.revokeInstallPermission(bp)
8045                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8046                            // We will be transferring the permission flags, so clear them.
8047                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8048                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8049                            changedInstallPermission = true;
8050                        }
8051
8052                        // If the permission is not to be promoted to runtime we ignore it and
8053                        // also its other flags as they are not applicable to install permissions.
8054                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8055                            for (int userId : currentUserIds) {
8056                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8057                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8058                                    // Transfer the permission flags.
8059                                    permissionsState.updatePermissionFlags(bp, userId,
8060                                            flags, flags);
8061                                    // If we granted the permission, we have to write.
8062                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8063                                            changedRuntimePermissionUserIds, userId);
8064                                }
8065                            }
8066                        }
8067                    } break;
8068
8069                    default: {
8070                        if (packageOfInterest == null
8071                                || packageOfInterest.equals(pkg.packageName)) {
8072                            Slog.w(TAG, "Not granting permission " + perm
8073                                    + " to package " + pkg.packageName
8074                                    + " because it was previously installed without");
8075                        }
8076                    } break;
8077                }
8078            } else {
8079                if (permissionsState.revokeInstallPermission(bp) !=
8080                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8081                    // Also drop the permission flags.
8082                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8083                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8084                    changedInstallPermission = true;
8085                    Slog.i(TAG, "Un-granting permission " + perm
8086                            + " from package " + pkg.packageName
8087                            + " (protectionLevel=" + bp.protectionLevel
8088                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8089                            + ")");
8090                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8091                    // Don't print warning for app op permissions, since it is fine for them
8092                    // not to be granted, there is a UI for the user to decide.
8093                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8094                        Slog.w(TAG, "Not granting permission " + perm
8095                                + " to package " + pkg.packageName
8096                                + " (protectionLevel=" + bp.protectionLevel
8097                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8098                                + ")");
8099                    }
8100                }
8101            }
8102        }
8103
8104        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8105                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8106            // This is the first that we have heard about this package, so the
8107            // permissions we have now selected are fixed until explicitly
8108            // changed.
8109            ps.installPermissionsFixed = true;
8110        }
8111
8112        // Persist the runtime permissions state for users with changes.
8113        for (int userId : changedRuntimePermissionUserIds) {
8114            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8115        }
8116    }
8117
8118    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8119        boolean allowed = false;
8120        final int NP = PackageParser.NEW_PERMISSIONS.length;
8121        for (int ip=0; ip<NP; ip++) {
8122            final PackageParser.NewPermissionInfo npi
8123                    = PackageParser.NEW_PERMISSIONS[ip];
8124            if (npi.name.equals(perm)
8125                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8126                allowed = true;
8127                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8128                        + pkg.packageName);
8129                break;
8130            }
8131        }
8132        return allowed;
8133    }
8134
8135    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8136            BasePermission bp, PermissionsState origPermissions) {
8137        boolean allowed;
8138        allowed = (compareSignatures(
8139                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8140                        == PackageManager.SIGNATURE_MATCH)
8141                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8142                        == PackageManager.SIGNATURE_MATCH);
8143        if (!allowed && (bp.protectionLevel
8144                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8145            if (isSystemApp(pkg)) {
8146                // For updated system applications, a system permission
8147                // is granted only if it had been defined by the original application.
8148                if (pkg.isUpdatedSystemApp()) {
8149                    final PackageSetting sysPs = mSettings
8150                            .getDisabledSystemPkgLPr(pkg.packageName);
8151                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8152                        // If the original was granted this permission, we take
8153                        // that grant decision as read and propagate it to the
8154                        // update.
8155                        if (sysPs.isPrivileged()) {
8156                            allowed = true;
8157                        }
8158                    } else {
8159                        // The system apk may have been updated with an older
8160                        // version of the one on the data partition, but which
8161                        // granted a new system permission that it didn't have
8162                        // before.  In this case we do want to allow the app to
8163                        // now get the new permission if the ancestral apk is
8164                        // privileged to get it.
8165                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8166                            for (int j=0;
8167                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8168                                if (perm.equals(
8169                                        sysPs.pkg.requestedPermissions.get(j))) {
8170                                    allowed = true;
8171                                    break;
8172                                }
8173                            }
8174                        }
8175                    }
8176                } else {
8177                    allowed = isPrivilegedApp(pkg);
8178                }
8179            }
8180        }
8181        if (!allowed && (bp.protectionLevel
8182                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8183            // For development permissions, a development permission
8184            // is granted only if it was already granted.
8185            allowed = origPermissions.hasInstallPermission(perm);
8186        }
8187        return allowed;
8188    }
8189
8190    final class ActivityIntentResolver
8191            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8192        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8193                boolean defaultOnly, int userId) {
8194            if (!sUserManager.exists(userId)) return null;
8195            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8196            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8197        }
8198
8199        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8200                int userId) {
8201            if (!sUserManager.exists(userId)) return null;
8202            mFlags = flags;
8203            return super.queryIntent(intent, resolvedType,
8204                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8205        }
8206
8207        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8208                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8209            if (!sUserManager.exists(userId)) return null;
8210            if (packageActivities == null) {
8211                return null;
8212            }
8213            mFlags = flags;
8214            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8215            final int N = packageActivities.size();
8216            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8217                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8218
8219            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8220            for (int i = 0; i < N; ++i) {
8221                intentFilters = packageActivities.get(i).intents;
8222                if (intentFilters != null && intentFilters.size() > 0) {
8223                    PackageParser.ActivityIntentInfo[] array =
8224                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8225                    intentFilters.toArray(array);
8226                    listCut.add(array);
8227                }
8228            }
8229            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8230        }
8231
8232        public final void addActivity(PackageParser.Activity a, String type) {
8233            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8234            mActivities.put(a.getComponentName(), a);
8235            if (DEBUG_SHOW_INFO)
8236                Log.v(
8237                TAG, "  " + type + " " +
8238                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8239            if (DEBUG_SHOW_INFO)
8240                Log.v(TAG, "    Class=" + a.info.name);
8241            final int NI = a.intents.size();
8242            for (int j=0; j<NI; j++) {
8243                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8244                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8245                    intent.setPriority(0);
8246                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8247                            + a.className + " with priority > 0, forcing to 0");
8248                }
8249                if (DEBUG_SHOW_INFO) {
8250                    Log.v(TAG, "    IntentFilter:");
8251                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8252                }
8253                if (!intent.debugCheck()) {
8254                    Log.w(TAG, "==> For Activity " + a.info.name);
8255                }
8256                addFilter(intent);
8257            }
8258        }
8259
8260        public final void removeActivity(PackageParser.Activity a, String type) {
8261            mActivities.remove(a.getComponentName());
8262            if (DEBUG_SHOW_INFO) {
8263                Log.v(TAG, "  " + type + " "
8264                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8265                                : a.info.name) + ":");
8266                Log.v(TAG, "    Class=" + a.info.name);
8267            }
8268            final int NI = a.intents.size();
8269            for (int j=0; j<NI; j++) {
8270                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8271                if (DEBUG_SHOW_INFO) {
8272                    Log.v(TAG, "    IntentFilter:");
8273                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8274                }
8275                removeFilter(intent);
8276            }
8277        }
8278
8279        @Override
8280        protected boolean allowFilterResult(
8281                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8282            ActivityInfo filterAi = filter.activity.info;
8283            for (int i=dest.size()-1; i>=0; i--) {
8284                ActivityInfo destAi = dest.get(i).activityInfo;
8285                if (destAi.name == filterAi.name
8286                        && destAi.packageName == filterAi.packageName) {
8287                    return false;
8288                }
8289            }
8290            return true;
8291        }
8292
8293        @Override
8294        protected ActivityIntentInfo[] newArray(int size) {
8295            return new ActivityIntentInfo[size];
8296        }
8297
8298        @Override
8299        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8300            if (!sUserManager.exists(userId)) return true;
8301            PackageParser.Package p = filter.activity.owner;
8302            if (p != null) {
8303                PackageSetting ps = (PackageSetting)p.mExtras;
8304                if (ps != null) {
8305                    // System apps are never considered stopped for purposes of
8306                    // filtering, because there may be no way for the user to
8307                    // actually re-launch them.
8308                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8309                            && ps.getStopped(userId);
8310                }
8311            }
8312            return false;
8313        }
8314
8315        @Override
8316        protected boolean isPackageForFilter(String packageName,
8317                PackageParser.ActivityIntentInfo info) {
8318            return packageName.equals(info.activity.owner.packageName);
8319        }
8320
8321        @Override
8322        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8323                int match, int userId) {
8324            if (!sUserManager.exists(userId)) return null;
8325            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8326                return null;
8327            }
8328            final PackageParser.Activity activity = info.activity;
8329            if (mSafeMode && (activity.info.applicationInfo.flags
8330                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8331                return null;
8332            }
8333            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8334            if (ps == null) {
8335                return null;
8336            }
8337            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8338                    ps.readUserState(userId), userId);
8339            if (ai == null) {
8340                return null;
8341            }
8342            final ResolveInfo res = new ResolveInfo();
8343            res.activityInfo = ai;
8344            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8345                res.filter = info;
8346            }
8347            if (info != null) {
8348                res.handleAllWebDataURI = info.handleAllWebDataURI();
8349            }
8350            res.priority = info.getPriority();
8351            res.preferredOrder = activity.owner.mPreferredOrder;
8352            //System.out.println("Result: " + res.activityInfo.className +
8353            //                   " = " + res.priority);
8354            res.match = match;
8355            res.isDefault = info.hasDefault;
8356            res.labelRes = info.labelRes;
8357            res.nonLocalizedLabel = info.nonLocalizedLabel;
8358            if (userNeedsBadging(userId)) {
8359                res.noResourceId = true;
8360            } else {
8361                res.icon = info.icon;
8362            }
8363            res.iconResourceId = info.icon;
8364            res.system = res.activityInfo.applicationInfo.isSystemApp();
8365            return res;
8366        }
8367
8368        @Override
8369        protected void sortResults(List<ResolveInfo> results) {
8370            Collections.sort(results, mResolvePrioritySorter);
8371        }
8372
8373        @Override
8374        protected void dumpFilter(PrintWriter out, String prefix,
8375                PackageParser.ActivityIntentInfo filter) {
8376            out.print(prefix); out.print(
8377                    Integer.toHexString(System.identityHashCode(filter.activity)));
8378                    out.print(' ');
8379                    filter.activity.printComponentShortName(out);
8380                    out.print(" filter ");
8381                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8382        }
8383
8384        @Override
8385        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8386            return filter.activity;
8387        }
8388
8389        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8390            PackageParser.Activity activity = (PackageParser.Activity)label;
8391            out.print(prefix); out.print(
8392                    Integer.toHexString(System.identityHashCode(activity)));
8393                    out.print(' ');
8394                    activity.printComponentShortName(out);
8395            if (count > 1) {
8396                out.print(" ("); out.print(count); out.print(" filters)");
8397            }
8398            out.println();
8399        }
8400
8401//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8402//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8403//            final List<ResolveInfo> retList = Lists.newArrayList();
8404//            while (i.hasNext()) {
8405//                final ResolveInfo resolveInfo = i.next();
8406//                if (isEnabledLP(resolveInfo.activityInfo)) {
8407//                    retList.add(resolveInfo);
8408//                }
8409//            }
8410//            return retList;
8411//        }
8412
8413        // Keys are String (activity class name), values are Activity.
8414        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8415                = new ArrayMap<ComponentName, PackageParser.Activity>();
8416        private int mFlags;
8417    }
8418
8419    private final class ServiceIntentResolver
8420            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8421        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8422                boolean defaultOnly, int userId) {
8423            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8424            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8425        }
8426
8427        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8428                int userId) {
8429            if (!sUserManager.exists(userId)) return null;
8430            mFlags = flags;
8431            return super.queryIntent(intent, resolvedType,
8432                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8433        }
8434
8435        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8436                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8437            if (!sUserManager.exists(userId)) return null;
8438            if (packageServices == null) {
8439                return null;
8440            }
8441            mFlags = flags;
8442            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8443            final int N = packageServices.size();
8444            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8445                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8446
8447            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8448            for (int i = 0; i < N; ++i) {
8449                intentFilters = packageServices.get(i).intents;
8450                if (intentFilters != null && intentFilters.size() > 0) {
8451                    PackageParser.ServiceIntentInfo[] array =
8452                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8453                    intentFilters.toArray(array);
8454                    listCut.add(array);
8455                }
8456            }
8457            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8458        }
8459
8460        public final void addService(PackageParser.Service s) {
8461            mServices.put(s.getComponentName(), s);
8462            if (DEBUG_SHOW_INFO) {
8463                Log.v(TAG, "  "
8464                        + (s.info.nonLocalizedLabel != null
8465                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8466                Log.v(TAG, "    Class=" + s.info.name);
8467            }
8468            final int NI = s.intents.size();
8469            int j;
8470            for (j=0; j<NI; j++) {
8471                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8472                if (DEBUG_SHOW_INFO) {
8473                    Log.v(TAG, "    IntentFilter:");
8474                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8475                }
8476                if (!intent.debugCheck()) {
8477                    Log.w(TAG, "==> For Service " + s.info.name);
8478                }
8479                addFilter(intent);
8480            }
8481        }
8482
8483        public final void removeService(PackageParser.Service s) {
8484            mServices.remove(s.getComponentName());
8485            if (DEBUG_SHOW_INFO) {
8486                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8487                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8488                Log.v(TAG, "    Class=" + s.info.name);
8489            }
8490            final int NI = s.intents.size();
8491            int j;
8492            for (j=0; j<NI; j++) {
8493                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8494                if (DEBUG_SHOW_INFO) {
8495                    Log.v(TAG, "    IntentFilter:");
8496                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8497                }
8498                removeFilter(intent);
8499            }
8500        }
8501
8502        @Override
8503        protected boolean allowFilterResult(
8504                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8505            ServiceInfo filterSi = filter.service.info;
8506            for (int i=dest.size()-1; i>=0; i--) {
8507                ServiceInfo destAi = dest.get(i).serviceInfo;
8508                if (destAi.name == filterSi.name
8509                        && destAi.packageName == filterSi.packageName) {
8510                    return false;
8511                }
8512            }
8513            return true;
8514        }
8515
8516        @Override
8517        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8518            return new PackageParser.ServiceIntentInfo[size];
8519        }
8520
8521        @Override
8522        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8523            if (!sUserManager.exists(userId)) return true;
8524            PackageParser.Package p = filter.service.owner;
8525            if (p != null) {
8526                PackageSetting ps = (PackageSetting)p.mExtras;
8527                if (ps != null) {
8528                    // System apps are never considered stopped for purposes of
8529                    // filtering, because there may be no way for the user to
8530                    // actually re-launch them.
8531                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8532                            && ps.getStopped(userId);
8533                }
8534            }
8535            return false;
8536        }
8537
8538        @Override
8539        protected boolean isPackageForFilter(String packageName,
8540                PackageParser.ServiceIntentInfo info) {
8541            return packageName.equals(info.service.owner.packageName);
8542        }
8543
8544        @Override
8545        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8546                int match, int userId) {
8547            if (!sUserManager.exists(userId)) return null;
8548            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8549            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8550                return null;
8551            }
8552            final PackageParser.Service service = info.service;
8553            if (mSafeMode && (service.info.applicationInfo.flags
8554                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8555                return null;
8556            }
8557            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8558            if (ps == null) {
8559                return null;
8560            }
8561            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8562                    ps.readUserState(userId), userId);
8563            if (si == null) {
8564                return null;
8565            }
8566            final ResolveInfo res = new ResolveInfo();
8567            res.serviceInfo = si;
8568            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8569                res.filter = filter;
8570            }
8571            res.priority = info.getPriority();
8572            res.preferredOrder = service.owner.mPreferredOrder;
8573            res.match = match;
8574            res.isDefault = info.hasDefault;
8575            res.labelRes = info.labelRes;
8576            res.nonLocalizedLabel = info.nonLocalizedLabel;
8577            res.icon = info.icon;
8578            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8579            return res;
8580        }
8581
8582        @Override
8583        protected void sortResults(List<ResolveInfo> results) {
8584            Collections.sort(results, mResolvePrioritySorter);
8585        }
8586
8587        @Override
8588        protected void dumpFilter(PrintWriter out, String prefix,
8589                PackageParser.ServiceIntentInfo filter) {
8590            out.print(prefix); out.print(
8591                    Integer.toHexString(System.identityHashCode(filter.service)));
8592                    out.print(' ');
8593                    filter.service.printComponentShortName(out);
8594                    out.print(" filter ");
8595                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8596        }
8597
8598        @Override
8599        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8600            return filter.service;
8601        }
8602
8603        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8604            PackageParser.Service service = (PackageParser.Service)label;
8605            out.print(prefix); out.print(
8606                    Integer.toHexString(System.identityHashCode(service)));
8607                    out.print(' ');
8608                    service.printComponentShortName(out);
8609            if (count > 1) {
8610                out.print(" ("); out.print(count); out.print(" filters)");
8611            }
8612            out.println();
8613        }
8614
8615//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8616//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8617//            final List<ResolveInfo> retList = Lists.newArrayList();
8618//            while (i.hasNext()) {
8619//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8620//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8621//                    retList.add(resolveInfo);
8622//                }
8623//            }
8624//            return retList;
8625//        }
8626
8627        // Keys are String (activity class name), values are Activity.
8628        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8629                = new ArrayMap<ComponentName, PackageParser.Service>();
8630        private int mFlags;
8631    };
8632
8633    private final class ProviderIntentResolver
8634            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8635        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8636                boolean defaultOnly, int userId) {
8637            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8638            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8639        }
8640
8641        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8642                int userId) {
8643            if (!sUserManager.exists(userId))
8644                return null;
8645            mFlags = flags;
8646            return super.queryIntent(intent, resolvedType,
8647                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8648        }
8649
8650        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8651                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8652            if (!sUserManager.exists(userId))
8653                return null;
8654            if (packageProviders == null) {
8655                return null;
8656            }
8657            mFlags = flags;
8658            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8659            final int N = packageProviders.size();
8660            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8661                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8662
8663            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8664            for (int i = 0; i < N; ++i) {
8665                intentFilters = packageProviders.get(i).intents;
8666                if (intentFilters != null && intentFilters.size() > 0) {
8667                    PackageParser.ProviderIntentInfo[] array =
8668                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8669                    intentFilters.toArray(array);
8670                    listCut.add(array);
8671                }
8672            }
8673            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8674        }
8675
8676        public final void addProvider(PackageParser.Provider p) {
8677            if (mProviders.containsKey(p.getComponentName())) {
8678                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8679                return;
8680            }
8681
8682            mProviders.put(p.getComponentName(), p);
8683            if (DEBUG_SHOW_INFO) {
8684                Log.v(TAG, "  "
8685                        + (p.info.nonLocalizedLabel != null
8686                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8687                Log.v(TAG, "    Class=" + p.info.name);
8688            }
8689            final int NI = p.intents.size();
8690            int j;
8691            for (j = 0; j < NI; j++) {
8692                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8693                if (DEBUG_SHOW_INFO) {
8694                    Log.v(TAG, "    IntentFilter:");
8695                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8696                }
8697                if (!intent.debugCheck()) {
8698                    Log.w(TAG, "==> For Provider " + p.info.name);
8699                }
8700                addFilter(intent);
8701            }
8702        }
8703
8704        public final void removeProvider(PackageParser.Provider p) {
8705            mProviders.remove(p.getComponentName());
8706            if (DEBUG_SHOW_INFO) {
8707                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8708                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8709                Log.v(TAG, "    Class=" + p.info.name);
8710            }
8711            final int NI = p.intents.size();
8712            int j;
8713            for (j = 0; j < NI; j++) {
8714                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8715                if (DEBUG_SHOW_INFO) {
8716                    Log.v(TAG, "    IntentFilter:");
8717                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8718                }
8719                removeFilter(intent);
8720            }
8721        }
8722
8723        @Override
8724        protected boolean allowFilterResult(
8725                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8726            ProviderInfo filterPi = filter.provider.info;
8727            for (int i = dest.size() - 1; i >= 0; i--) {
8728                ProviderInfo destPi = dest.get(i).providerInfo;
8729                if (destPi.name == filterPi.name
8730                        && destPi.packageName == filterPi.packageName) {
8731                    return false;
8732                }
8733            }
8734            return true;
8735        }
8736
8737        @Override
8738        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8739            return new PackageParser.ProviderIntentInfo[size];
8740        }
8741
8742        @Override
8743        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8744            if (!sUserManager.exists(userId))
8745                return true;
8746            PackageParser.Package p = filter.provider.owner;
8747            if (p != null) {
8748                PackageSetting ps = (PackageSetting) p.mExtras;
8749                if (ps != null) {
8750                    // System apps are never considered stopped for purposes of
8751                    // filtering, because there may be no way for the user to
8752                    // actually re-launch them.
8753                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8754                            && ps.getStopped(userId);
8755                }
8756            }
8757            return false;
8758        }
8759
8760        @Override
8761        protected boolean isPackageForFilter(String packageName,
8762                PackageParser.ProviderIntentInfo info) {
8763            return packageName.equals(info.provider.owner.packageName);
8764        }
8765
8766        @Override
8767        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8768                int match, int userId) {
8769            if (!sUserManager.exists(userId))
8770                return null;
8771            final PackageParser.ProviderIntentInfo info = filter;
8772            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8773                return null;
8774            }
8775            final PackageParser.Provider provider = info.provider;
8776            if (mSafeMode && (provider.info.applicationInfo.flags
8777                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8778                return null;
8779            }
8780            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8781            if (ps == null) {
8782                return null;
8783            }
8784            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8785                    ps.readUserState(userId), userId);
8786            if (pi == null) {
8787                return null;
8788            }
8789            final ResolveInfo res = new ResolveInfo();
8790            res.providerInfo = pi;
8791            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8792                res.filter = filter;
8793            }
8794            res.priority = info.getPriority();
8795            res.preferredOrder = provider.owner.mPreferredOrder;
8796            res.match = match;
8797            res.isDefault = info.hasDefault;
8798            res.labelRes = info.labelRes;
8799            res.nonLocalizedLabel = info.nonLocalizedLabel;
8800            res.icon = info.icon;
8801            res.system = res.providerInfo.applicationInfo.isSystemApp();
8802            return res;
8803        }
8804
8805        @Override
8806        protected void sortResults(List<ResolveInfo> results) {
8807            Collections.sort(results, mResolvePrioritySorter);
8808        }
8809
8810        @Override
8811        protected void dumpFilter(PrintWriter out, String prefix,
8812                PackageParser.ProviderIntentInfo filter) {
8813            out.print(prefix);
8814            out.print(
8815                    Integer.toHexString(System.identityHashCode(filter.provider)));
8816            out.print(' ');
8817            filter.provider.printComponentShortName(out);
8818            out.print(" filter ");
8819            out.println(Integer.toHexString(System.identityHashCode(filter)));
8820        }
8821
8822        @Override
8823        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8824            return filter.provider;
8825        }
8826
8827        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8828            PackageParser.Provider provider = (PackageParser.Provider)label;
8829            out.print(prefix); out.print(
8830                    Integer.toHexString(System.identityHashCode(provider)));
8831                    out.print(' ');
8832                    provider.printComponentShortName(out);
8833            if (count > 1) {
8834                out.print(" ("); out.print(count); out.print(" filters)");
8835            }
8836            out.println();
8837        }
8838
8839        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8840                = new ArrayMap<ComponentName, PackageParser.Provider>();
8841        private int mFlags;
8842    };
8843
8844    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8845            new Comparator<ResolveInfo>() {
8846        public int compare(ResolveInfo r1, ResolveInfo r2) {
8847            int v1 = r1.priority;
8848            int v2 = r2.priority;
8849            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8850            if (v1 != v2) {
8851                return (v1 > v2) ? -1 : 1;
8852            }
8853            v1 = r1.preferredOrder;
8854            v2 = r2.preferredOrder;
8855            if (v1 != v2) {
8856                return (v1 > v2) ? -1 : 1;
8857            }
8858            if (r1.isDefault != r2.isDefault) {
8859                return r1.isDefault ? -1 : 1;
8860            }
8861            v1 = r1.match;
8862            v2 = r2.match;
8863            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8864            if (v1 != v2) {
8865                return (v1 > v2) ? -1 : 1;
8866            }
8867            if (r1.system != r2.system) {
8868                return r1.system ? -1 : 1;
8869            }
8870            return 0;
8871        }
8872    };
8873
8874    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8875            new Comparator<ProviderInfo>() {
8876        public int compare(ProviderInfo p1, ProviderInfo p2) {
8877            final int v1 = p1.initOrder;
8878            final int v2 = p2.initOrder;
8879            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8880        }
8881    };
8882
8883    final void sendPackageBroadcast(final String action, final String pkg,
8884            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8885            final int[] userIds) {
8886        mHandler.post(new Runnable() {
8887            @Override
8888            public void run() {
8889                try {
8890                    final IActivityManager am = ActivityManagerNative.getDefault();
8891                    if (am == null) return;
8892                    final int[] resolvedUserIds;
8893                    if (userIds == null) {
8894                        resolvedUserIds = am.getRunningUserIds();
8895                    } else {
8896                        resolvedUserIds = userIds;
8897                    }
8898                    for (int id : resolvedUserIds) {
8899                        final Intent intent = new Intent(action,
8900                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8901                        if (extras != null) {
8902                            intent.putExtras(extras);
8903                        }
8904                        if (targetPkg != null) {
8905                            intent.setPackage(targetPkg);
8906                        }
8907                        // Modify the UID when posting to other users
8908                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8909                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8910                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8911                            intent.putExtra(Intent.EXTRA_UID, uid);
8912                        }
8913                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8914                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8915                        if (DEBUG_BROADCASTS) {
8916                            RuntimeException here = new RuntimeException("here");
8917                            here.fillInStackTrace();
8918                            Slog.d(TAG, "Sending to user " + id + ": "
8919                                    + intent.toShortString(false, true, false, false)
8920                                    + " " + intent.getExtras(), here);
8921                        }
8922                        am.broadcastIntent(null, intent, null, finishedReceiver,
8923                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8924                                null, finishedReceiver != null, false, id);
8925                    }
8926                } catch (RemoteException ex) {
8927                }
8928            }
8929        });
8930    }
8931
8932    /**
8933     * Check if the external storage media is available. This is true if there
8934     * is a mounted external storage medium or if the external storage is
8935     * emulated.
8936     */
8937    private boolean isExternalMediaAvailable() {
8938        return mMediaMounted || Environment.isExternalStorageEmulated();
8939    }
8940
8941    @Override
8942    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8943        // writer
8944        synchronized (mPackages) {
8945            if (!isExternalMediaAvailable()) {
8946                // If the external storage is no longer mounted at this point,
8947                // the caller may not have been able to delete all of this
8948                // packages files and can not delete any more.  Bail.
8949                return null;
8950            }
8951            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8952            if (lastPackage != null) {
8953                pkgs.remove(lastPackage);
8954            }
8955            if (pkgs.size() > 0) {
8956                return pkgs.get(0);
8957            }
8958        }
8959        return null;
8960    }
8961
8962    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8963        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8964                userId, andCode ? 1 : 0, packageName);
8965        if (mSystemReady) {
8966            msg.sendToTarget();
8967        } else {
8968            if (mPostSystemReadyMessages == null) {
8969                mPostSystemReadyMessages = new ArrayList<>();
8970            }
8971            mPostSystemReadyMessages.add(msg);
8972        }
8973    }
8974
8975    void startCleaningPackages() {
8976        // reader
8977        synchronized (mPackages) {
8978            if (!isExternalMediaAvailable()) {
8979                return;
8980            }
8981            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8982                return;
8983            }
8984        }
8985        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8986        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8987        IActivityManager am = ActivityManagerNative.getDefault();
8988        if (am != null) {
8989            try {
8990                am.startService(null, intent, null, UserHandle.USER_OWNER);
8991            } catch (RemoteException e) {
8992            }
8993        }
8994    }
8995
8996    @Override
8997    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8998            int installFlags, String installerPackageName, VerificationParams verificationParams,
8999            String packageAbiOverride) {
9000        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9001                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9002    }
9003
9004    @Override
9005    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9006            int installFlags, String installerPackageName, VerificationParams verificationParams,
9007            String packageAbiOverride, int userId) {
9008        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9009
9010        final int callingUid = Binder.getCallingUid();
9011        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9012
9013        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9014            try {
9015                if (observer != null) {
9016                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9017                }
9018            } catch (RemoteException re) {
9019            }
9020            return;
9021        }
9022
9023        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9024            installFlags |= PackageManager.INSTALL_FROM_ADB;
9025
9026        } else {
9027            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9028            // about installerPackageName.
9029
9030            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9031            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9032        }
9033
9034        UserHandle user;
9035        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9036            user = UserHandle.ALL;
9037        } else {
9038            user = new UserHandle(userId);
9039        }
9040
9041        // Only system components can circumvent runtime permissions when installing.
9042        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9043                && mContext.checkCallingOrSelfPermission(Manifest.permission
9044                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9045            throw new SecurityException("You need the "
9046                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9047                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9048        }
9049
9050        verificationParams.setInstallerUid(callingUid);
9051
9052        final File originFile = new File(originPath);
9053        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9054
9055        final Message msg = mHandler.obtainMessage(INIT_COPY);
9056        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9057                null, verificationParams, user, packageAbiOverride);
9058        mHandler.sendMessage(msg);
9059    }
9060
9061    void installStage(String packageName, File stagedDir, String stagedCid,
9062            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9063            String installerPackageName, int installerUid, UserHandle user) {
9064        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9065                params.referrerUri, installerUid, null);
9066
9067        final OriginInfo origin;
9068        if (stagedDir != null) {
9069            origin = OriginInfo.fromStagedFile(stagedDir);
9070        } else {
9071            origin = OriginInfo.fromStagedContainer(stagedCid);
9072        }
9073
9074        final Message msg = mHandler.obtainMessage(INIT_COPY);
9075        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9076                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9077        mHandler.sendMessage(msg);
9078    }
9079
9080    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9081        Bundle extras = new Bundle(1);
9082        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9083
9084        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9085                packageName, extras, null, null, new int[] {userId});
9086        try {
9087            IActivityManager am = ActivityManagerNative.getDefault();
9088            final boolean isSystem =
9089                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9090            if (isSystem && am.isUserRunning(userId, false)) {
9091                // The just-installed/enabled app is bundled on the system, so presumed
9092                // to be able to run automatically without needing an explicit launch.
9093                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9094                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9095                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9096                        .setPackage(packageName);
9097                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9098                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9099            }
9100        } catch (RemoteException e) {
9101            // shouldn't happen
9102            Slog.w(TAG, "Unable to bootstrap installed package", e);
9103        }
9104    }
9105
9106    @Override
9107    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9108            int userId) {
9109        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9110        PackageSetting pkgSetting;
9111        final int uid = Binder.getCallingUid();
9112        enforceCrossUserPermission(uid, userId, true, true,
9113                "setApplicationHiddenSetting for user " + userId);
9114
9115        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9116            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9117            return false;
9118        }
9119
9120        long callingId = Binder.clearCallingIdentity();
9121        try {
9122            boolean sendAdded = false;
9123            boolean sendRemoved = false;
9124            // writer
9125            synchronized (mPackages) {
9126                pkgSetting = mSettings.mPackages.get(packageName);
9127                if (pkgSetting == null) {
9128                    return false;
9129                }
9130                if (pkgSetting.getHidden(userId) != hidden) {
9131                    pkgSetting.setHidden(hidden, userId);
9132                    mSettings.writePackageRestrictionsLPr(userId);
9133                    if (hidden) {
9134                        sendRemoved = true;
9135                    } else {
9136                        sendAdded = true;
9137                    }
9138                }
9139            }
9140            if (sendAdded) {
9141                sendPackageAddedForUser(packageName, pkgSetting, userId);
9142                return true;
9143            }
9144            if (sendRemoved) {
9145                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9146                        "hiding pkg");
9147                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9148            }
9149        } finally {
9150            Binder.restoreCallingIdentity(callingId);
9151        }
9152        return false;
9153    }
9154
9155    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9156            int userId) {
9157        final PackageRemovedInfo info = new PackageRemovedInfo();
9158        info.removedPackage = packageName;
9159        info.removedUsers = new int[] {userId};
9160        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9161        info.sendBroadcast(false, false, false);
9162    }
9163
9164    /**
9165     * Returns true if application is not found or there was an error. Otherwise it returns
9166     * the hidden state of the package for the given user.
9167     */
9168    @Override
9169    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9170        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9171        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9172                false, "getApplicationHidden for user " + userId);
9173        PackageSetting pkgSetting;
9174        long callingId = Binder.clearCallingIdentity();
9175        try {
9176            // writer
9177            synchronized (mPackages) {
9178                pkgSetting = mSettings.mPackages.get(packageName);
9179                if (pkgSetting == null) {
9180                    return true;
9181                }
9182                return pkgSetting.getHidden(userId);
9183            }
9184        } finally {
9185            Binder.restoreCallingIdentity(callingId);
9186        }
9187    }
9188
9189    /**
9190     * @hide
9191     */
9192    @Override
9193    public int installExistingPackageAsUser(String packageName, int userId) {
9194        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9195                null);
9196        PackageSetting pkgSetting;
9197        final int uid = Binder.getCallingUid();
9198        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9199                + userId);
9200        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9201            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9202        }
9203
9204        long callingId = Binder.clearCallingIdentity();
9205        try {
9206            boolean sendAdded = false;
9207
9208            // writer
9209            synchronized (mPackages) {
9210                pkgSetting = mSettings.mPackages.get(packageName);
9211                if (pkgSetting == null) {
9212                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9213                }
9214                if (!pkgSetting.getInstalled(userId)) {
9215                    pkgSetting.setInstalled(true, userId);
9216                    pkgSetting.setHidden(false, userId);
9217                    mSettings.writePackageRestrictionsLPr(userId);
9218                    sendAdded = true;
9219                }
9220            }
9221
9222            if (sendAdded) {
9223                sendPackageAddedForUser(packageName, pkgSetting, userId);
9224            }
9225        } finally {
9226            Binder.restoreCallingIdentity(callingId);
9227        }
9228
9229        return PackageManager.INSTALL_SUCCEEDED;
9230    }
9231
9232    boolean isUserRestricted(int userId, String restrictionKey) {
9233        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9234        if (restrictions.getBoolean(restrictionKey, false)) {
9235            Log.w(TAG, "User is restricted: " + restrictionKey);
9236            return true;
9237        }
9238        return false;
9239    }
9240
9241    @Override
9242    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9243        mContext.enforceCallingOrSelfPermission(
9244                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9245                "Only package verification agents can verify applications");
9246
9247        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9248        final PackageVerificationResponse response = new PackageVerificationResponse(
9249                verificationCode, Binder.getCallingUid());
9250        msg.arg1 = id;
9251        msg.obj = response;
9252        mHandler.sendMessage(msg);
9253    }
9254
9255    @Override
9256    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9257            long millisecondsToDelay) {
9258        mContext.enforceCallingOrSelfPermission(
9259                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9260                "Only package verification agents can extend verification timeouts");
9261
9262        final PackageVerificationState state = mPendingVerification.get(id);
9263        final PackageVerificationResponse response = new PackageVerificationResponse(
9264                verificationCodeAtTimeout, Binder.getCallingUid());
9265
9266        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9267            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9268        }
9269        if (millisecondsToDelay < 0) {
9270            millisecondsToDelay = 0;
9271        }
9272        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9273                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9274            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9275        }
9276
9277        if ((state != null) && !state.timeoutExtended()) {
9278            state.extendTimeout();
9279
9280            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9281            msg.arg1 = id;
9282            msg.obj = response;
9283            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9284        }
9285    }
9286
9287    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9288            int verificationCode, UserHandle user) {
9289        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9290        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9291        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9292        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9293        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9294
9295        mContext.sendBroadcastAsUser(intent, user,
9296                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9297    }
9298
9299    private ComponentName matchComponentForVerifier(String packageName,
9300            List<ResolveInfo> receivers) {
9301        ActivityInfo targetReceiver = null;
9302
9303        final int NR = receivers.size();
9304        for (int i = 0; i < NR; i++) {
9305            final ResolveInfo info = receivers.get(i);
9306            if (info.activityInfo == null) {
9307                continue;
9308            }
9309
9310            if (packageName.equals(info.activityInfo.packageName)) {
9311                targetReceiver = info.activityInfo;
9312                break;
9313            }
9314        }
9315
9316        if (targetReceiver == null) {
9317            return null;
9318        }
9319
9320        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9321    }
9322
9323    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9324            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9325        if (pkgInfo.verifiers.length == 0) {
9326            return null;
9327        }
9328
9329        final int N = pkgInfo.verifiers.length;
9330        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9331        for (int i = 0; i < N; i++) {
9332            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9333
9334            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9335                    receivers);
9336            if (comp == null) {
9337                continue;
9338            }
9339
9340            final int verifierUid = getUidForVerifier(verifierInfo);
9341            if (verifierUid == -1) {
9342                continue;
9343            }
9344
9345            if (DEBUG_VERIFY) {
9346                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9347                        + " with the correct signature");
9348            }
9349            sufficientVerifiers.add(comp);
9350            verificationState.addSufficientVerifier(verifierUid);
9351        }
9352
9353        return sufficientVerifiers;
9354    }
9355
9356    private int getUidForVerifier(VerifierInfo verifierInfo) {
9357        synchronized (mPackages) {
9358            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9359            if (pkg == null) {
9360                return -1;
9361            } else if (pkg.mSignatures.length != 1) {
9362                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9363                        + " has more than one signature; ignoring");
9364                return -1;
9365            }
9366
9367            /*
9368             * If the public key of the package's signature does not match
9369             * our expected public key, then this is a different package and
9370             * we should skip.
9371             */
9372
9373            final byte[] expectedPublicKey;
9374            try {
9375                final Signature verifierSig = pkg.mSignatures[0];
9376                final PublicKey publicKey = verifierSig.getPublicKey();
9377                expectedPublicKey = publicKey.getEncoded();
9378            } catch (CertificateException e) {
9379                return -1;
9380            }
9381
9382            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9383
9384            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9385                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9386                        + " does not have the expected public key; ignoring");
9387                return -1;
9388            }
9389
9390            return pkg.applicationInfo.uid;
9391        }
9392    }
9393
9394    @Override
9395    public void finishPackageInstall(int token) {
9396        enforceSystemOrRoot("Only the system is allowed to finish installs");
9397
9398        if (DEBUG_INSTALL) {
9399            Slog.v(TAG, "BM finishing package install for " + token);
9400        }
9401
9402        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9403        mHandler.sendMessage(msg);
9404    }
9405
9406    /**
9407     * Get the verification agent timeout.
9408     *
9409     * @return verification timeout in milliseconds
9410     */
9411    private long getVerificationTimeout() {
9412        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9413                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9414                DEFAULT_VERIFICATION_TIMEOUT);
9415    }
9416
9417    /**
9418     * Get the default verification agent response code.
9419     *
9420     * @return default verification response code
9421     */
9422    private int getDefaultVerificationResponse() {
9423        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9424                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9425                DEFAULT_VERIFICATION_RESPONSE);
9426    }
9427
9428    /**
9429     * Check whether or not package verification has been enabled.
9430     *
9431     * @return true if verification should be performed
9432     */
9433    private boolean isVerificationEnabled(int userId, int installFlags) {
9434        if (!DEFAULT_VERIFY_ENABLE) {
9435            return false;
9436        }
9437
9438        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9439
9440        // Check if installing from ADB
9441        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9442            // Do not run verification in a test harness environment
9443            if (ActivityManager.isRunningInTestHarness()) {
9444                return false;
9445            }
9446            if (ensureVerifyAppsEnabled) {
9447                return true;
9448            }
9449            // Check if the developer does not want package verification for ADB installs
9450            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9451                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9452                return false;
9453            }
9454        }
9455
9456        if (ensureVerifyAppsEnabled) {
9457            return true;
9458        }
9459
9460        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9461                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9462    }
9463
9464    @Override
9465    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9466            throws RemoteException {
9467        mContext.enforceCallingOrSelfPermission(
9468                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9469                "Only intentfilter verification agents can verify applications");
9470
9471        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9472        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9473                Binder.getCallingUid(), verificationCode, failedDomains);
9474        msg.arg1 = id;
9475        msg.obj = response;
9476        mHandler.sendMessage(msg);
9477    }
9478
9479    @Override
9480    public int getIntentVerificationStatus(String packageName, int userId) {
9481        synchronized (mPackages) {
9482            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9483        }
9484    }
9485
9486    @Override
9487    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9488        boolean result = false;
9489        synchronized (mPackages) {
9490            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9491        }
9492        if (result) {
9493            scheduleWritePackageRestrictionsLocked(userId);
9494        }
9495        return result;
9496    }
9497
9498    @Override
9499    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9500        synchronized (mPackages) {
9501            return mSettings.getIntentFilterVerificationsLPr(packageName);
9502        }
9503    }
9504
9505    @Override
9506    public List<IntentFilter> getAllIntentFilters(String packageName) {
9507        if (TextUtils.isEmpty(packageName)) {
9508            return Collections.<IntentFilter>emptyList();
9509        }
9510        synchronized (mPackages) {
9511            PackageParser.Package pkg = mPackages.get(packageName);
9512            if (pkg == null || pkg.activities == null) {
9513                return Collections.<IntentFilter>emptyList();
9514            }
9515            final int count = pkg.activities.size();
9516            ArrayList<IntentFilter> result = new ArrayList<>();
9517            for (int n=0; n<count; n++) {
9518                PackageParser.Activity activity = pkg.activities.get(n);
9519                if (activity.intents != null || activity.intents.size() > 0) {
9520                    result.addAll(activity.intents);
9521                }
9522            }
9523            return result;
9524        }
9525    }
9526
9527    @Override
9528    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9529        synchronized (mPackages) {
9530            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9531            if (packageName != null) {
9532                result |= updateIntentVerificationStatus(packageName,
9533                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9534                        UserHandle.myUserId());
9535            }
9536            return result;
9537        }
9538    }
9539
9540    @Override
9541    public String getDefaultBrowserPackageName(int userId) {
9542        synchronized (mPackages) {
9543            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9544        }
9545    }
9546
9547    /**
9548     * Get the "allow unknown sources" setting.
9549     *
9550     * @return the current "allow unknown sources" setting
9551     */
9552    private int getUnknownSourcesSettings() {
9553        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9554                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9555                -1);
9556    }
9557
9558    @Override
9559    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9560        final int uid = Binder.getCallingUid();
9561        // writer
9562        synchronized (mPackages) {
9563            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9564            if (targetPackageSetting == null) {
9565                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9566            }
9567
9568            PackageSetting installerPackageSetting;
9569            if (installerPackageName != null) {
9570                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9571                if (installerPackageSetting == null) {
9572                    throw new IllegalArgumentException("Unknown installer package: "
9573                            + installerPackageName);
9574                }
9575            } else {
9576                installerPackageSetting = null;
9577            }
9578
9579            Signature[] callerSignature;
9580            Object obj = mSettings.getUserIdLPr(uid);
9581            if (obj != null) {
9582                if (obj instanceof SharedUserSetting) {
9583                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9584                } else if (obj instanceof PackageSetting) {
9585                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9586                } else {
9587                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9588                }
9589            } else {
9590                throw new SecurityException("Unknown calling uid " + uid);
9591            }
9592
9593            // Verify: can't set installerPackageName to a package that is
9594            // not signed with the same cert as the caller.
9595            if (installerPackageSetting != null) {
9596                if (compareSignatures(callerSignature,
9597                        installerPackageSetting.signatures.mSignatures)
9598                        != PackageManager.SIGNATURE_MATCH) {
9599                    throw new SecurityException(
9600                            "Caller does not have same cert as new installer package "
9601                            + installerPackageName);
9602                }
9603            }
9604
9605            // Verify: if target already has an installer package, it must
9606            // be signed with the same cert as the caller.
9607            if (targetPackageSetting.installerPackageName != null) {
9608                PackageSetting setting = mSettings.mPackages.get(
9609                        targetPackageSetting.installerPackageName);
9610                // If the currently set package isn't valid, then it's always
9611                // okay to change it.
9612                if (setting != null) {
9613                    if (compareSignatures(callerSignature,
9614                            setting.signatures.mSignatures)
9615                            != PackageManager.SIGNATURE_MATCH) {
9616                        throw new SecurityException(
9617                                "Caller does not have same cert as old installer package "
9618                                + targetPackageSetting.installerPackageName);
9619                    }
9620                }
9621            }
9622
9623            // Okay!
9624            targetPackageSetting.installerPackageName = installerPackageName;
9625            scheduleWriteSettingsLocked();
9626        }
9627    }
9628
9629    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9630        // Queue up an async operation since the package installation may take a little while.
9631        mHandler.post(new Runnable() {
9632            public void run() {
9633                mHandler.removeCallbacks(this);
9634                 // Result object to be returned
9635                PackageInstalledInfo res = new PackageInstalledInfo();
9636                res.returnCode = currentStatus;
9637                res.uid = -1;
9638                res.pkg = null;
9639                res.removedInfo = new PackageRemovedInfo();
9640                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9641                    args.doPreInstall(res.returnCode);
9642                    synchronized (mInstallLock) {
9643                        installPackageLI(args, res);
9644                    }
9645                    args.doPostInstall(res.returnCode, res.uid);
9646                }
9647
9648                // A restore should be performed at this point if (a) the install
9649                // succeeded, (b) the operation is not an update, and (c) the new
9650                // package has not opted out of backup participation.
9651                final boolean update = res.removedInfo.removedPackage != null;
9652                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9653                boolean doRestore = !update
9654                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9655
9656                // Set up the post-install work request bookkeeping.  This will be used
9657                // and cleaned up by the post-install event handling regardless of whether
9658                // there's a restore pass performed.  Token values are >= 1.
9659                int token;
9660                if (mNextInstallToken < 0) mNextInstallToken = 1;
9661                token = mNextInstallToken++;
9662
9663                PostInstallData data = new PostInstallData(args, res);
9664                mRunningInstalls.put(token, data);
9665                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9666
9667                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9668                    // Pass responsibility to the Backup Manager.  It will perform a
9669                    // restore if appropriate, then pass responsibility back to the
9670                    // Package Manager to run the post-install observer callbacks
9671                    // and broadcasts.
9672                    IBackupManager bm = IBackupManager.Stub.asInterface(
9673                            ServiceManager.getService(Context.BACKUP_SERVICE));
9674                    if (bm != null) {
9675                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9676                                + " to BM for possible restore");
9677                        try {
9678                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9679                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9680                            } else {
9681                                doRestore = false;
9682                            }
9683                        } catch (RemoteException e) {
9684                            // can't happen; the backup manager is local
9685                        } catch (Exception e) {
9686                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9687                            doRestore = false;
9688                        }
9689                    } else {
9690                        Slog.e(TAG, "Backup Manager not found!");
9691                        doRestore = false;
9692                    }
9693                }
9694
9695                if (!doRestore) {
9696                    // No restore possible, or the Backup Manager was mysteriously not
9697                    // available -- just fire the post-install work request directly.
9698                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9699                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9700                    mHandler.sendMessage(msg);
9701                }
9702            }
9703        });
9704    }
9705
9706    private abstract class HandlerParams {
9707        private static final int MAX_RETRIES = 4;
9708
9709        /**
9710         * Number of times startCopy() has been attempted and had a non-fatal
9711         * error.
9712         */
9713        private int mRetries = 0;
9714
9715        /** User handle for the user requesting the information or installation. */
9716        private final UserHandle mUser;
9717
9718        HandlerParams(UserHandle user) {
9719            mUser = user;
9720        }
9721
9722        UserHandle getUser() {
9723            return mUser;
9724        }
9725
9726        final boolean startCopy() {
9727            boolean res;
9728            try {
9729                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9730
9731                if (++mRetries > MAX_RETRIES) {
9732                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9733                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9734                    handleServiceError();
9735                    return false;
9736                } else {
9737                    handleStartCopy();
9738                    res = true;
9739                }
9740            } catch (RemoteException e) {
9741                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9742                mHandler.sendEmptyMessage(MCS_RECONNECT);
9743                res = false;
9744            }
9745            handleReturnCode();
9746            return res;
9747        }
9748
9749        final void serviceError() {
9750            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9751            handleServiceError();
9752            handleReturnCode();
9753        }
9754
9755        abstract void handleStartCopy() throws RemoteException;
9756        abstract void handleServiceError();
9757        abstract void handleReturnCode();
9758    }
9759
9760    class MeasureParams extends HandlerParams {
9761        private final PackageStats mStats;
9762        private boolean mSuccess;
9763
9764        private final IPackageStatsObserver mObserver;
9765
9766        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9767            super(new UserHandle(stats.userHandle));
9768            mObserver = observer;
9769            mStats = stats;
9770        }
9771
9772        @Override
9773        public String toString() {
9774            return "MeasureParams{"
9775                + Integer.toHexString(System.identityHashCode(this))
9776                + " " + mStats.packageName + "}";
9777        }
9778
9779        @Override
9780        void handleStartCopy() throws RemoteException {
9781            synchronized (mInstallLock) {
9782                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9783            }
9784
9785            if (mSuccess) {
9786                final boolean mounted;
9787                if (Environment.isExternalStorageEmulated()) {
9788                    mounted = true;
9789                } else {
9790                    final String status = Environment.getExternalStorageState();
9791                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9792                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9793                }
9794
9795                if (mounted) {
9796                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9797
9798                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9799                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9800
9801                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9802                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9803
9804                    // Always subtract cache size, since it's a subdirectory
9805                    mStats.externalDataSize -= mStats.externalCacheSize;
9806
9807                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9808                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9809
9810                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9811                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9812                }
9813            }
9814        }
9815
9816        @Override
9817        void handleReturnCode() {
9818            if (mObserver != null) {
9819                try {
9820                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9821                } catch (RemoteException e) {
9822                    Slog.i(TAG, "Observer no longer exists.");
9823                }
9824            }
9825        }
9826
9827        @Override
9828        void handleServiceError() {
9829            Slog.e(TAG, "Could not measure application " + mStats.packageName
9830                            + " external storage");
9831        }
9832    }
9833
9834    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9835            throws RemoteException {
9836        long result = 0;
9837        for (File path : paths) {
9838            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9839        }
9840        return result;
9841    }
9842
9843    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9844        for (File path : paths) {
9845            try {
9846                mcs.clearDirectory(path.getAbsolutePath());
9847            } catch (RemoteException e) {
9848            }
9849        }
9850    }
9851
9852    static class OriginInfo {
9853        /**
9854         * Location where install is coming from, before it has been
9855         * copied/renamed into place. This could be a single monolithic APK
9856         * file, or a cluster directory. This location may be untrusted.
9857         */
9858        final File file;
9859        final String cid;
9860
9861        /**
9862         * Flag indicating that {@link #file} or {@link #cid} has already been
9863         * staged, meaning downstream users don't need to defensively copy the
9864         * contents.
9865         */
9866        final boolean staged;
9867
9868        /**
9869         * Flag indicating that {@link #file} or {@link #cid} is an already
9870         * installed app that is being moved.
9871         */
9872        final boolean existing;
9873
9874        final String resolvedPath;
9875        final File resolvedFile;
9876
9877        static OriginInfo fromNothing() {
9878            return new OriginInfo(null, null, false, false);
9879        }
9880
9881        static OriginInfo fromUntrustedFile(File file) {
9882            return new OriginInfo(file, null, false, false);
9883        }
9884
9885        static OriginInfo fromExistingFile(File file) {
9886            return new OriginInfo(file, null, false, true);
9887        }
9888
9889        static OriginInfo fromStagedFile(File file) {
9890            return new OriginInfo(file, null, true, false);
9891        }
9892
9893        static OriginInfo fromStagedContainer(String cid) {
9894            return new OriginInfo(null, cid, true, false);
9895        }
9896
9897        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9898            this.file = file;
9899            this.cid = cid;
9900            this.staged = staged;
9901            this.existing = existing;
9902
9903            if (cid != null) {
9904                resolvedPath = PackageHelper.getSdDir(cid);
9905                resolvedFile = new File(resolvedPath);
9906            } else if (file != null) {
9907                resolvedPath = file.getAbsolutePath();
9908                resolvedFile = file;
9909            } else {
9910                resolvedPath = null;
9911                resolvedFile = null;
9912            }
9913        }
9914    }
9915
9916    class MoveInfo {
9917        final int moveId;
9918        final String fromUuid;
9919        final String toUuid;
9920        final String packageName;
9921        final String dataAppName;
9922        final int appId;
9923        final String seinfo;
9924
9925        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9926                String dataAppName, int appId, String seinfo) {
9927            this.moveId = moveId;
9928            this.fromUuid = fromUuid;
9929            this.toUuid = toUuid;
9930            this.packageName = packageName;
9931            this.dataAppName = dataAppName;
9932            this.appId = appId;
9933            this.seinfo = seinfo;
9934        }
9935    }
9936
9937    class InstallParams extends HandlerParams {
9938        final OriginInfo origin;
9939        final MoveInfo move;
9940        final IPackageInstallObserver2 observer;
9941        int installFlags;
9942        final String installerPackageName;
9943        final String volumeUuid;
9944        final VerificationParams verificationParams;
9945        private InstallArgs mArgs;
9946        private int mRet;
9947        final String packageAbiOverride;
9948
9949        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9950                int installFlags, String installerPackageName, String volumeUuid,
9951                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9952            super(user);
9953            this.origin = origin;
9954            this.move = move;
9955            this.observer = observer;
9956            this.installFlags = installFlags;
9957            this.installerPackageName = installerPackageName;
9958            this.volumeUuid = volumeUuid;
9959            this.verificationParams = verificationParams;
9960            this.packageAbiOverride = packageAbiOverride;
9961        }
9962
9963        @Override
9964        public String toString() {
9965            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9966                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9967        }
9968
9969        public ManifestDigest getManifestDigest() {
9970            if (verificationParams == null) {
9971                return null;
9972            }
9973            return verificationParams.getManifestDigest();
9974        }
9975
9976        private int installLocationPolicy(PackageInfoLite pkgLite) {
9977            String packageName = pkgLite.packageName;
9978            int installLocation = pkgLite.installLocation;
9979            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9980            // reader
9981            synchronized (mPackages) {
9982                PackageParser.Package pkg = mPackages.get(packageName);
9983                if (pkg != null) {
9984                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9985                        // Check for downgrading.
9986                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9987                            try {
9988                                checkDowngrade(pkg, pkgLite);
9989                            } catch (PackageManagerException e) {
9990                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9991                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9992                            }
9993                        }
9994                        // Check for updated system application.
9995                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9996                            if (onSd) {
9997                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9998                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9999                            }
10000                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10001                        } else {
10002                            if (onSd) {
10003                                // Install flag overrides everything.
10004                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10005                            }
10006                            // If current upgrade specifies particular preference
10007                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10008                                // Application explicitly specified internal.
10009                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10010                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10011                                // App explictly prefers external. Let policy decide
10012                            } else {
10013                                // Prefer previous location
10014                                if (isExternal(pkg)) {
10015                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10016                                }
10017                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10018                            }
10019                        }
10020                    } else {
10021                        // Invalid install. Return error code
10022                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10023                    }
10024                }
10025            }
10026            // All the special cases have been taken care of.
10027            // Return result based on recommended install location.
10028            if (onSd) {
10029                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10030            }
10031            return pkgLite.recommendedInstallLocation;
10032        }
10033
10034        /*
10035         * Invoke remote method to get package information and install
10036         * location values. Override install location based on default
10037         * policy if needed and then create install arguments based
10038         * on the install location.
10039         */
10040        public void handleStartCopy() throws RemoteException {
10041            int ret = PackageManager.INSTALL_SUCCEEDED;
10042
10043            // If we're already staged, we've firmly committed to an install location
10044            if (origin.staged) {
10045                if (origin.file != null) {
10046                    installFlags |= PackageManager.INSTALL_INTERNAL;
10047                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10048                } else if (origin.cid != null) {
10049                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10050                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10051                } else {
10052                    throw new IllegalStateException("Invalid stage location");
10053                }
10054            }
10055
10056            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10057            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10058
10059            PackageInfoLite pkgLite = null;
10060
10061            if (onInt && onSd) {
10062                // Check if both bits are set.
10063                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10064                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10065            } else {
10066                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10067                        packageAbiOverride);
10068
10069                /*
10070                 * If we have too little free space, try to free cache
10071                 * before giving up.
10072                 */
10073                if (!origin.staged && pkgLite.recommendedInstallLocation
10074                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10075                    // TODO: focus freeing disk space on the target device
10076                    final StorageManager storage = StorageManager.from(mContext);
10077                    final long lowThreshold = storage.getStorageLowBytes(
10078                            Environment.getDataDirectory());
10079
10080                    final long sizeBytes = mContainerService.calculateInstalledSize(
10081                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10082
10083                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10084                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10085                                installFlags, packageAbiOverride);
10086                    }
10087
10088                    /*
10089                     * The cache free must have deleted the file we
10090                     * downloaded to install.
10091                     *
10092                     * TODO: fix the "freeCache" call to not delete
10093                     *       the file we care about.
10094                     */
10095                    if (pkgLite.recommendedInstallLocation
10096                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10097                        pkgLite.recommendedInstallLocation
10098                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10099                    }
10100                }
10101            }
10102
10103            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10104                int loc = pkgLite.recommendedInstallLocation;
10105                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10106                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10107                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10108                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10109                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10110                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10111                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10112                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10113                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10114                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10115                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10116                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10117                } else {
10118                    // Override with defaults if needed.
10119                    loc = installLocationPolicy(pkgLite);
10120                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10121                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10122                    } else if (!onSd && !onInt) {
10123                        // Override install location with flags
10124                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10125                            // Set the flag to install on external media.
10126                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10127                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10128                        } else {
10129                            // Make sure the flag for installing on external
10130                            // media is unset
10131                            installFlags |= PackageManager.INSTALL_INTERNAL;
10132                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10133                        }
10134                    }
10135                }
10136            }
10137
10138            final InstallArgs args = createInstallArgs(this);
10139            mArgs = args;
10140
10141            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10142                 /*
10143                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10144                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10145                 */
10146                int userIdentifier = getUser().getIdentifier();
10147                if (userIdentifier == UserHandle.USER_ALL
10148                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10149                    userIdentifier = UserHandle.USER_OWNER;
10150                }
10151
10152                /*
10153                 * Determine if we have any installed package verifiers. If we
10154                 * do, then we'll defer to them to verify the packages.
10155                 */
10156                final int requiredUid = mRequiredVerifierPackage == null ? -1
10157                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10158                if (!origin.existing && requiredUid != -1
10159                        && isVerificationEnabled(userIdentifier, installFlags)) {
10160                    final Intent verification = new Intent(
10161                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10162                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10163                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10164                            PACKAGE_MIME_TYPE);
10165                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10166
10167                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10168                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10169                            0 /* TODO: Which userId? */);
10170
10171                    if (DEBUG_VERIFY) {
10172                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10173                                + verification.toString() + " with " + pkgLite.verifiers.length
10174                                + " optional verifiers");
10175                    }
10176
10177                    final int verificationId = mPendingVerificationToken++;
10178
10179                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10180
10181                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10182                            installerPackageName);
10183
10184                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10185                            installFlags);
10186
10187                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10188                            pkgLite.packageName);
10189
10190                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10191                            pkgLite.versionCode);
10192
10193                    if (verificationParams != null) {
10194                        if (verificationParams.getVerificationURI() != null) {
10195                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10196                                 verificationParams.getVerificationURI());
10197                        }
10198                        if (verificationParams.getOriginatingURI() != null) {
10199                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10200                                  verificationParams.getOriginatingURI());
10201                        }
10202                        if (verificationParams.getReferrer() != null) {
10203                            verification.putExtra(Intent.EXTRA_REFERRER,
10204                                  verificationParams.getReferrer());
10205                        }
10206                        if (verificationParams.getOriginatingUid() >= 0) {
10207                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10208                                  verificationParams.getOriginatingUid());
10209                        }
10210                        if (verificationParams.getInstallerUid() >= 0) {
10211                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10212                                  verificationParams.getInstallerUid());
10213                        }
10214                    }
10215
10216                    final PackageVerificationState verificationState = new PackageVerificationState(
10217                            requiredUid, args);
10218
10219                    mPendingVerification.append(verificationId, verificationState);
10220
10221                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10222                            receivers, verificationState);
10223
10224                    /*
10225                     * If any sufficient verifiers were listed in the package
10226                     * manifest, attempt to ask them.
10227                     */
10228                    if (sufficientVerifiers != null) {
10229                        final int N = sufficientVerifiers.size();
10230                        if (N == 0) {
10231                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10232                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10233                        } else {
10234                            for (int i = 0; i < N; i++) {
10235                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10236
10237                                final Intent sufficientIntent = new Intent(verification);
10238                                sufficientIntent.setComponent(verifierComponent);
10239
10240                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10241                            }
10242                        }
10243                    }
10244
10245                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10246                            mRequiredVerifierPackage, receivers);
10247                    if (ret == PackageManager.INSTALL_SUCCEEDED
10248                            && mRequiredVerifierPackage != null) {
10249                        /*
10250                         * Send the intent to the required verification agent,
10251                         * but only start the verification timeout after the
10252                         * target BroadcastReceivers have run.
10253                         */
10254                        verification.setComponent(requiredVerifierComponent);
10255                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10256                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10257                                new BroadcastReceiver() {
10258                                    @Override
10259                                    public void onReceive(Context context, Intent intent) {
10260                                        final Message msg = mHandler
10261                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10262                                        msg.arg1 = verificationId;
10263                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10264                                    }
10265                                }, null, 0, null, null);
10266
10267                        /*
10268                         * We don't want the copy to proceed until verification
10269                         * succeeds, so null out this field.
10270                         */
10271                        mArgs = null;
10272                    }
10273                } else {
10274                    /*
10275                     * No package verification is enabled, so immediately start
10276                     * the remote call to initiate copy using temporary file.
10277                     */
10278                    ret = args.copyApk(mContainerService, true);
10279                }
10280            }
10281
10282            mRet = ret;
10283        }
10284
10285        @Override
10286        void handleReturnCode() {
10287            // If mArgs is null, then MCS couldn't be reached. When it
10288            // reconnects, it will try again to install. At that point, this
10289            // will succeed.
10290            if (mArgs != null) {
10291                processPendingInstall(mArgs, mRet);
10292            }
10293        }
10294
10295        @Override
10296        void handleServiceError() {
10297            mArgs = createInstallArgs(this);
10298            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10299        }
10300
10301        public boolean isForwardLocked() {
10302            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10303        }
10304    }
10305
10306    /**
10307     * Used during creation of InstallArgs
10308     *
10309     * @param installFlags package installation flags
10310     * @return true if should be installed on external storage
10311     */
10312    private static boolean installOnExternalAsec(int installFlags) {
10313        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10314            return false;
10315        }
10316        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10317            return true;
10318        }
10319        return false;
10320    }
10321
10322    /**
10323     * Used during creation of InstallArgs
10324     *
10325     * @param installFlags package installation flags
10326     * @return true if should be installed as forward locked
10327     */
10328    private static boolean installForwardLocked(int installFlags) {
10329        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10330    }
10331
10332    private InstallArgs createInstallArgs(InstallParams params) {
10333        if (params.move != null) {
10334            return new MoveInstallArgs(params);
10335        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10336            return new AsecInstallArgs(params);
10337        } else {
10338            return new FileInstallArgs(params);
10339        }
10340    }
10341
10342    /**
10343     * Create args that describe an existing installed package. Typically used
10344     * when cleaning up old installs, or used as a move source.
10345     */
10346    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10347            String resourcePath, String[] instructionSets) {
10348        final boolean isInAsec;
10349        if (installOnExternalAsec(installFlags)) {
10350            /* Apps on SD card are always in ASEC containers. */
10351            isInAsec = true;
10352        } else if (installForwardLocked(installFlags)
10353                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10354            /*
10355             * Forward-locked apps are only in ASEC containers if they're the
10356             * new style
10357             */
10358            isInAsec = true;
10359        } else {
10360            isInAsec = false;
10361        }
10362
10363        if (isInAsec) {
10364            return new AsecInstallArgs(codePath, instructionSets,
10365                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10366        } else {
10367            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10368        }
10369    }
10370
10371    static abstract class InstallArgs {
10372        /** @see InstallParams#origin */
10373        final OriginInfo origin;
10374        /** @see InstallParams#move */
10375        final MoveInfo move;
10376
10377        final IPackageInstallObserver2 observer;
10378        // Always refers to PackageManager flags only
10379        final int installFlags;
10380        final String installerPackageName;
10381        final String volumeUuid;
10382        final ManifestDigest manifestDigest;
10383        final UserHandle user;
10384        final String abiOverride;
10385
10386        // The list of instruction sets supported by this app. This is currently
10387        // only used during the rmdex() phase to clean up resources. We can get rid of this
10388        // if we move dex files under the common app path.
10389        /* nullable */ String[] instructionSets;
10390
10391        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10392                int installFlags, String installerPackageName, String volumeUuid,
10393                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10394                String abiOverride) {
10395            this.origin = origin;
10396            this.move = move;
10397            this.installFlags = installFlags;
10398            this.observer = observer;
10399            this.installerPackageName = installerPackageName;
10400            this.volumeUuid = volumeUuid;
10401            this.manifestDigest = manifestDigest;
10402            this.user = user;
10403            this.instructionSets = instructionSets;
10404            this.abiOverride = abiOverride;
10405        }
10406
10407        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10408        abstract int doPreInstall(int status);
10409
10410        /**
10411         * Rename package into final resting place. All paths on the given
10412         * scanned package should be updated to reflect the rename.
10413         */
10414        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10415        abstract int doPostInstall(int status, int uid);
10416
10417        /** @see PackageSettingBase#codePathString */
10418        abstract String getCodePath();
10419        /** @see PackageSettingBase#resourcePathString */
10420        abstract String getResourcePath();
10421
10422        // Need installer lock especially for dex file removal.
10423        abstract void cleanUpResourcesLI();
10424        abstract boolean doPostDeleteLI(boolean delete);
10425
10426        /**
10427         * Called before the source arguments are copied. This is used mostly
10428         * for MoveParams when it needs to read the source file to put it in the
10429         * destination.
10430         */
10431        int doPreCopy() {
10432            return PackageManager.INSTALL_SUCCEEDED;
10433        }
10434
10435        /**
10436         * Called after the source arguments are copied. This is used mostly for
10437         * MoveParams when it needs to read the source file to put it in the
10438         * destination.
10439         *
10440         * @return
10441         */
10442        int doPostCopy(int uid) {
10443            return PackageManager.INSTALL_SUCCEEDED;
10444        }
10445
10446        protected boolean isFwdLocked() {
10447            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10448        }
10449
10450        protected boolean isExternalAsec() {
10451            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10452        }
10453
10454        UserHandle getUser() {
10455            return user;
10456        }
10457    }
10458
10459    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10460        if (!allCodePaths.isEmpty()) {
10461            if (instructionSets == null) {
10462                throw new IllegalStateException("instructionSet == null");
10463            }
10464            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10465            for (String codePath : allCodePaths) {
10466                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10467                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10468                    if (retCode < 0) {
10469                        Slog.w(TAG, "Couldn't remove dex file for package: "
10470                                + " at location " + codePath + ", retcode=" + retCode);
10471                        // we don't consider this to be a failure of the core package deletion
10472                    }
10473                }
10474            }
10475        }
10476    }
10477
10478    /**
10479     * Logic to handle installation of non-ASEC applications, including copying
10480     * and renaming logic.
10481     */
10482    class FileInstallArgs extends InstallArgs {
10483        private File codeFile;
10484        private File resourceFile;
10485
10486        // Example topology:
10487        // /data/app/com.example/base.apk
10488        // /data/app/com.example/split_foo.apk
10489        // /data/app/com.example/lib/arm/libfoo.so
10490        // /data/app/com.example/lib/arm64/libfoo.so
10491        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10492
10493        /** New install */
10494        FileInstallArgs(InstallParams params) {
10495            super(params.origin, params.move, params.observer, params.installFlags,
10496                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10497                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10498            if (isFwdLocked()) {
10499                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10500            }
10501        }
10502
10503        /** Existing install */
10504        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10505            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10506                    null);
10507            this.codeFile = (codePath != null) ? new File(codePath) : null;
10508            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10509        }
10510
10511        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10512            if (origin.staged) {
10513                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10514                codeFile = origin.file;
10515                resourceFile = origin.file;
10516                return PackageManager.INSTALL_SUCCEEDED;
10517            }
10518
10519            try {
10520                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10521                codeFile = tempDir;
10522                resourceFile = tempDir;
10523            } catch (IOException e) {
10524                Slog.w(TAG, "Failed to create copy file: " + e);
10525                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10526            }
10527
10528            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10529                @Override
10530                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10531                    if (!FileUtils.isValidExtFilename(name)) {
10532                        throw new IllegalArgumentException("Invalid filename: " + name);
10533                    }
10534                    try {
10535                        final File file = new File(codeFile, name);
10536                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10537                                O_RDWR | O_CREAT, 0644);
10538                        Os.chmod(file.getAbsolutePath(), 0644);
10539                        return new ParcelFileDescriptor(fd);
10540                    } catch (ErrnoException e) {
10541                        throw new RemoteException("Failed to open: " + e.getMessage());
10542                    }
10543                }
10544            };
10545
10546            int ret = PackageManager.INSTALL_SUCCEEDED;
10547            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10548            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10549                Slog.e(TAG, "Failed to copy package");
10550                return ret;
10551            }
10552
10553            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10554            NativeLibraryHelper.Handle handle = null;
10555            try {
10556                handle = NativeLibraryHelper.Handle.create(codeFile);
10557                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10558                        abiOverride);
10559            } catch (IOException e) {
10560                Slog.e(TAG, "Copying native libraries failed", e);
10561                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10562            } finally {
10563                IoUtils.closeQuietly(handle);
10564            }
10565
10566            return ret;
10567        }
10568
10569        int doPreInstall(int status) {
10570            if (status != PackageManager.INSTALL_SUCCEEDED) {
10571                cleanUp();
10572            }
10573            return status;
10574        }
10575
10576        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10577            if (status != PackageManager.INSTALL_SUCCEEDED) {
10578                cleanUp();
10579                return false;
10580            }
10581
10582            final File targetDir = codeFile.getParentFile();
10583            final File beforeCodeFile = codeFile;
10584            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10585
10586            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10587            try {
10588                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10589            } catch (ErrnoException e) {
10590                Slog.w(TAG, "Failed to rename", e);
10591                return false;
10592            }
10593
10594            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10595                Slog.w(TAG, "Failed to restorecon");
10596                return false;
10597            }
10598
10599            // Reflect the rename internally
10600            codeFile = afterCodeFile;
10601            resourceFile = afterCodeFile;
10602
10603            // Reflect the rename in scanned details
10604            pkg.codePath = afterCodeFile.getAbsolutePath();
10605            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10606                    pkg.baseCodePath);
10607            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10608                    pkg.splitCodePaths);
10609
10610            // Reflect the rename in app info
10611            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10612            pkg.applicationInfo.setCodePath(pkg.codePath);
10613            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10614            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10615            pkg.applicationInfo.setResourcePath(pkg.codePath);
10616            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10617            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10618
10619            return true;
10620        }
10621
10622        int doPostInstall(int status, int uid) {
10623            if (status != PackageManager.INSTALL_SUCCEEDED) {
10624                cleanUp();
10625            }
10626            return status;
10627        }
10628
10629        @Override
10630        String getCodePath() {
10631            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10632        }
10633
10634        @Override
10635        String getResourcePath() {
10636            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10637        }
10638
10639        private boolean cleanUp() {
10640            if (codeFile == null || !codeFile.exists()) {
10641                return false;
10642            }
10643
10644            if (codeFile.isDirectory()) {
10645                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10646            } else {
10647                codeFile.delete();
10648            }
10649
10650            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10651                resourceFile.delete();
10652            }
10653
10654            return true;
10655        }
10656
10657        void cleanUpResourcesLI() {
10658            // Try enumerating all code paths before deleting
10659            List<String> allCodePaths = Collections.EMPTY_LIST;
10660            if (codeFile != null && codeFile.exists()) {
10661                try {
10662                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10663                    allCodePaths = pkg.getAllCodePaths();
10664                } catch (PackageParserException e) {
10665                    // Ignored; we tried our best
10666                }
10667            }
10668
10669            cleanUp();
10670            removeDexFiles(allCodePaths, instructionSets);
10671        }
10672
10673        boolean doPostDeleteLI(boolean delete) {
10674            // XXX err, shouldn't we respect the delete flag?
10675            cleanUpResourcesLI();
10676            return true;
10677        }
10678    }
10679
10680    private boolean isAsecExternal(String cid) {
10681        final String asecPath = PackageHelper.getSdFilesystem(cid);
10682        return !asecPath.startsWith(mAsecInternalPath);
10683    }
10684
10685    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10686            PackageManagerException {
10687        if (copyRet < 0) {
10688            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10689                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10690                throw new PackageManagerException(copyRet, message);
10691            }
10692        }
10693    }
10694
10695    /**
10696     * Extract the MountService "container ID" from the full code path of an
10697     * .apk.
10698     */
10699    static String cidFromCodePath(String fullCodePath) {
10700        int eidx = fullCodePath.lastIndexOf("/");
10701        String subStr1 = fullCodePath.substring(0, eidx);
10702        int sidx = subStr1.lastIndexOf("/");
10703        return subStr1.substring(sidx+1, eidx);
10704    }
10705
10706    /**
10707     * Logic to handle installation of ASEC applications, including copying and
10708     * renaming logic.
10709     */
10710    class AsecInstallArgs extends InstallArgs {
10711        static final String RES_FILE_NAME = "pkg.apk";
10712        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10713
10714        String cid;
10715        String packagePath;
10716        String resourcePath;
10717
10718        /** New install */
10719        AsecInstallArgs(InstallParams params) {
10720            super(params.origin, params.move, params.observer, params.installFlags,
10721                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10722                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10723        }
10724
10725        /** Existing install */
10726        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10727                        boolean isExternal, boolean isForwardLocked) {
10728            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10729                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10730                    instructionSets, null);
10731            // Hackily pretend we're still looking at a full code path
10732            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10733                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10734            }
10735
10736            // Extract cid from fullCodePath
10737            int eidx = fullCodePath.lastIndexOf("/");
10738            String subStr1 = fullCodePath.substring(0, eidx);
10739            int sidx = subStr1.lastIndexOf("/");
10740            cid = subStr1.substring(sidx+1, eidx);
10741            setMountPath(subStr1);
10742        }
10743
10744        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10745            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10746                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10747                    instructionSets, null);
10748            this.cid = cid;
10749            setMountPath(PackageHelper.getSdDir(cid));
10750        }
10751
10752        void createCopyFile() {
10753            cid = mInstallerService.allocateExternalStageCidLegacy();
10754        }
10755
10756        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10757            if (origin.staged) {
10758                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10759                cid = origin.cid;
10760                setMountPath(PackageHelper.getSdDir(cid));
10761                return PackageManager.INSTALL_SUCCEEDED;
10762            }
10763
10764            if (temp) {
10765                createCopyFile();
10766            } else {
10767                /*
10768                 * Pre-emptively destroy the container since it's destroyed if
10769                 * copying fails due to it existing anyway.
10770                 */
10771                PackageHelper.destroySdDir(cid);
10772            }
10773
10774            final String newMountPath = imcs.copyPackageToContainer(
10775                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10776                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10777
10778            if (newMountPath != null) {
10779                setMountPath(newMountPath);
10780                return PackageManager.INSTALL_SUCCEEDED;
10781            } else {
10782                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10783            }
10784        }
10785
10786        @Override
10787        String getCodePath() {
10788            return packagePath;
10789        }
10790
10791        @Override
10792        String getResourcePath() {
10793            return resourcePath;
10794        }
10795
10796        int doPreInstall(int status) {
10797            if (status != PackageManager.INSTALL_SUCCEEDED) {
10798                // Destroy container
10799                PackageHelper.destroySdDir(cid);
10800            } else {
10801                boolean mounted = PackageHelper.isContainerMounted(cid);
10802                if (!mounted) {
10803                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10804                            Process.SYSTEM_UID);
10805                    if (newMountPath != null) {
10806                        setMountPath(newMountPath);
10807                    } else {
10808                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10809                    }
10810                }
10811            }
10812            return status;
10813        }
10814
10815        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10816            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10817            String newMountPath = null;
10818            if (PackageHelper.isContainerMounted(cid)) {
10819                // Unmount the container
10820                if (!PackageHelper.unMountSdDir(cid)) {
10821                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10822                    return false;
10823                }
10824            }
10825            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10826                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10827                        " which might be stale. Will try to clean up.");
10828                // Clean up the stale container and proceed to recreate.
10829                if (!PackageHelper.destroySdDir(newCacheId)) {
10830                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10831                    return false;
10832                }
10833                // Successfully cleaned up stale container. Try to rename again.
10834                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10835                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10836                            + " inspite of cleaning it up.");
10837                    return false;
10838                }
10839            }
10840            if (!PackageHelper.isContainerMounted(newCacheId)) {
10841                Slog.w(TAG, "Mounting container " + newCacheId);
10842                newMountPath = PackageHelper.mountSdDir(newCacheId,
10843                        getEncryptKey(), Process.SYSTEM_UID);
10844            } else {
10845                newMountPath = PackageHelper.getSdDir(newCacheId);
10846            }
10847            if (newMountPath == null) {
10848                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10849                return false;
10850            }
10851            Log.i(TAG, "Succesfully renamed " + cid +
10852                    " to " + newCacheId +
10853                    " at new path: " + newMountPath);
10854            cid = newCacheId;
10855
10856            final File beforeCodeFile = new File(packagePath);
10857            setMountPath(newMountPath);
10858            final File afterCodeFile = new File(packagePath);
10859
10860            // Reflect the rename in scanned details
10861            pkg.codePath = afterCodeFile.getAbsolutePath();
10862            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10863                    pkg.baseCodePath);
10864            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10865                    pkg.splitCodePaths);
10866
10867            // Reflect the rename in app info
10868            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10869            pkg.applicationInfo.setCodePath(pkg.codePath);
10870            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10871            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10872            pkg.applicationInfo.setResourcePath(pkg.codePath);
10873            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10874            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10875
10876            return true;
10877        }
10878
10879        private void setMountPath(String mountPath) {
10880            final File mountFile = new File(mountPath);
10881
10882            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10883            if (monolithicFile.exists()) {
10884                packagePath = monolithicFile.getAbsolutePath();
10885                if (isFwdLocked()) {
10886                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10887                } else {
10888                    resourcePath = packagePath;
10889                }
10890            } else {
10891                packagePath = mountFile.getAbsolutePath();
10892                resourcePath = packagePath;
10893            }
10894        }
10895
10896        int doPostInstall(int status, int uid) {
10897            if (status != PackageManager.INSTALL_SUCCEEDED) {
10898                cleanUp();
10899            } else {
10900                final int groupOwner;
10901                final String protectedFile;
10902                if (isFwdLocked()) {
10903                    groupOwner = UserHandle.getSharedAppGid(uid);
10904                    protectedFile = RES_FILE_NAME;
10905                } else {
10906                    groupOwner = -1;
10907                    protectedFile = null;
10908                }
10909
10910                if (uid < Process.FIRST_APPLICATION_UID
10911                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10912                    Slog.e(TAG, "Failed to finalize " + cid);
10913                    PackageHelper.destroySdDir(cid);
10914                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10915                }
10916
10917                boolean mounted = PackageHelper.isContainerMounted(cid);
10918                if (!mounted) {
10919                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10920                }
10921            }
10922            return status;
10923        }
10924
10925        private void cleanUp() {
10926            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10927
10928            // Destroy secure container
10929            PackageHelper.destroySdDir(cid);
10930        }
10931
10932        private List<String> getAllCodePaths() {
10933            final File codeFile = new File(getCodePath());
10934            if (codeFile != null && codeFile.exists()) {
10935                try {
10936                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10937                    return pkg.getAllCodePaths();
10938                } catch (PackageParserException e) {
10939                    // Ignored; we tried our best
10940                }
10941            }
10942            return Collections.EMPTY_LIST;
10943        }
10944
10945        void cleanUpResourcesLI() {
10946            // Enumerate all code paths before deleting
10947            cleanUpResourcesLI(getAllCodePaths());
10948        }
10949
10950        private void cleanUpResourcesLI(List<String> allCodePaths) {
10951            cleanUp();
10952            removeDexFiles(allCodePaths, instructionSets);
10953        }
10954
10955        String getPackageName() {
10956            return getAsecPackageName(cid);
10957        }
10958
10959        boolean doPostDeleteLI(boolean delete) {
10960            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10961            final List<String> allCodePaths = getAllCodePaths();
10962            boolean mounted = PackageHelper.isContainerMounted(cid);
10963            if (mounted) {
10964                // Unmount first
10965                if (PackageHelper.unMountSdDir(cid)) {
10966                    mounted = false;
10967                }
10968            }
10969            if (!mounted && delete) {
10970                cleanUpResourcesLI(allCodePaths);
10971            }
10972            return !mounted;
10973        }
10974
10975        @Override
10976        int doPreCopy() {
10977            if (isFwdLocked()) {
10978                if (!PackageHelper.fixSdPermissions(cid,
10979                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10980                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10981                }
10982            }
10983
10984            return PackageManager.INSTALL_SUCCEEDED;
10985        }
10986
10987        @Override
10988        int doPostCopy(int uid) {
10989            if (isFwdLocked()) {
10990                if (uid < Process.FIRST_APPLICATION_UID
10991                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10992                                RES_FILE_NAME)) {
10993                    Slog.e(TAG, "Failed to finalize " + cid);
10994                    PackageHelper.destroySdDir(cid);
10995                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10996                }
10997            }
10998
10999            return PackageManager.INSTALL_SUCCEEDED;
11000        }
11001    }
11002
11003    /**
11004     * Logic to handle movement of existing installed applications.
11005     */
11006    class MoveInstallArgs extends InstallArgs {
11007        private File codeFile;
11008        private File resourceFile;
11009
11010        /** New install */
11011        MoveInstallArgs(InstallParams params) {
11012            super(params.origin, params.move, params.observer, params.installFlags,
11013                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11014                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11015        }
11016
11017        int copyApk(IMediaContainerService imcs, boolean temp) {
11018            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11019                    + move.fromUuid + " to " + move.toUuid);
11020            synchronized (mInstaller) {
11021                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11022                        move.dataAppName, move.appId, move.seinfo) != 0) {
11023                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11024                }
11025            }
11026
11027            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11028            resourceFile = codeFile;
11029            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11030
11031            return PackageManager.INSTALL_SUCCEEDED;
11032        }
11033
11034        int doPreInstall(int status) {
11035            if (status != PackageManager.INSTALL_SUCCEEDED) {
11036                cleanUp();
11037            }
11038            return status;
11039        }
11040
11041        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11042            if (status != PackageManager.INSTALL_SUCCEEDED) {
11043                cleanUp();
11044                return false;
11045            }
11046
11047            // Reflect the move in app info
11048            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11049            pkg.applicationInfo.setCodePath(pkg.codePath);
11050            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11051            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11052            pkg.applicationInfo.setResourcePath(pkg.codePath);
11053            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11054            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11055
11056            return true;
11057        }
11058
11059        int doPostInstall(int status, int uid) {
11060            if (status != PackageManager.INSTALL_SUCCEEDED) {
11061                cleanUp();
11062            }
11063            return status;
11064        }
11065
11066        @Override
11067        String getCodePath() {
11068            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11069        }
11070
11071        @Override
11072        String getResourcePath() {
11073            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11074        }
11075
11076        private boolean cleanUp() {
11077            if (codeFile == null || !codeFile.exists()) {
11078                return false;
11079            }
11080
11081            if (codeFile.isDirectory()) {
11082                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11083            } else {
11084                codeFile.delete();
11085            }
11086
11087            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11088                resourceFile.delete();
11089            }
11090
11091            return true;
11092        }
11093
11094        void cleanUpResourcesLI() {
11095            cleanUp();
11096        }
11097
11098        boolean doPostDeleteLI(boolean delete) {
11099            // XXX err, shouldn't we respect the delete flag?
11100            cleanUpResourcesLI();
11101            return true;
11102        }
11103    }
11104
11105    static String getAsecPackageName(String packageCid) {
11106        int idx = packageCid.lastIndexOf("-");
11107        if (idx == -1) {
11108            return packageCid;
11109        }
11110        return packageCid.substring(0, idx);
11111    }
11112
11113    // Utility method used to create code paths based on package name and available index.
11114    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11115        String idxStr = "";
11116        int idx = 1;
11117        // Fall back to default value of idx=1 if prefix is not
11118        // part of oldCodePath
11119        if (oldCodePath != null) {
11120            String subStr = oldCodePath;
11121            // Drop the suffix right away
11122            if (suffix != null && subStr.endsWith(suffix)) {
11123                subStr = subStr.substring(0, subStr.length() - suffix.length());
11124            }
11125            // If oldCodePath already contains prefix find out the
11126            // ending index to either increment or decrement.
11127            int sidx = subStr.lastIndexOf(prefix);
11128            if (sidx != -1) {
11129                subStr = subStr.substring(sidx + prefix.length());
11130                if (subStr != null) {
11131                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11132                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11133                    }
11134                    try {
11135                        idx = Integer.parseInt(subStr);
11136                        if (idx <= 1) {
11137                            idx++;
11138                        } else {
11139                            idx--;
11140                        }
11141                    } catch(NumberFormatException e) {
11142                    }
11143                }
11144            }
11145        }
11146        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11147        return prefix + idxStr;
11148    }
11149
11150    private File getNextCodePath(File targetDir, String packageName) {
11151        int suffix = 1;
11152        File result;
11153        do {
11154            result = new File(targetDir, packageName + "-" + suffix);
11155            suffix++;
11156        } while (result.exists());
11157        return result;
11158    }
11159
11160    // Utility method that returns the relative package path with respect
11161    // to the installation directory. Like say for /data/data/com.test-1.apk
11162    // string com.test-1 is returned.
11163    static String deriveCodePathName(String codePath) {
11164        if (codePath == null) {
11165            return null;
11166        }
11167        final File codeFile = new File(codePath);
11168        final String name = codeFile.getName();
11169        if (codeFile.isDirectory()) {
11170            return name;
11171        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11172            final int lastDot = name.lastIndexOf('.');
11173            return name.substring(0, lastDot);
11174        } else {
11175            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11176            return null;
11177        }
11178    }
11179
11180    class PackageInstalledInfo {
11181        String name;
11182        int uid;
11183        // The set of users that originally had this package installed.
11184        int[] origUsers;
11185        // The set of users that now have this package installed.
11186        int[] newUsers;
11187        PackageParser.Package pkg;
11188        int returnCode;
11189        String returnMsg;
11190        PackageRemovedInfo removedInfo;
11191
11192        public void setError(int code, String msg) {
11193            returnCode = code;
11194            returnMsg = msg;
11195            Slog.w(TAG, msg);
11196        }
11197
11198        public void setError(String msg, PackageParserException e) {
11199            returnCode = e.error;
11200            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11201            Slog.w(TAG, msg, e);
11202        }
11203
11204        public void setError(String msg, PackageManagerException e) {
11205            returnCode = e.error;
11206            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11207            Slog.w(TAG, msg, e);
11208        }
11209
11210        // In some error cases we want to convey more info back to the observer
11211        String origPackage;
11212        String origPermission;
11213    }
11214
11215    /*
11216     * Install a non-existing package.
11217     */
11218    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11219            UserHandle user, String installerPackageName, String volumeUuid,
11220            PackageInstalledInfo res) {
11221        // Remember this for later, in case we need to rollback this install
11222        String pkgName = pkg.packageName;
11223
11224        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11225        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11226                UserHandle.USER_OWNER).exists();
11227        synchronized(mPackages) {
11228            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11229                // A package with the same name is already installed, though
11230                // it has been renamed to an older name.  The package we
11231                // are trying to install should be installed as an update to
11232                // the existing one, but that has not been requested, so bail.
11233                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11234                        + " without first uninstalling package running as "
11235                        + mSettings.mRenamedPackages.get(pkgName));
11236                return;
11237            }
11238            if (mPackages.containsKey(pkgName)) {
11239                // Don't allow installation over an existing package with the same name.
11240                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11241                        + " without first uninstalling.");
11242                return;
11243            }
11244        }
11245
11246        try {
11247            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11248                    System.currentTimeMillis(), user);
11249
11250            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11251            // delete the partially installed application. the data directory will have to be
11252            // restored if it was already existing
11253            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11254                // remove package from internal structures.  Note that we want deletePackageX to
11255                // delete the package data and cache directories that it created in
11256                // scanPackageLocked, unless those directories existed before we even tried to
11257                // install.
11258                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11259                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11260                                res.removedInfo, true);
11261            }
11262
11263        } catch (PackageManagerException e) {
11264            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11265        }
11266    }
11267
11268    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11269        // Can't rotate keys during boot or if sharedUser.
11270        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11271                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11272            return false;
11273        }
11274        // app is using upgradeKeySets; make sure all are valid
11275        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11276        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11277        for (int i = 0; i < upgradeKeySets.length; i++) {
11278            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11279                Slog.wtf(TAG, "Package "
11280                         + (oldPs.name != null ? oldPs.name : "<null>")
11281                         + " contains upgrade-key-set reference to unknown key-set: "
11282                         + upgradeKeySets[i]
11283                         + " reverting to signatures check.");
11284                return false;
11285            }
11286        }
11287        return true;
11288    }
11289
11290    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11291        // Upgrade keysets are being used.  Determine if new package has a superset of the
11292        // required keys.
11293        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11294        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11295        for (int i = 0; i < upgradeKeySets.length; i++) {
11296            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11297            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11298                return true;
11299            }
11300        }
11301        return false;
11302    }
11303
11304    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11305            UserHandle user, String installerPackageName, String volumeUuid,
11306            PackageInstalledInfo res) {
11307        final PackageParser.Package oldPackage;
11308        final String pkgName = pkg.packageName;
11309        final int[] allUsers;
11310        final boolean[] perUserInstalled;
11311        final boolean weFroze;
11312
11313        // First find the old package info and check signatures
11314        synchronized(mPackages) {
11315            oldPackage = mPackages.get(pkgName);
11316            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11317            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11318            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11319                if(!checkUpgradeKeySetLP(ps, pkg)) {
11320                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11321                            "New package not signed by keys specified by upgrade-keysets: "
11322                            + pkgName);
11323                    return;
11324                }
11325            } else {
11326                // default to original signature matching
11327                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11328                    != PackageManager.SIGNATURE_MATCH) {
11329                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11330                            "New package has a different signature: " + pkgName);
11331                    return;
11332                }
11333            }
11334
11335            // In case of rollback, remember per-user/profile install state
11336            allUsers = sUserManager.getUserIds();
11337            perUserInstalled = new boolean[allUsers.length];
11338            for (int i = 0; i < allUsers.length; i++) {
11339                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11340            }
11341
11342            // Mark the app as frozen to prevent launching during the upgrade
11343            // process, and then kill all running instances
11344            if (!ps.frozen) {
11345                ps.frozen = true;
11346                weFroze = true;
11347            } else {
11348                weFroze = false;
11349            }
11350        }
11351
11352        // Now that we're guarded by frozen state, kill app during upgrade
11353        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11354
11355        try {
11356            boolean sysPkg = (isSystemApp(oldPackage));
11357            if (sysPkg) {
11358                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11359                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11360            } else {
11361                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11362                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11363            }
11364        } finally {
11365            // Regardless of success or failure of upgrade steps above, always
11366            // unfreeze the package if we froze it
11367            if (weFroze) {
11368                unfreezePackage(pkgName);
11369            }
11370        }
11371    }
11372
11373    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11374            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11375            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11376            String volumeUuid, PackageInstalledInfo res) {
11377        String pkgName = deletedPackage.packageName;
11378        boolean deletedPkg = true;
11379        boolean updatedSettings = false;
11380
11381        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11382                + deletedPackage);
11383        long origUpdateTime;
11384        if (pkg.mExtras != null) {
11385            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11386        } else {
11387            origUpdateTime = 0;
11388        }
11389
11390        // First delete the existing package while retaining the data directory
11391        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11392                res.removedInfo, true)) {
11393            // If the existing package wasn't successfully deleted
11394            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11395            deletedPkg = false;
11396        } else {
11397            // Successfully deleted the old package; proceed with replace.
11398
11399            // If deleted package lived in a container, give users a chance to
11400            // relinquish resources before killing.
11401            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11402                if (DEBUG_INSTALL) {
11403                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11404                }
11405                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11406                final ArrayList<String> pkgList = new ArrayList<String>(1);
11407                pkgList.add(deletedPackage.applicationInfo.packageName);
11408                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11409            }
11410
11411            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11412            try {
11413                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11414                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11415                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11416                        perUserInstalled, res, user);
11417                updatedSettings = true;
11418            } catch (PackageManagerException e) {
11419                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11420            }
11421        }
11422
11423        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11424            // remove package from internal structures.  Note that we want deletePackageX to
11425            // delete the package data and cache directories that it created in
11426            // scanPackageLocked, unless those directories existed before we even tried to
11427            // install.
11428            if(updatedSettings) {
11429                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11430                deletePackageLI(
11431                        pkgName, null, true, allUsers, perUserInstalled,
11432                        PackageManager.DELETE_KEEP_DATA,
11433                                res.removedInfo, true);
11434            }
11435            // Since we failed to install the new package we need to restore the old
11436            // package that we deleted.
11437            if (deletedPkg) {
11438                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11439                File restoreFile = new File(deletedPackage.codePath);
11440                // Parse old package
11441                boolean oldExternal = isExternal(deletedPackage);
11442                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11443                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11444                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11445                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11446                try {
11447                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11448                } catch (PackageManagerException e) {
11449                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11450                            + e.getMessage());
11451                    return;
11452                }
11453                // Restore of old package succeeded. Update permissions.
11454                // writer
11455                synchronized (mPackages) {
11456                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11457                            UPDATE_PERMISSIONS_ALL);
11458                    // can downgrade to reader
11459                    mSettings.writeLPr();
11460                }
11461                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11462            }
11463        }
11464    }
11465
11466    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11467            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11468            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11469            String volumeUuid, PackageInstalledInfo res) {
11470        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11471                + ", old=" + deletedPackage);
11472        boolean disabledSystem = false;
11473        boolean updatedSettings = false;
11474        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11475        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11476                != 0) {
11477            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11478        }
11479        String packageName = deletedPackage.packageName;
11480        if (packageName == null) {
11481            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11482                    "Attempt to delete null packageName.");
11483            return;
11484        }
11485        PackageParser.Package oldPkg;
11486        PackageSetting oldPkgSetting;
11487        // reader
11488        synchronized (mPackages) {
11489            oldPkg = mPackages.get(packageName);
11490            oldPkgSetting = mSettings.mPackages.get(packageName);
11491            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11492                    (oldPkgSetting == null)) {
11493                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11494                        "Couldn't find package:" + packageName + " information");
11495                return;
11496            }
11497        }
11498
11499        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11500        res.removedInfo.removedPackage = packageName;
11501        // Remove existing system package
11502        removePackageLI(oldPkgSetting, true);
11503        // writer
11504        synchronized (mPackages) {
11505            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11506            if (!disabledSystem && deletedPackage != null) {
11507                // We didn't need to disable the .apk as a current system package,
11508                // which means we are replacing another update that is already
11509                // installed.  We need to make sure to delete the older one's .apk.
11510                res.removedInfo.args = createInstallArgsForExisting(0,
11511                        deletedPackage.applicationInfo.getCodePath(),
11512                        deletedPackage.applicationInfo.getResourcePath(),
11513                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11514            } else {
11515                res.removedInfo.args = null;
11516            }
11517        }
11518
11519        // Successfully disabled the old package. Now proceed with re-installation
11520        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11521
11522        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11523        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11524
11525        PackageParser.Package newPackage = null;
11526        try {
11527            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11528            if (newPackage.mExtras != null) {
11529                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11530                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11531                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11532
11533                // is the update attempting to change shared user? that isn't going to work...
11534                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11535                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11536                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11537                            + " to " + newPkgSetting.sharedUser);
11538                    updatedSettings = true;
11539                }
11540            }
11541
11542            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11543                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11544                        perUserInstalled, res, user);
11545                updatedSettings = true;
11546            }
11547
11548        } catch (PackageManagerException e) {
11549            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11550        }
11551
11552        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11553            // Re installation failed. Restore old information
11554            // Remove new pkg information
11555            if (newPackage != null) {
11556                removeInstalledPackageLI(newPackage, true);
11557            }
11558            // Add back the old system package
11559            try {
11560                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11561            } catch (PackageManagerException e) {
11562                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11563            }
11564            // Restore the old system information in Settings
11565            synchronized (mPackages) {
11566                if (disabledSystem) {
11567                    mSettings.enableSystemPackageLPw(packageName);
11568                }
11569                if (updatedSettings) {
11570                    mSettings.setInstallerPackageName(packageName,
11571                            oldPkgSetting.installerPackageName);
11572                }
11573                mSettings.writeLPr();
11574            }
11575        }
11576    }
11577
11578    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11579            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11580            UserHandle user) {
11581        String pkgName = newPackage.packageName;
11582        synchronized (mPackages) {
11583            //write settings. the installStatus will be incomplete at this stage.
11584            //note that the new package setting would have already been
11585            //added to mPackages. It hasn't been persisted yet.
11586            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11587            mSettings.writeLPr();
11588        }
11589
11590        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11591
11592        synchronized (mPackages) {
11593            updatePermissionsLPw(newPackage.packageName, newPackage,
11594                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11595                            ? UPDATE_PERMISSIONS_ALL : 0));
11596            // For system-bundled packages, we assume that installing an upgraded version
11597            // of the package implies that the user actually wants to run that new code,
11598            // so we enable the package.
11599            PackageSetting ps = mSettings.mPackages.get(pkgName);
11600            if (ps != null) {
11601                if (isSystemApp(newPackage)) {
11602                    // NB: implicit assumption that system package upgrades apply to all users
11603                    if (DEBUG_INSTALL) {
11604                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11605                    }
11606                    if (res.origUsers != null) {
11607                        for (int userHandle : res.origUsers) {
11608                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11609                                    userHandle, installerPackageName);
11610                        }
11611                    }
11612                    // Also convey the prior install/uninstall state
11613                    if (allUsers != null && perUserInstalled != null) {
11614                        for (int i = 0; i < allUsers.length; i++) {
11615                            if (DEBUG_INSTALL) {
11616                                Slog.d(TAG, "    user " + allUsers[i]
11617                                        + " => " + perUserInstalled[i]);
11618                            }
11619                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11620                        }
11621                        // these install state changes will be persisted in the
11622                        // upcoming call to mSettings.writeLPr().
11623                    }
11624                }
11625                // It's implied that when a user requests installation, they want the app to be
11626                // installed and enabled.
11627                int userId = user.getIdentifier();
11628                if (userId != UserHandle.USER_ALL) {
11629                    ps.setInstalled(true, userId);
11630                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11631                }
11632            }
11633            res.name = pkgName;
11634            res.uid = newPackage.applicationInfo.uid;
11635            res.pkg = newPackage;
11636            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11637            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11638            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11639            //to update install status
11640            mSettings.writeLPr();
11641        }
11642    }
11643
11644    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11645        final int installFlags = args.installFlags;
11646        final String installerPackageName = args.installerPackageName;
11647        final String volumeUuid = args.volumeUuid;
11648        final File tmpPackageFile = new File(args.getCodePath());
11649        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11650        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11651                || (args.volumeUuid != null));
11652        boolean replace = false;
11653        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11654        // Result object to be returned
11655        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11656
11657        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11658        // Retrieve PackageSettings and parse package
11659        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11660                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11661                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11662        PackageParser pp = new PackageParser();
11663        pp.setSeparateProcesses(mSeparateProcesses);
11664        pp.setDisplayMetrics(mMetrics);
11665
11666        final PackageParser.Package pkg;
11667        try {
11668            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11669        } catch (PackageParserException e) {
11670            res.setError("Failed parse during installPackageLI", e);
11671            return;
11672        }
11673
11674        // Mark that we have an install time CPU ABI override.
11675        pkg.cpuAbiOverride = args.abiOverride;
11676
11677        String pkgName = res.name = pkg.packageName;
11678        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11679            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11680                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11681                return;
11682            }
11683        }
11684
11685        try {
11686            pp.collectCertificates(pkg, parseFlags);
11687            pp.collectManifestDigest(pkg);
11688        } catch (PackageParserException e) {
11689            res.setError("Failed collect during installPackageLI", e);
11690            return;
11691        }
11692
11693        /* If the installer passed in a manifest digest, compare it now. */
11694        if (args.manifestDigest != null) {
11695            if (DEBUG_INSTALL) {
11696                final String parsedManifest = pkg.manifestDigest == null ? "null"
11697                        : pkg.manifestDigest.toString();
11698                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11699                        + parsedManifest);
11700            }
11701
11702            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11703                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11704                return;
11705            }
11706        } else if (DEBUG_INSTALL) {
11707            final String parsedManifest = pkg.manifestDigest == null
11708                    ? "null" : pkg.manifestDigest.toString();
11709            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11710        }
11711
11712        // Get rid of all references to package scan path via parser.
11713        pp = null;
11714        String oldCodePath = null;
11715        boolean systemApp = false;
11716        synchronized (mPackages) {
11717            // Check if installing already existing package
11718            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11719                String oldName = mSettings.mRenamedPackages.get(pkgName);
11720                if (pkg.mOriginalPackages != null
11721                        && pkg.mOriginalPackages.contains(oldName)
11722                        && mPackages.containsKey(oldName)) {
11723                    // This package is derived from an original package,
11724                    // and this device has been updating from that original
11725                    // name.  We must continue using the original name, so
11726                    // rename the new package here.
11727                    pkg.setPackageName(oldName);
11728                    pkgName = pkg.packageName;
11729                    replace = true;
11730                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11731                            + oldName + " pkgName=" + pkgName);
11732                } else if (mPackages.containsKey(pkgName)) {
11733                    // This package, under its official name, already exists
11734                    // on the device; we should replace it.
11735                    replace = true;
11736                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11737                }
11738
11739                // Prevent apps opting out from runtime permissions
11740                if (replace) {
11741                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11742                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11743                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11744                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11745                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11746                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11747                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11748                                        + " doesn't support runtime permissions but the old"
11749                                        + " target SDK " + oldTargetSdk + " does.");
11750                        return;
11751                    }
11752                }
11753            }
11754
11755            PackageSetting ps = mSettings.mPackages.get(pkgName);
11756            if (ps != null) {
11757                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11758
11759                // Quick sanity check that we're signed correctly if updating;
11760                // we'll check this again later when scanning, but we want to
11761                // bail early here before tripping over redefined permissions.
11762                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11763                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11764                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11765                                + pkg.packageName + " upgrade keys do not match the "
11766                                + "previously installed version");
11767                        return;
11768                    }
11769                } else {
11770                    try {
11771                        verifySignaturesLP(ps, pkg);
11772                    } catch (PackageManagerException e) {
11773                        res.setError(e.error, e.getMessage());
11774                        return;
11775                    }
11776                }
11777
11778                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11779                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11780                    systemApp = (ps.pkg.applicationInfo.flags &
11781                            ApplicationInfo.FLAG_SYSTEM) != 0;
11782                }
11783                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11784            }
11785
11786            // Check whether the newly-scanned package wants to define an already-defined perm
11787            int N = pkg.permissions.size();
11788            for (int i = N-1; i >= 0; i--) {
11789                PackageParser.Permission perm = pkg.permissions.get(i);
11790                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11791                if (bp != null) {
11792                    // If the defining package is signed with our cert, it's okay.  This
11793                    // also includes the "updating the same package" case, of course.
11794                    // "updating same package" could also involve key-rotation.
11795                    final boolean sigsOk;
11796                    if (bp.sourcePackage.equals(pkg.packageName)
11797                            && (bp.packageSetting instanceof PackageSetting)
11798                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11799                                    scanFlags))) {
11800                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11801                    } else {
11802                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11803                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11804                    }
11805                    if (!sigsOk) {
11806                        // If the owning package is the system itself, we log but allow
11807                        // install to proceed; we fail the install on all other permission
11808                        // redefinitions.
11809                        if (!bp.sourcePackage.equals("android")) {
11810                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11811                                    + pkg.packageName + " attempting to redeclare permission "
11812                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11813                            res.origPermission = perm.info.name;
11814                            res.origPackage = bp.sourcePackage;
11815                            return;
11816                        } else {
11817                            Slog.w(TAG, "Package " + pkg.packageName
11818                                    + " attempting to redeclare system permission "
11819                                    + perm.info.name + "; ignoring new declaration");
11820                            pkg.permissions.remove(i);
11821                        }
11822                    }
11823                }
11824            }
11825
11826        }
11827
11828        if (systemApp && onExternal) {
11829            // Disable updates to system apps on sdcard
11830            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11831                    "Cannot install updates to system apps on sdcard");
11832            return;
11833        }
11834
11835        if (args.move != null) {
11836            // We did an in-place move, so dex is ready to roll
11837            scanFlags |= SCAN_NO_DEX;
11838            scanFlags |= SCAN_MOVE;
11839        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11840            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11841            scanFlags |= SCAN_NO_DEX;
11842
11843            try {
11844                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11845                        true /* extract libs */);
11846            } catch (PackageManagerException pme) {
11847                Slog.e(TAG, "Error deriving application ABI", pme);
11848                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11849                return;
11850            }
11851
11852            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11853            int result = mPackageDexOptimizer
11854                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11855                            false /* defer */, false /* inclDependencies */);
11856            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11857                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11858                return;
11859            }
11860        }
11861
11862        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11863            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11864            return;
11865        }
11866
11867        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11868
11869        if (replace) {
11870            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11871                    installerPackageName, volumeUuid, res);
11872        } else {
11873            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11874                    args.user, installerPackageName, volumeUuid, res);
11875        }
11876        synchronized (mPackages) {
11877            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11878            if (ps != null) {
11879                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11880            }
11881        }
11882    }
11883
11884    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11885        if (mIntentFilterVerifierComponent == null) {
11886            Slog.w(TAG, "No IntentFilter verification will not be done as "
11887                    + "there is no IntentFilterVerifier available!");
11888            return;
11889        }
11890
11891        final int verifierUid = getPackageUid(
11892                mIntentFilterVerifierComponent.getPackageName(),
11893                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11894
11895        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11896        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11897        msg.obj = pkg;
11898        msg.arg1 = userId;
11899        msg.arg2 = verifierUid;
11900
11901        mHandler.sendMessage(msg);
11902    }
11903
11904    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11905            PackageParser.Package pkg) {
11906        int size = pkg.activities.size();
11907        if (size == 0) {
11908            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11909                    "No activity, so no need to verify any IntentFilter!");
11910            return;
11911        }
11912
11913        final boolean hasDomainURLs = hasDomainURLs(pkg);
11914        if (!hasDomainURLs) {
11915            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11916                    "No domain URLs, so no need to verify any IntentFilter!");
11917            return;
11918        }
11919
11920        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11921                + " if any IntentFilter from the " + size
11922                + " Activities needs verification ...");
11923
11924        final int verificationId = mIntentFilterVerificationToken++;
11925        int count = 0;
11926        final String packageName = pkg.packageName;
11927        boolean needToVerify = false;
11928
11929        synchronized (mPackages) {
11930            // If any filters need to be verified, then all need to be.
11931            for (PackageParser.Activity a : pkg.activities) {
11932                for (ActivityIntentInfo filter : a.intents) {
11933                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
11934                        if (DEBUG_DOMAIN_VERIFICATION) {
11935                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
11936                        }
11937                        needToVerify = true;
11938                        break;
11939                    }
11940                }
11941            }
11942            if (needToVerify) {
11943                for (PackageParser.Activity a : pkg.activities) {
11944                    for (ActivityIntentInfo filter : a.intents) {
11945                        boolean needsFilterVerification = filter.hasWebDataURI();
11946                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11947                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11948                                    "Verification needed for IntentFilter:" + filter.toString());
11949                            mIntentFilterVerifier.addOneIntentFilterVerification(
11950                                    verifierUid, userId, verificationId, filter, packageName);
11951                            count++;
11952                        }
11953                    }
11954                }
11955            }
11956        }
11957
11958        if (count > 0) {
11959            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
11960                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11961                    +  " for userId:" + userId);
11962            mIntentFilterVerifier.startVerifications(userId);
11963        } else {
11964            if (DEBUG_DOMAIN_VERIFICATION) {
11965                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
11966            }
11967        }
11968    }
11969
11970    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11971        final ComponentName cn  = filter.activity.getComponentName();
11972        final String packageName = cn.getPackageName();
11973
11974        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11975                packageName);
11976        if (ivi == null) {
11977            return true;
11978        }
11979        int status = ivi.getStatus();
11980        switch (status) {
11981            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11982            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11983                return true;
11984
11985            default:
11986                // Nothing to do
11987                return false;
11988        }
11989    }
11990
11991    private static boolean isMultiArch(PackageSetting ps) {
11992        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11993    }
11994
11995    private static boolean isMultiArch(ApplicationInfo info) {
11996        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11997    }
11998
11999    private static boolean isExternal(PackageParser.Package pkg) {
12000        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12001    }
12002
12003    private static boolean isExternal(PackageSetting ps) {
12004        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12005    }
12006
12007    private static boolean isExternal(ApplicationInfo info) {
12008        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12009    }
12010
12011    private static boolean isSystemApp(PackageParser.Package pkg) {
12012        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12013    }
12014
12015    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12016        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12017    }
12018
12019    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12020        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12021    }
12022
12023    private static boolean isSystemApp(PackageSetting ps) {
12024        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12025    }
12026
12027    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12028        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12029    }
12030
12031    private int packageFlagsToInstallFlags(PackageSetting ps) {
12032        int installFlags = 0;
12033        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12034            // This existing package was an external ASEC install when we have
12035            // the external flag without a UUID
12036            installFlags |= PackageManager.INSTALL_EXTERNAL;
12037        }
12038        if (ps.isForwardLocked()) {
12039            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12040        }
12041        return installFlags;
12042    }
12043
12044    private void deleteTempPackageFiles() {
12045        final FilenameFilter filter = new FilenameFilter() {
12046            public boolean accept(File dir, String name) {
12047                return name.startsWith("vmdl") && name.endsWith(".tmp");
12048            }
12049        };
12050        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12051            file.delete();
12052        }
12053    }
12054
12055    @Override
12056    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12057            int flags) {
12058        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12059                flags);
12060    }
12061
12062    @Override
12063    public void deletePackage(final String packageName,
12064            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12065        mContext.enforceCallingOrSelfPermission(
12066                android.Manifest.permission.DELETE_PACKAGES, null);
12067        final int uid = Binder.getCallingUid();
12068        if (UserHandle.getUserId(uid) != userId) {
12069            mContext.enforceCallingPermission(
12070                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12071                    "deletePackage for user " + userId);
12072        }
12073        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12074            try {
12075                observer.onPackageDeleted(packageName,
12076                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12077            } catch (RemoteException re) {
12078            }
12079            return;
12080        }
12081
12082        boolean uninstallBlocked = false;
12083        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12084            int[] users = sUserManager.getUserIds();
12085            for (int i = 0; i < users.length; ++i) {
12086                if (getBlockUninstallForUser(packageName, users[i])) {
12087                    uninstallBlocked = true;
12088                    break;
12089                }
12090            }
12091        } else {
12092            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12093        }
12094        if (uninstallBlocked) {
12095            try {
12096                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12097                        null);
12098            } catch (RemoteException re) {
12099            }
12100            return;
12101        }
12102
12103        if (DEBUG_REMOVE) {
12104            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12105        }
12106        // Queue up an async operation since the package deletion may take a little while.
12107        mHandler.post(new Runnable() {
12108            public void run() {
12109                mHandler.removeCallbacks(this);
12110                final int returnCode = deletePackageX(packageName, userId, flags);
12111                if (observer != null) {
12112                    try {
12113                        observer.onPackageDeleted(packageName, returnCode, null);
12114                    } catch (RemoteException e) {
12115                        Log.i(TAG, "Observer no longer exists.");
12116                    } //end catch
12117                } //end if
12118            } //end run
12119        });
12120    }
12121
12122    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12123        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12124                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12125        try {
12126            if (dpm != null) {
12127                if (dpm.isDeviceOwner(packageName)) {
12128                    return true;
12129                }
12130                int[] users;
12131                if (userId == UserHandle.USER_ALL) {
12132                    users = sUserManager.getUserIds();
12133                } else {
12134                    users = new int[]{userId};
12135                }
12136                for (int i = 0; i < users.length; ++i) {
12137                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12138                        return true;
12139                    }
12140                }
12141            }
12142        } catch (RemoteException e) {
12143        }
12144        return false;
12145    }
12146
12147    /**
12148     *  This method is an internal method that could be get invoked either
12149     *  to delete an installed package or to clean up a failed installation.
12150     *  After deleting an installed package, a broadcast is sent to notify any
12151     *  listeners that the package has been installed. For cleaning up a failed
12152     *  installation, the broadcast is not necessary since the package's
12153     *  installation wouldn't have sent the initial broadcast either
12154     *  The key steps in deleting a package are
12155     *  deleting the package information in internal structures like mPackages,
12156     *  deleting the packages base directories through installd
12157     *  updating mSettings to reflect current status
12158     *  persisting settings for later use
12159     *  sending a broadcast if necessary
12160     */
12161    private int deletePackageX(String packageName, int userId, int flags) {
12162        final PackageRemovedInfo info = new PackageRemovedInfo();
12163        final boolean res;
12164
12165        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12166                ? UserHandle.ALL : new UserHandle(userId);
12167
12168        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12169            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12170            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12171        }
12172
12173        boolean removedForAllUsers = false;
12174        boolean systemUpdate = false;
12175
12176        // for the uninstall-updates case and restricted profiles, remember the per-
12177        // userhandle installed state
12178        int[] allUsers;
12179        boolean[] perUserInstalled;
12180        synchronized (mPackages) {
12181            PackageSetting ps = mSettings.mPackages.get(packageName);
12182            allUsers = sUserManager.getUserIds();
12183            perUserInstalled = new boolean[allUsers.length];
12184            for (int i = 0; i < allUsers.length; i++) {
12185                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12186            }
12187        }
12188
12189        synchronized (mInstallLock) {
12190            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12191            res = deletePackageLI(packageName, removeForUser,
12192                    true, allUsers, perUserInstalled,
12193                    flags | REMOVE_CHATTY, info, true);
12194            systemUpdate = info.isRemovedPackageSystemUpdate;
12195            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12196                removedForAllUsers = true;
12197            }
12198            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12199                    + " removedForAllUsers=" + removedForAllUsers);
12200        }
12201
12202        if (res) {
12203            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12204
12205            // If the removed package was a system update, the old system package
12206            // was re-enabled; we need to broadcast this information
12207            if (systemUpdate) {
12208                Bundle extras = new Bundle(1);
12209                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12210                        ? info.removedAppId : info.uid);
12211                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12212
12213                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12214                        extras, null, null, null);
12215                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12216                        extras, null, null, null);
12217                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12218                        null, packageName, null, null);
12219            }
12220        }
12221        // Force a gc here.
12222        Runtime.getRuntime().gc();
12223        // Delete the resources here after sending the broadcast to let
12224        // other processes clean up before deleting resources.
12225        if (info.args != null) {
12226            synchronized (mInstallLock) {
12227                info.args.doPostDeleteLI(true);
12228            }
12229        }
12230
12231        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12232    }
12233
12234    class PackageRemovedInfo {
12235        String removedPackage;
12236        int uid = -1;
12237        int removedAppId = -1;
12238        int[] removedUsers = null;
12239        boolean isRemovedPackageSystemUpdate = false;
12240        // Clean up resources deleted packages.
12241        InstallArgs args = null;
12242
12243        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12244            Bundle extras = new Bundle(1);
12245            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12246            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12247            if (replacing) {
12248                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12249            }
12250            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12251            if (removedPackage != null) {
12252                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12253                        extras, null, null, removedUsers);
12254                if (fullRemove && !replacing) {
12255                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12256                            extras, null, null, removedUsers);
12257                }
12258            }
12259            if (removedAppId >= 0) {
12260                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12261                        removedUsers);
12262            }
12263        }
12264    }
12265
12266    /*
12267     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12268     * flag is not set, the data directory is removed as well.
12269     * make sure this flag is set for partially installed apps. If not its meaningless to
12270     * delete a partially installed application.
12271     */
12272    private void removePackageDataLI(PackageSetting ps,
12273            int[] allUserHandles, boolean[] perUserInstalled,
12274            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12275        String packageName = ps.name;
12276        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12277        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12278        // Retrieve object to delete permissions for shared user later on
12279        final PackageSetting deletedPs;
12280        // reader
12281        synchronized (mPackages) {
12282            deletedPs = mSettings.mPackages.get(packageName);
12283            if (outInfo != null) {
12284                outInfo.removedPackage = packageName;
12285                outInfo.removedUsers = deletedPs != null
12286                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12287                        : null;
12288            }
12289        }
12290        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12291            removeDataDirsLI(ps.volumeUuid, packageName);
12292            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12293        }
12294        // writer
12295        synchronized (mPackages) {
12296            if (deletedPs != null) {
12297                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12298                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12299                    clearDefaultBrowserIfNeeded(packageName);
12300                    if (outInfo != null) {
12301                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12302                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12303                    }
12304                    updatePermissionsLPw(deletedPs.name, null, 0);
12305                    if (deletedPs.sharedUser != null) {
12306                        // Remove permissions associated with package. Since runtime
12307                        // permissions are per user we have to kill the removed package
12308                        // or packages running under the shared user of the removed
12309                        // package if revoking the permissions requested only by the removed
12310                        // package is successful and this causes a change in gids.
12311                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12312                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12313                                    userId);
12314                            if (userIdToKill == UserHandle.USER_ALL
12315                                    || userIdToKill >= UserHandle.USER_OWNER) {
12316                                // If gids changed for this user, kill all affected packages.
12317                                mHandler.post(new Runnable() {
12318                                    @Override
12319                                    public void run() {
12320                                        // This has to happen with no lock held.
12321                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12322                                                KILL_APP_REASON_GIDS_CHANGED);
12323                                    }
12324                                });
12325                            break;
12326                            }
12327                        }
12328                    }
12329                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12330                }
12331                // make sure to preserve per-user disabled state if this removal was just
12332                // a downgrade of a system app to the factory package
12333                if (allUserHandles != null && perUserInstalled != null) {
12334                    if (DEBUG_REMOVE) {
12335                        Slog.d(TAG, "Propagating install state across downgrade");
12336                    }
12337                    for (int i = 0; i < allUserHandles.length; i++) {
12338                        if (DEBUG_REMOVE) {
12339                            Slog.d(TAG, "    user " + allUserHandles[i]
12340                                    + " => " + perUserInstalled[i]);
12341                        }
12342                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12343                    }
12344                }
12345            }
12346            // can downgrade to reader
12347            if (writeSettings) {
12348                // Save settings now
12349                mSettings.writeLPr();
12350            }
12351        }
12352        if (outInfo != null) {
12353            // A user ID was deleted here. Go through all users and remove it
12354            // from KeyStore.
12355            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12356        }
12357    }
12358
12359    static boolean locationIsPrivileged(File path) {
12360        try {
12361            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12362                    .getCanonicalPath();
12363            return path.getCanonicalPath().startsWith(privilegedAppDir);
12364        } catch (IOException e) {
12365            Slog.e(TAG, "Unable to access code path " + path);
12366        }
12367        return false;
12368    }
12369
12370    /*
12371     * Tries to delete system package.
12372     */
12373    private boolean deleteSystemPackageLI(PackageSetting newPs,
12374            int[] allUserHandles, boolean[] perUserInstalled,
12375            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12376        final boolean applyUserRestrictions
12377                = (allUserHandles != null) && (perUserInstalled != null);
12378        PackageSetting disabledPs = null;
12379        // Confirm if the system package has been updated
12380        // An updated system app can be deleted. This will also have to restore
12381        // the system pkg from system partition
12382        // reader
12383        synchronized (mPackages) {
12384            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12385        }
12386        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12387                + " disabledPs=" + disabledPs);
12388        if (disabledPs == null) {
12389            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12390            return false;
12391        } else if (DEBUG_REMOVE) {
12392            Slog.d(TAG, "Deleting system pkg from data partition");
12393        }
12394        if (DEBUG_REMOVE) {
12395            if (applyUserRestrictions) {
12396                Slog.d(TAG, "Remembering install states:");
12397                for (int i = 0; i < allUserHandles.length; i++) {
12398                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12399                }
12400            }
12401        }
12402        // Delete the updated package
12403        outInfo.isRemovedPackageSystemUpdate = true;
12404        if (disabledPs.versionCode < newPs.versionCode) {
12405            // Delete data for downgrades
12406            flags &= ~PackageManager.DELETE_KEEP_DATA;
12407        } else {
12408            // Preserve data by setting flag
12409            flags |= PackageManager.DELETE_KEEP_DATA;
12410        }
12411        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12412                allUserHandles, perUserInstalled, outInfo, writeSettings);
12413        if (!ret) {
12414            return false;
12415        }
12416        // writer
12417        synchronized (mPackages) {
12418            // Reinstate the old system package
12419            mSettings.enableSystemPackageLPw(newPs.name);
12420            // Remove any native libraries from the upgraded package.
12421            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12422        }
12423        // Install the system package
12424        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12425        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12426        if (locationIsPrivileged(disabledPs.codePath)) {
12427            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12428        }
12429
12430        final PackageParser.Package newPkg;
12431        try {
12432            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12433        } catch (PackageManagerException e) {
12434            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12435            return false;
12436        }
12437
12438        // writer
12439        synchronized (mPackages) {
12440            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12441            updatePermissionsLPw(newPkg.packageName, newPkg,
12442                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12443            if (applyUserRestrictions) {
12444                if (DEBUG_REMOVE) {
12445                    Slog.d(TAG, "Propagating install state across reinstall");
12446                }
12447                for (int i = 0; i < allUserHandles.length; i++) {
12448                    if (DEBUG_REMOVE) {
12449                        Slog.d(TAG, "    user " + allUserHandles[i]
12450                                + " => " + perUserInstalled[i]);
12451                    }
12452                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12453                }
12454                // Regardless of writeSettings we need to ensure that this restriction
12455                // state propagation is persisted
12456                mSettings.writeAllUsersPackageRestrictionsLPr();
12457            }
12458            // can downgrade to reader here
12459            if (writeSettings) {
12460                mSettings.writeLPr();
12461            }
12462        }
12463        return true;
12464    }
12465
12466    private boolean deleteInstalledPackageLI(PackageSetting ps,
12467            boolean deleteCodeAndResources, int flags,
12468            int[] allUserHandles, boolean[] perUserInstalled,
12469            PackageRemovedInfo outInfo, boolean writeSettings) {
12470        if (outInfo != null) {
12471            outInfo.uid = ps.appId;
12472        }
12473
12474        // Delete package data from internal structures and also remove data if flag is set
12475        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12476
12477        // Delete application code and resources
12478        if (deleteCodeAndResources && (outInfo != null)) {
12479            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12480                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12481            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12482        }
12483        return true;
12484    }
12485
12486    @Override
12487    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12488            int userId) {
12489        mContext.enforceCallingOrSelfPermission(
12490                android.Manifest.permission.DELETE_PACKAGES, null);
12491        synchronized (mPackages) {
12492            PackageSetting ps = mSettings.mPackages.get(packageName);
12493            if (ps == null) {
12494                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12495                return false;
12496            }
12497            if (!ps.getInstalled(userId)) {
12498                // Can't block uninstall for an app that is not installed or enabled.
12499                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12500                return false;
12501            }
12502            ps.setBlockUninstall(blockUninstall, userId);
12503            mSettings.writePackageRestrictionsLPr(userId);
12504        }
12505        return true;
12506    }
12507
12508    @Override
12509    public boolean getBlockUninstallForUser(String packageName, int userId) {
12510        synchronized (mPackages) {
12511            PackageSetting ps = mSettings.mPackages.get(packageName);
12512            if (ps == null) {
12513                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12514                return false;
12515            }
12516            return ps.getBlockUninstall(userId);
12517        }
12518    }
12519
12520    /*
12521     * This method handles package deletion in general
12522     */
12523    private boolean deletePackageLI(String packageName, UserHandle user,
12524            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12525            int flags, PackageRemovedInfo outInfo,
12526            boolean writeSettings) {
12527        if (packageName == null) {
12528            Slog.w(TAG, "Attempt to delete null packageName.");
12529            return false;
12530        }
12531        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12532        PackageSetting ps;
12533        boolean dataOnly = false;
12534        int removeUser = -1;
12535        int appId = -1;
12536        synchronized (mPackages) {
12537            ps = mSettings.mPackages.get(packageName);
12538            if (ps == null) {
12539                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12540                return false;
12541            }
12542            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12543                    && user.getIdentifier() != UserHandle.USER_ALL) {
12544                // The caller is asking that the package only be deleted for a single
12545                // user.  To do this, we just mark its uninstalled state and delete
12546                // its data.  If this is a system app, we only allow this to happen if
12547                // they have set the special DELETE_SYSTEM_APP which requests different
12548                // semantics than normal for uninstalling system apps.
12549                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12550                ps.setUserState(user.getIdentifier(),
12551                        COMPONENT_ENABLED_STATE_DEFAULT,
12552                        false, //installed
12553                        true,  //stopped
12554                        true,  //notLaunched
12555                        false, //hidden
12556                        null, null, null,
12557                        false, // blockUninstall
12558                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12559                if (!isSystemApp(ps)) {
12560                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12561                        // Other user still have this package installed, so all
12562                        // we need to do is clear this user's data and save that
12563                        // it is uninstalled.
12564                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12565                        removeUser = user.getIdentifier();
12566                        appId = ps.appId;
12567                        scheduleWritePackageRestrictionsLocked(removeUser);
12568                    } else {
12569                        // We need to set it back to 'installed' so the uninstall
12570                        // broadcasts will be sent correctly.
12571                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12572                        ps.setInstalled(true, user.getIdentifier());
12573                    }
12574                } else {
12575                    // This is a system app, so we assume that the
12576                    // other users still have this package installed, so all
12577                    // we need to do is clear this user's data and save that
12578                    // it is uninstalled.
12579                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12580                    removeUser = user.getIdentifier();
12581                    appId = ps.appId;
12582                    scheduleWritePackageRestrictionsLocked(removeUser);
12583                }
12584            }
12585        }
12586
12587        if (removeUser >= 0) {
12588            // From above, we determined that we are deleting this only
12589            // for a single user.  Continue the work here.
12590            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12591            if (outInfo != null) {
12592                outInfo.removedPackage = packageName;
12593                outInfo.removedAppId = appId;
12594                outInfo.removedUsers = new int[] {removeUser};
12595            }
12596            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12597            removeKeystoreDataIfNeeded(removeUser, appId);
12598            schedulePackageCleaning(packageName, removeUser, false);
12599            synchronized (mPackages) {
12600                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12601                    scheduleWritePackageRestrictionsLocked(removeUser);
12602                }
12603                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12604                        removeUser);
12605            }
12606            return true;
12607        }
12608
12609        if (dataOnly) {
12610            // Delete application data first
12611            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12612            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12613            return true;
12614        }
12615
12616        boolean ret = false;
12617        if (isSystemApp(ps)) {
12618            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12619            // When an updated system application is deleted we delete the existing resources as well and
12620            // fall back to existing code in system partition
12621            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12622                    flags, outInfo, writeSettings);
12623        } else {
12624            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12625            // Kill application pre-emptively especially for apps on sd.
12626            killApplication(packageName, ps.appId, "uninstall pkg");
12627            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12628                    allUserHandles, perUserInstalled,
12629                    outInfo, writeSettings);
12630        }
12631
12632        return ret;
12633    }
12634
12635    private final class ClearStorageConnection implements ServiceConnection {
12636        IMediaContainerService mContainerService;
12637
12638        @Override
12639        public void onServiceConnected(ComponentName name, IBinder service) {
12640            synchronized (this) {
12641                mContainerService = IMediaContainerService.Stub.asInterface(service);
12642                notifyAll();
12643            }
12644        }
12645
12646        @Override
12647        public void onServiceDisconnected(ComponentName name) {
12648        }
12649    }
12650
12651    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12652        final boolean mounted;
12653        if (Environment.isExternalStorageEmulated()) {
12654            mounted = true;
12655        } else {
12656            final String status = Environment.getExternalStorageState();
12657
12658            mounted = status.equals(Environment.MEDIA_MOUNTED)
12659                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12660        }
12661
12662        if (!mounted) {
12663            return;
12664        }
12665
12666        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12667        int[] users;
12668        if (userId == UserHandle.USER_ALL) {
12669            users = sUserManager.getUserIds();
12670        } else {
12671            users = new int[] { userId };
12672        }
12673        final ClearStorageConnection conn = new ClearStorageConnection();
12674        if (mContext.bindServiceAsUser(
12675                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12676            try {
12677                for (int curUser : users) {
12678                    long timeout = SystemClock.uptimeMillis() + 5000;
12679                    synchronized (conn) {
12680                        long now = SystemClock.uptimeMillis();
12681                        while (conn.mContainerService == null && now < timeout) {
12682                            try {
12683                                conn.wait(timeout - now);
12684                            } catch (InterruptedException e) {
12685                            }
12686                        }
12687                    }
12688                    if (conn.mContainerService == null) {
12689                        return;
12690                    }
12691
12692                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12693                    clearDirectory(conn.mContainerService,
12694                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12695                    if (allData) {
12696                        clearDirectory(conn.mContainerService,
12697                                userEnv.buildExternalStorageAppDataDirs(packageName));
12698                        clearDirectory(conn.mContainerService,
12699                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12700                    }
12701                }
12702            } finally {
12703                mContext.unbindService(conn);
12704            }
12705        }
12706    }
12707
12708    @Override
12709    public void clearApplicationUserData(final String packageName,
12710            final IPackageDataObserver observer, final int userId) {
12711        mContext.enforceCallingOrSelfPermission(
12712                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12713        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12714        // Queue up an async operation since the package deletion may take a little while.
12715        mHandler.post(new Runnable() {
12716            public void run() {
12717                mHandler.removeCallbacks(this);
12718                final boolean succeeded;
12719                synchronized (mInstallLock) {
12720                    succeeded = clearApplicationUserDataLI(packageName, userId);
12721                }
12722                clearExternalStorageDataSync(packageName, userId, true);
12723                if (succeeded) {
12724                    // invoke DeviceStorageMonitor's update method to clear any notifications
12725                    DeviceStorageMonitorInternal
12726                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12727                    if (dsm != null) {
12728                        dsm.checkMemory();
12729                    }
12730                }
12731                if(observer != null) {
12732                    try {
12733                        observer.onRemoveCompleted(packageName, succeeded);
12734                    } catch (RemoteException e) {
12735                        Log.i(TAG, "Observer no longer exists.");
12736                    }
12737                } //end if observer
12738            } //end run
12739        });
12740    }
12741
12742    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12743        if (packageName == null) {
12744            Slog.w(TAG, "Attempt to delete null packageName.");
12745            return false;
12746        }
12747
12748        // Try finding details about the requested package
12749        PackageParser.Package pkg;
12750        synchronized (mPackages) {
12751            pkg = mPackages.get(packageName);
12752            if (pkg == null) {
12753                final PackageSetting ps = mSettings.mPackages.get(packageName);
12754                if (ps != null) {
12755                    pkg = ps.pkg;
12756                }
12757            }
12758
12759            if (pkg == null) {
12760                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12761                return false;
12762            }
12763
12764            PackageSetting ps = (PackageSetting) pkg.mExtras;
12765            PermissionsState permissionsState = ps.getPermissionsState();
12766            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12767        }
12768
12769        // Always delete data directories for package, even if we found no other
12770        // record of app. This helps users recover from UID mismatches without
12771        // resorting to a full data wipe.
12772        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12773        if (retCode < 0) {
12774            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12775            return false;
12776        }
12777
12778        final int appId = pkg.applicationInfo.uid;
12779        removeKeystoreDataIfNeeded(userId, appId);
12780
12781        // Create a native library symlink only if we have native libraries
12782        // and if the native libraries are 32 bit libraries. We do not provide
12783        // this symlink for 64 bit libraries.
12784        if (pkg.applicationInfo.primaryCpuAbi != null &&
12785                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12786            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12787            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12788                    nativeLibPath, userId) < 0) {
12789                Slog.w(TAG, "Failed linking native library dir");
12790                return false;
12791            }
12792        }
12793
12794        return true;
12795    }
12796
12797
12798    /**
12799     * Revokes granted runtime permissions and clears resettable flags
12800     * which are flags that can be set by a user interaction.
12801     *
12802     * @param permissionsState The permission state to reset.
12803     * @param userId The device user for which to do a reset.
12804     */
12805    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12806            PermissionsState permissionsState, int userId) {
12807        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12808                | PackageManager.FLAG_PERMISSION_USER_FIXED
12809                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12810
12811        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
12812    }
12813
12814    /**
12815     * Revokes granted runtime permissions and clears all flags.
12816     *
12817     * @param permissionsState The permission state to reset.
12818     * @param userId The device user for which to do a reset.
12819     */
12820    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
12821            PermissionsState permissionsState, int userId) {
12822        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
12823                PackageManager.MASK_PERMISSION_FLAGS);
12824    }
12825
12826    /**
12827     * Revokes granted runtime permissions and clears certain flags.
12828     *
12829     * @param permissionsState The permission state to reset.
12830     * @param userId The device user for which to do a reset.
12831     * @param flags The flags that is going to be reset.
12832     */
12833    private void revokeRuntimePermissionsAndClearFlagsLocked(
12834            PermissionsState permissionsState, int userId, int flags) {
12835        boolean needsWrite = false;
12836
12837        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12838            BasePermission bp = mSettings.mPermissions.get(state.getName());
12839            if (bp != null) {
12840                permissionsState.revokeRuntimePermission(bp, userId);
12841                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
12842                needsWrite = true;
12843            }
12844        }
12845
12846        // Ensure default permissions are never cleared.
12847        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
12848
12849        if (needsWrite) {
12850            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12851        }
12852    }
12853
12854    /**
12855     * Remove entries from the keystore daemon. Will only remove it if the
12856     * {@code appId} is valid.
12857     */
12858    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12859        if (appId < 0) {
12860            return;
12861        }
12862
12863        final KeyStore keyStore = KeyStore.getInstance();
12864        if (keyStore != null) {
12865            if (userId == UserHandle.USER_ALL) {
12866                for (final int individual : sUserManager.getUserIds()) {
12867                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12868                }
12869            } else {
12870                keyStore.clearUid(UserHandle.getUid(userId, appId));
12871            }
12872        } else {
12873            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12874        }
12875    }
12876
12877    @Override
12878    public void deleteApplicationCacheFiles(final String packageName,
12879            final IPackageDataObserver observer) {
12880        mContext.enforceCallingOrSelfPermission(
12881                android.Manifest.permission.DELETE_CACHE_FILES, null);
12882        // Queue up an async operation since the package deletion may take a little while.
12883        final int userId = UserHandle.getCallingUserId();
12884        mHandler.post(new Runnable() {
12885            public void run() {
12886                mHandler.removeCallbacks(this);
12887                final boolean succeded;
12888                synchronized (mInstallLock) {
12889                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12890                }
12891                clearExternalStorageDataSync(packageName, userId, false);
12892                if (observer != null) {
12893                    try {
12894                        observer.onRemoveCompleted(packageName, succeded);
12895                    } catch (RemoteException e) {
12896                        Log.i(TAG, "Observer no longer exists.");
12897                    }
12898                } //end if observer
12899            } //end run
12900        });
12901    }
12902
12903    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12904        if (packageName == null) {
12905            Slog.w(TAG, "Attempt to delete null packageName.");
12906            return false;
12907        }
12908        PackageParser.Package p;
12909        synchronized (mPackages) {
12910            p = mPackages.get(packageName);
12911        }
12912        if (p == null) {
12913            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12914            return false;
12915        }
12916        final ApplicationInfo applicationInfo = p.applicationInfo;
12917        if (applicationInfo == null) {
12918            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12919            return false;
12920        }
12921        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12922        if (retCode < 0) {
12923            Slog.w(TAG, "Couldn't remove cache files for package: "
12924                       + packageName + " u" + userId);
12925            return false;
12926        }
12927        return true;
12928    }
12929
12930    @Override
12931    public void getPackageSizeInfo(final String packageName, int userHandle,
12932            final IPackageStatsObserver observer) {
12933        mContext.enforceCallingOrSelfPermission(
12934                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12935        if (packageName == null) {
12936            throw new IllegalArgumentException("Attempt to get size of null packageName");
12937        }
12938
12939        PackageStats stats = new PackageStats(packageName, userHandle);
12940
12941        /*
12942         * Queue up an async operation since the package measurement may take a
12943         * little while.
12944         */
12945        Message msg = mHandler.obtainMessage(INIT_COPY);
12946        msg.obj = new MeasureParams(stats, observer);
12947        mHandler.sendMessage(msg);
12948    }
12949
12950    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12951            PackageStats pStats) {
12952        if (packageName == null) {
12953            Slog.w(TAG, "Attempt to get size of null packageName.");
12954            return false;
12955        }
12956        PackageParser.Package p;
12957        boolean dataOnly = false;
12958        String libDirRoot = null;
12959        String asecPath = null;
12960        PackageSetting ps = null;
12961        synchronized (mPackages) {
12962            p = mPackages.get(packageName);
12963            ps = mSettings.mPackages.get(packageName);
12964            if(p == null) {
12965                dataOnly = true;
12966                if((ps == null) || (ps.pkg == null)) {
12967                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12968                    return false;
12969                }
12970                p = ps.pkg;
12971            }
12972            if (ps != null) {
12973                libDirRoot = ps.legacyNativeLibraryPathString;
12974            }
12975            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12976                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12977                if (secureContainerId != null) {
12978                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12979                }
12980            }
12981        }
12982        String publicSrcDir = null;
12983        if(!dataOnly) {
12984            final ApplicationInfo applicationInfo = p.applicationInfo;
12985            if (applicationInfo == null) {
12986                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12987                return false;
12988            }
12989            if (p.isForwardLocked()) {
12990                publicSrcDir = applicationInfo.getBaseResourcePath();
12991            }
12992        }
12993        // TODO: extend to measure size of split APKs
12994        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12995        // not just the first level.
12996        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12997        // just the primary.
12998        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12999        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13000                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13001        if (res < 0) {
13002            return false;
13003        }
13004
13005        // Fix-up for forward-locked applications in ASEC containers.
13006        if (!isExternal(p)) {
13007            pStats.codeSize += pStats.externalCodeSize;
13008            pStats.externalCodeSize = 0L;
13009        }
13010
13011        return true;
13012    }
13013
13014
13015    @Override
13016    public void addPackageToPreferred(String packageName) {
13017        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13018    }
13019
13020    @Override
13021    public void removePackageFromPreferred(String packageName) {
13022        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13023    }
13024
13025    @Override
13026    public List<PackageInfo> getPreferredPackages(int flags) {
13027        return new ArrayList<PackageInfo>();
13028    }
13029
13030    private int getUidTargetSdkVersionLockedLPr(int uid) {
13031        Object obj = mSettings.getUserIdLPr(uid);
13032        if (obj instanceof SharedUserSetting) {
13033            final SharedUserSetting sus = (SharedUserSetting) obj;
13034            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13035            final Iterator<PackageSetting> it = sus.packages.iterator();
13036            while (it.hasNext()) {
13037                final PackageSetting ps = it.next();
13038                if (ps.pkg != null) {
13039                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13040                    if (v < vers) vers = v;
13041                }
13042            }
13043            return vers;
13044        } else if (obj instanceof PackageSetting) {
13045            final PackageSetting ps = (PackageSetting) obj;
13046            if (ps.pkg != null) {
13047                return ps.pkg.applicationInfo.targetSdkVersion;
13048            }
13049        }
13050        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13051    }
13052
13053    @Override
13054    public void addPreferredActivity(IntentFilter filter, int match,
13055            ComponentName[] set, ComponentName activity, int userId) {
13056        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13057                "Adding preferred");
13058    }
13059
13060    private void addPreferredActivityInternal(IntentFilter filter, int match,
13061            ComponentName[] set, ComponentName activity, boolean always, int userId,
13062            String opname) {
13063        // writer
13064        int callingUid = Binder.getCallingUid();
13065        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13066        if (filter.countActions() == 0) {
13067            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13068            return;
13069        }
13070        synchronized (mPackages) {
13071            if (mContext.checkCallingOrSelfPermission(
13072                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13073                    != PackageManager.PERMISSION_GRANTED) {
13074                if (getUidTargetSdkVersionLockedLPr(callingUid)
13075                        < Build.VERSION_CODES.FROYO) {
13076                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13077                            + callingUid);
13078                    return;
13079                }
13080                mContext.enforceCallingOrSelfPermission(
13081                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13082            }
13083
13084            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13085            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13086                    + userId + ":");
13087            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13088            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13089            scheduleWritePackageRestrictionsLocked(userId);
13090        }
13091    }
13092
13093    @Override
13094    public void replacePreferredActivity(IntentFilter filter, int match,
13095            ComponentName[] set, ComponentName activity, int userId) {
13096        if (filter.countActions() != 1) {
13097            throw new IllegalArgumentException(
13098                    "replacePreferredActivity expects filter to have only 1 action.");
13099        }
13100        if (filter.countDataAuthorities() != 0
13101                || filter.countDataPaths() != 0
13102                || filter.countDataSchemes() > 1
13103                || filter.countDataTypes() != 0) {
13104            throw new IllegalArgumentException(
13105                    "replacePreferredActivity expects filter to have no data authorities, " +
13106                    "paths, or types; and at most one scheme.");
13107        }
13108
13109        final int callingUid = Binder.getCallingUid();
13110        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13111        synchronized (mPackages) {
13112            if (mContext.checkCallingOrSelfPermission(
13113                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13114                    != PackageManager.PERMISSION_GRANTED) {
13115                if (getUidTargetSdkVersionLockedLPr(callingUid)
13116                        < Build.VERSION_CODES.FROYO) {
13117                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13118                            + Binder.getCallingUid());
13119                    return;
13120                }
13121                mContext.enforceCallingOrSelfPermission(
13122                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13123            }
13124
13125            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13126            if (pir != null) {
13127                // Get all of the existing entries that exactly match this filter.
13128                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13129                if (existing != null && existing.size() == 1) {
13130                    PreferredActivity cur = existing.get(0);
13131                    if (DEBUG_PREFERRED) {
13132                        Slog.i(TAG, "Checking replace of preferred:");
13133                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13134                        if (!cur.mPref.mAlways) {
13135                            Slog.i(TAG, "  -- CUR; not mAlways!");
13136                        } else {
13137                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13138                            Slog.i(TAG, "  -- CUR: mSet="
13139                                    + Arrays.toString(cur.mPref.mSetComponents));
13140                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13141                            Slog.i(TAG, "  -- NEW: mMatch="
13142                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13143                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13144                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13145                        }
13146                    }
13147                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13148                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13149                            && cur.mPref.sameSet(set)) {
13150                        // Setting the preferred activity to what it happens to be already
13151                        if (DEBUG_PREFERRED) {
13152                            Slog.i(TAG, "Replacing with same preferred activity "
13153                                    + cur.mPref.mShortComponent + " for user "
13154                                    + userId + ":");
13155                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13156                        }
13157                        return;
13158                    }
13159                }
13160
13161                if (existing != null) {
13162                    if (DEBUG_PREFERRED) {
13163                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13164                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13165                    }
13166                    for (int i = 0; i < existing.size(); i++) {
13167                        PreferredActivity pa = existing.get(i);
13168                        if (DEBUG_PREFERRED) {
13169                            Slog.i(TAG, "Removing existing preferred activity "
13170                                    + pa.mPref.mComponent + ":");
13171                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13172                        }
13173                        pir.removeFilter(pa);
13174                    }
13175                }
13176            }
13177            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13178                    "Replacing preferred");
13179        }
13180    }
13181
13182    @Override
13183    public void clearPackagePreferredActivities(String packageName) {
13184        final int uid = Binder.getCallingUid();
13185        // writer
13186        synchronized (mPackages) {
13187            PackageParser.Package pkg = mPackages.get(packageName);
13188            if (pkg == null || pkg.applicationInfo.uid != uid) {
13189                if (mContext.checkCallingOrSelfPermission(
13190                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13191                        != PackageManager.PERMISSION_GRANTED) {
13192                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13193                            < Build.VERSION_CODES.FROYO) {
13194                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13195                                + Binder.getCallingUid());
13196                        return;
13197                    }
13198                    mContext.enforceCallingOrSelfPermission(
13199                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13200                }
13201            }
13202
13203            int user = UserHandle.getCallingUserId();
13204            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13205                scheduleWritePackageRestrictionsLocked(user);
13206            }
13207        }
13208    }
13209
13210    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13211    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13212        ArrayList<PreferredActivity> removed = null;
13213        boolean changed = false;
13214        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13215            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13216            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13217            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13218                continue;
13219            }
13220            Iterator<PreferredActivity> it = pir.filterIterator();
13221            while (it.hasNext()) {
13222                PreferredActivity pa = it.next();
13223                // Mark entry for removal only if it matches the package name
13224                // and the entry is of type "always".
13225                if (packageName == null ||
13226                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13227                                && pa.mPref.mAlways)) {
13228                    if (removed == null) {
13229                        removed = new ArrayList<PreferredActivity>();
13230                    }
13231                    removed.add(pa);
13232                }
13233            }
13234            if (removed != null) {
13235                for (int j=0; j<removed.size(); j++) {
13236                    PreferredActivity pa = removed.get(j);
13237                    pir.removeFilter(pa);
13238                }
13239                changed = true;
13240            }
13241        }
13242        return changed;
13243    }
13244
13245    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13246    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13247        if (userId == UserHandle.USER_ALL) {
13248            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13249                    sUserManager.getUserIds())) {
13250                for (int oneUserId : sUserManager.getUserIds()) {
13251                    scheduleWritePackageRestrictionsLocked(oneUserId);
13252                }
13253            }
13254        } else {
13255            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13256                scheduleWritePackageRestrictionsLocked(userId);
13257            }
13258        }
13259    }
13260
13261
13262    void clearDefaultBrowserIfNeeded(String packageName) {
13263        for (int oneUserId : sUserManager.getUserIds()) {
13264            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13265            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13266            if (packageName.equals(defaultBrowserPackageName)) {
13267                setDefaultBrowserPackageName(null, oneUserId);
13268            }
13269        }
13270    }
13271
13272    @Override
13273    public void resetPreferredActivities(int userId) {
13274        /* TODO: Actually use userId. Why is it being passed in? */
13275        mContext.enforceCallingOrSelfPermission(
13276                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13277        // writer
13278        synchronized (mPackages) {
13279            int user = UserHandle.getCallingUserId();
13280            clearPackagePreferredActivitiesLPw(null, user);
13281            mSettings.readDefaultPreferredAppsLPw(this, user);
13282            scheduleWritePackageRestrictionsLocked(user);
13283        }
13284    }
13285
13286    @Override
13287    public int getPreferredActivities(List<IntentFilter> outFilters,
13288            List<ComponentName> outActivities, String packageName) {
13289
13290        int num = 0;
13291        final int userId = UserHandle.getCallingUserId();
13292        // reader
13293        synchronized (mPackages) {
13294            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13295            if (pir != null) {
13296                final Iterator<PreferredActivity> it = pir.filterIterator();
13297                while (it.hasNext()) {
13298                    final PreferredActivity pa = it.next();
13299                    if (packageName == null
13300                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13301                                    && pa.mPref.mAlways)) {
13302                        if (outFilters != null) {
13303                            outFilters.add(new IntentFilter(pa));
13304                        }
13305                        if (outActivities != null) {
13306                            outActivities.add(pa.mPref.mComponent);
13307                        }
13308                    }
13309                }
13310            }
13311        }
13312
13313        return num;
13314    }
13315
13316    @Override
13317    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13318            int userId) {
13319        int callingUid = Binder.getCallingUid();
13320        if (callingUid != Process.SYSTEM_UID) {
13321            throw new SecurityException(
13322                    "addPersistentPreferredActivity can only be run by the system");
13323        }
13324        if (filter.countActions() == 0) {
13325            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13326            return;
13327        }
13328        synchronized (mPackages) {
13329            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13330                    " :");
13331            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13332            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13333                    new PersistentPreferredActivity(filter, activity));
13334            scheduleWritePackageRestrictionsLocked(userId);
13335        }
13336    }
13337
13338    @Override
13339    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13340        int callingUid = Binder.getCallingUid();
13341        if (callingUid != Process.SYSTEM_UID) {
13342            throw new SecurityException(
13343                    "clearPackagePersistentPreferredActivities can only be run by the system");
13344        }
13345        ArrayList<PersistentPreferredActivity> removed = null;
13346        boolean changed = false;
13347        synchronized (mPackages) {
13348            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13349                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13350                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13351                        .valueAt(i);
13352                if (userId != thisUserId) {
13353                    continue;
13354                }
13355                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13356                while (it.hasNext()) {
13357                    PersistentPreferredActivity ppa = it.next();
13358                    // Mark entry for removal only if it matches the package name.
13359                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13360                        if (removed == null) {
13361                            removed = new ArrayList<PersistentPreferredActivity>();
13362                        }
13363                        removed.add(ppa);
13364                    }
13365                }
13366                if (removed != null) {
13367                    for (int j=0; j<removed.size(); j++) {
13368                        PersistentPreferredActivity ppa = removed.get(j);
13369                        ppir.removeFilter(ppa);
13370                    }
13371                    changed = true;
13372                }
13373            }
13374
13375            if (changed) {
13376                scheduleWritePackageRestrictionsLocked(userId);
13377            }
13378        }
13379    }
13380
13381    /**
13382     * Non-Binder method, support for the backup/restore mechanism: write the
13383     * full set of preferred activities in its canonical XML format.  Returns true
13384     * on success; false otherwise.
13385     */
13386    @Override
13387    public byte[] getPreferredActivityBackup(int userId) {
13388        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13389            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13390        }
13391
13392        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13393        try {
13394            final XmlSerializer serializer = new FastXmlSerializer();
13395            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13396            serializer.startDocument(null, true);
13397            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13398
13399            synchronized (mPackages) {
13400                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13401            }
13402
13403            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13404            serializer.endDocument();
13405            serializer.flush();
13406        } catch (Exception e) {
13407            if (DEBUG_BACKUP) {
13408                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13409            }
13410            return null;
13411        }
13412
13413        return dataStream.toByteArray();
13414    }
13415
13416    @Override
13417    public void restorePreferredActivities(byte[] backup, int userId) {
13418        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13419            throw new SecurityException("Only the system may call restorePreferredActivities()");
13420        }
13421
13422        try {
13423            final XmlPullParser parser = Xml.newPullParser();
13424            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13425
13426            int type;
13427            while ((type = parser.next()) != XmlPullParser.START_TAG
13428                    && type != XmlPullParser.END_DOCUMENT) {
13429            }
13430            if (type != XmlPullParser.START_TAG) {
13431                // oops didn't find a start tag?!
13432                if (DEBUG_BACKUP) {
13433                    Slog.e(TAG, "Didn't find start tag during restore");
13434                }
13435                return;
13436            }
13437
13438            // this is supposed to be TAG_PREFERRED_BACKUP
13439            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13440                if (DEBUG_BACKUP) {
13441                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13442                }
13443                return;
13444            }
13445
13446            // skip interfering stuff, then we're aligned with the backing implementation
13447            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13448            synchronized (mPackages) {
13449                mSettings.readPreferredActivitiesLPw(parser, userId);
13450            }
13451        } catch (Exception e) {
13452            if (DEBUG_BACKUP) {
13453                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13454            }
13455        }
13456    }
13457
13458    @Override
13459    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13460            int sourceUserId, int targetUserId, int flags) {
13461        mContext.enforceCallingOrSelfPermission(
13462                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13463        int callingUid = Binder.getCallingUid();
13464        enforceOwnerRights(ownerPackage, callingUid);
13465        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13466        if (intentFilter.countActions() == 0) {
13467            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13468            return;
13469        }
13470        synchronized (mPackages) {
13471            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13472                    ownerPackage, targetUserId, flags);
13473            CrossProfileIntentResolver resolver =
13474                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13475            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13476            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13477            if (existing != null) {
13478                int size = existing.size();
13479                for (int i = 0; i < size; i++) {
13480                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13481                        return;
13482                    }
13483                }
13484            }
13485            resolver.addFilter(newFilter);
13486            scheduleWritePackageRestrictionsLocked(sourceUserId);
13487        }
13488    }
13489
13490    @Override
13491    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13492        mContext.enforceCallingOrSelfPermission(
13493                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13494        int callingUid = Binder.getCallingUid();
13495        enforceOwnerRights(ownerPackage, callingUid);
13496        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13497        synchronized (mPackages) {
13498            CrossProfileIntentResolver resolver =
13499                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13500            ArraySet<CrossProfileIntentFilter> set =
13501                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13502            for (CrossProfileIntentFilter filter : set) {
13503                if (filter.getOwnerPackage().equals(ownerPackage)) {
13504                    resolver.removeFilter(filter);
13505                }
13506            }
13507            scheduleWritePackageRestrictionsLocked(sourceUserId);
13508        }
13509    }
13510
13511    // Enforcing that callingUid is owning pkg on userId
13512    private void enforceOwnerRights(String pkg, int callingUid) {
13513        // The system owns everything.
13514        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13515            return;
13516        }
13517        int callingUserId = UserHandle.getUserId(callingUid);
13518        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13519        if (pi == null) {
13520            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13521                    + callingUserId);
13522        }
13523        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13524            throw new SecurityException("Calling uid " + callingUid
13525                    + " does not own package " + pkg);
13526        }
13527    }
13528
13529    @Override
13530    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13531        Intent intent = new Intent(Intent.ACTION_MAIN);
13532        intent.addCategory(Intent.CATEGORY_HOME);
13533
13534        final int callingUserId = UserHandle.getCallingUserId();
13535        List<ResolveInfo> list = queryIntentActivities(intent, null,
13536                PackageManager.GET_META_DATA, callingUserId);
13537        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13538                true, false, false, callingUserId);
13539
13540        allHomeCandidates.clear();
13541        if (list != null) {
13542            for (ResolveInfo ri : list) {
13543                allHomeCandidates.add(ri);
13544            }
13545        }
13546        return (preferred == null || preferred.activityInfo == null)
13547                ? null
13548                : new ComponentName(preferred.activityInfo.packageName,
13549                        preferred.activityInfo.name);
13550    }
13551
13552    @Override
13553    public void setApplicationEnabledSetting(String appPackageName,
13554            int newState, int flags, int userId, String callingPackage) {
13555        if (!sUserManager.exists(userId)) return;
13556        if (callingPackage == null) {
13557            callingPackage = Integer.toString(Binder.getCallingUid());
13558        }
13559        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13560    }
13561
13562    @Override
13563    public void setComponentEnabledSetting(ComponentName componentName,
13564            int newState, int flags, int userId) {
13565        if (!sUserManager.exists(userId)) return;
13566        setEnabledSetting(componentName.getPackageName(),
13567                componentName.getClassName(), newState, flags, userId, null);
13568    }
13569
13570    private void setEnabledSetting(final String packageName, String className, int newState,
13571            final int flags, int userId, String callingPackage) {
13572        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13573              || newState == COMPONENT_ENABLED_STATE_ENABLED
13574              || newState == COMPONENT_ENABLED_STATE_DISABLED
13575              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13576              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13577            throw new IllegalArgumentException("Invalid new component state: "
13578                    + newState);
13579        }
13580        PackageSetting pkgSetting;
13581        final int uid = Binder.getCallingUid();
13582        final int permission = mContext.checkCallingOrSelfPermission(
13583                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13584        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13585        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13586        boolean sendNow = false;
13587        boolean isApp = (className == null);
13588        String componentName = isApp ? packageName : className;
13589        int packageUid = -1;
13590        ArrayList<String> components;
13591
13592        // writer
13593        synchronized (mPackages) {
13594            pkgSetting = mSettings.mPackages.get(packageName);
13595            if (pkgSetting == null) {
13596                if (className == null) {
13597                    throw new IllegalArgumentException(
13598                            "Unknown package: " + packageName);
13599                }
13600                throw new IllegalArgumentException(
13601                        "Unknown component: " + packageName
13602                        + "/" + className);
13603            }
13604            // Allow root and verify that userId is not being specified by a different user
13605            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13606                throw new SecurityException(
13607                        "Permission Denial: attempt to change component state from pid="
13608                        + Binder.getCallingPid()
13609                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13610            }
13611            if (className == null) {
13612                // We're dealing with an application/package level state change
13613                if (pkgSetting.getEnabled(userId) == newState) {
13614                    // Nothing to do
13615                    return;
13616                }
13617                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13618                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13619                    // Don't care about who enables an app.
13620                    callingPackage = null;
13621                }
13622                pkgSetting.setEnabled(newState, userId, callingPackage);
13623                // pkgSetting.pkg.mSetEnabled = newState;
13624            } else {
13625                // We're dealing with a component level state change
13626                // First, verify that this is a valid class name.
13627                PackageParser.Package pkg = pkgSetting.pkg;
13628                if (pkg == null || !pkg.hasComponentClassName(className)) {
13629                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13630                        throw new IllegalArgumentException("Component class " + className
13631                                + " does not exist in " + packageName);
13632                    } else {
13633                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13634                                + className + " does not exist in " + packageName);
13635                    }
13636                }
13637                switch (newState) {
13638                case COMPONENT_ENABLED_STATE_ENABLED:
13639                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13640                        return;
13641                    }
13642                    break;
13643                case COMPONENT_ENABLED_STATE_DISABLED:
13644                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13645                        return;
13646                    }
13647                    break;
13648                case COMPONENT_ENABLED_STATE_DEFAULT:
13649                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13650                        return;
13651                    }
13652                    break;
13653                default:
13654                    Slog.e(TAG, "Invalid new component state: " + newState);
13655                    return;
13656                }
13657            }
13658            scheduleWritePackageRestrictionsLocked(userId);
13659            components = mPendingBroadcasts.get(userId, packageName);
13660            final boolean newPackage = components == null;
13661            if (newPackage) {
13662                components = new ArrayList<String>();
13663            }
13664            if (!components.contains(componentName)) {
13665                components.add(componentName);
13666            }
13667            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13668                sendNow = true;
13669                // Purge entry from pending broadcast list if another one exists already
13670                // since we are sending one right away.
13671                mPendingBroadcasts.remove(userId, packageName);
13672            } else {
13673                if (newPackage) {
13674                    mPendingBroadcasts.put(userId, packageName, components);
13675                }
13676                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13677                    // Schedule a message
13678                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13679                }
13680            }
13681        }
13682
13683        long callingId = Binder.clearCallingIdentity();
13684        try {
13685            if (sendNow) {
13686                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13687                sendPackageChangedBroadcast(packageName,
13688                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13689            }
13690        } finally {
13691            Binder.restoreCallingIdentity(callingId);
13692        }
13693    }
13694
13695    private void sendPackageChangedBroadcast(String packageName,
13696            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13697        if (DEBUG_INSTALL)
13698            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13699                    + componentNames);
13700        Bundle extras = new Bundle(4);
13701        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13702        String nameList[] = new String[componentNames.size()];
13703        componentNames.toArray(nameList);
13704        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13705        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13706        extras.putInt(Intent.EXTRA_UID, packageUid);
13707        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13708                new int[] {UserHandle.getUserId(packageUid)});
13709    }
13710
13711    @Override
13712    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13713        if (!sUserManager.exists(userId)) return;
13714        final int uid = Binder.getCallingUid();
13715        final int permission = mContext.checkCallingOrSelfPermission(
13716                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13717        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13718        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13719        // writer
13720        synchronized (mPackages) {
13721            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13722                    allowedByPermission, uid, userId)) {
13723                scheduleWritePackageRestrictionsLocked(userId);
13724            }
13725        }
13726    }
13727
13728    @Override
13729    public String getInstallerPackageName(String packageName) {
13730        // reader
13731        synchronized (mPackages) {
13732            return mSettings.getInstallerPackageNameLPr(packageName);
13733        }
13734    }
13735
13736    @Override
13737    public int getApplicationEnabledSetting(String packageName, int userId) {
13738        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13739        int uid = Binder.getCallingUid();
13740        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13741        // reader
13742        synchronized (mPackages) {
13743            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13744        }
13745    }
13746
13747    @Override
13748    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13749        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13750        int uid = Binder.getCallingUid();
13751        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13752        // reader
13753        synchronized (mPackages) {
13754            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13755        }
13756    }
13757
13758    @Override
13759    public void enterSafeMode() {
13760        enforceSystemOrRoot("Only the system can request entering safe mode");
13761
13762        if (!mSystemReady) {
13763            mSafeMode = true;
13764        }
13765    }
13766
13767    @Override
13768    public void systemReady() {
13769        mSystemReady = true;
13770
13771        // Read the compatibilty setting when the system is ready.
13772        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13773                mContext.getContentResolver(),
13774                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13775        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13776        if (DEBUG_SETTINGS) {
13777            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13778        }
13779
13780        synchronized (mPackages) {
13781            // Verify that all of the preferred activity components actually
13782            // exist.  It is possible for applications to be updated and at
13783            // that point remove a previously declared activity component that
13784            // had been set as a preferred activity.  We try to clean this up
13785            // the next time we encounter that preferred activity, but it is
13786            // possible for the user flow to never be able to return to that
13787            // situation so here we do a sanity check to make sure we haven't
13788            // left any junk around.
13789            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13790            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13791                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13792                removed.clear();
13793                for (PreferredActivity pa : pir.filterSet()) {
13794                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13795                        removed.add(pa);
13796                    }
13797                }
13798                if (removed.size() > 0) {
13799                    for (int r=0; r<removed.size(); r++) {
13800                        PreferredActivity pa = removed.get(r);
13801                        Slog.w(TAG, "Removing dangling preferred activity: "
13802                                + pa.mPref.mComponent);
13803                        pir.removeFilter(pa);
13804                    }
13805                    mSettings.writePackageRestrictionsLPr(
13806                            mSettings.mPreferredActivities.keyAt(i));
13807                }
13808            }
13809        }
13810        sUserManager.systemReady();
13811
13812        // If we upgraded grant all default permissions before kicking off.
13813        if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) {
13814            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
13815            for (int userId : UserManagerService.getInstance().getUserIds()) {
13816                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13817            }
13818        }
13819
13820        // Kick off any messages waiting for system ready
13821        if (mPostSystemReadyMessages != null) {
13822            for (Message msg : mPostSystemReadyMessages) {
13823                msg.sendToTarget();
13824            }
13825            mPostSystemReadyMessages = null;
13826        }
13827
13828        // Watch for external volumes that come and go over time
13829        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13830        storage.registerListener(mStorageListener);
13831
13832        mInstallerService.systemReady();
13833        mPackageDexOptimizer.systemReady();
13834    }
13835
13836    @Override
13837    public boolean isSafeMode() {
13838        return mSafeMode;
13839    }
13840
13841    @Override
13842    public boolean hasSystemUidErrors() {
13843        return mHasSystemUidErrors;
13844    }
13845
13846    static String arrayToString(int[] array) {
13847        StringBuffer buf = new StringBuffer(128);
13848        buf.append('[');
13849        if (array != null) {
13850            for (int i=0; i<array.length; i++) {
13851                if (i > 0) buf.append(", ");
13852                buf.append(array[i]);
13853            }
13854        }
13855        buf.append(']');
13856        return buf.toString();
13857    }
13858
13859    static class DumpState {
13860        public static final int DUMP_LIBS = 1 << 0;
13861        public static final int DUMP_FEATURES = 1 << 1;
13862        public static final int DUMP_RESOLVERS = 1 << 2;
13863        public static final int DUMP_PERMISSIONS = 1 << 3;
13864        public static final int DUMP_PACKAGES = 1 << 4;
13865        public static final int DUMP_SHARED_USERS = 1 << 5;
13866        public static final int DUMP_MESSAGES = 1 << 6;
13867        public static final int DUMP_PROVIDERS = 1 << 7;
13868        public static final int DUMP_VERIFIERS = 1 << 8;
13869        public static final int DUMP_PREFERRED = 1 << 9;
13870        public static final int DUMP_PREFERRED_XML = 1 << 10;
13871        public static final int DUMP_KEYSETS = 1 << 11;
13872        public static final int DUMP_VERSION = 1 << 12;
13873        public static final int DUMP_INSTALLS = 1 << 13;
13874        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13875        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13876
13877        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13878
13879        private int mTypes;
13880
13881        private int mOptions;
13882
13883        private boolean mTitlePrinted;
13884
13885        private SharedUserSetting mSharedUser;
13886
13887        public boolean isDumping(int type) {
13888            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13889                return true;
13890            }
13891
13892            return (mTypes & type) != 0;
13893        }
13894
13895        public void setDump(int type) {
13896            mTypes |= type;
13897        }
13898
13899        public boolean isOptionEnabled(int option) {
13900            return (mOptions & option) != 0;
13901        }
13902
13903        public void setOptionEnabled(int option) {
13904            mOptions |= option;
13905        }
13906
13907        public boolean onTitlePrinted() {
13908            final boolean printed = mTitlePrinted;
13909            mTitlePrinted = true;
13910            return printed;
13911        }
13912
13913        public boolean getTitlePrinted() {
13914            return mTitlePrinted;
13915        }
13916
13917        public void setTitlePrinted(boolean enabled) {
13918            mTitlePrinted = enabled;
13919        }
13920
13921        public SharedUserSetting getSharedUser() {
13922            return mSharedUser;
13923        }
13924
13925        public void setSharedUser(SharedUserSetting user) {
13926            mSharedUser = user;
13927        }
13928    }
13929
13930    @Override
13931    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13932        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13933                != PackageManager.PERMISSION_GRANTED) {
13934            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13935                    + Binder.getCallingPid()
13936                    + ", uid=" + Binder.getCallingUid()
13937                    + " without permission "
13938                    + android.Manifest.permission.DUMP);
13939            return;
13940        }
13941
13942        DumpState dumpState = new DumpState();
13943        boolean fullPreferred = false;
13944        boolean checkin = false;
13945
13946        String packageName = null;
13947
13948        int opti = 0;
13949        while (opti < args.length) {
13950            String opt = args[opti];
13951            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13952                break;
13953            }
13954            opti++;
13955
13956            if ("-a".equals(opt)) {
13957                // Right now we only know how to print all.
13958            } else if ("-h".equals(opt)) {
13959                pw.println("Package manager dump options:");
13960                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13961                pw.println("    --checkin: dump for a checkin");
13962                pw.println("    -f: print details of intent filters");
13963                pw.println("    -h: print this help");
13964                pw.println("  cmd may be one of:");
13965                pw.println("    l[ibraries]: list known shared libraries");
13966                pw.println("    f[ibraries]: list device features");
13967                pw.println("    k[eysets]: print known keysets");
13968                pw.println("    r[esolvers]: dump intent resolvers");
13969                pw.println("    perm[issions]: dump permissions");
13970                pw.println("    pref[erred]: print preferred package settings");
13971                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13972                pw.println("    prov[iders]: dump content providers");
13973                pw.println("    p[ackages]: dump installed packages");
13974                pw.println("    s[hared-users]: dump shared user IDs");
13975                pw.println("    m[essages]: print collected runtime messages");
13976                pw.println("    v[erifiers]: print package verifier info");
13977                pw.println("    version: print database version info");
13978                pw.println("    write: write current settings now");
13979                pw.println("    <package.name>: info about given package");
13980                pw.println("    installs: details about install sessions");
13981                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13982                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13983                return;
13984            } else if ("--checkin".equals(opt)) {
13985                checkin = true;
13986            } else if ("-f".equals(opt)) {
13987                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13988            } else {
13989                pw.println("Unknown argument: " + opt + "; use -h for help");
13990            }
13991        }
13992
13993        // Is the caller requesting to dump a particular piece of data?
13994        if (opti < args.length) {
13995            String cmd = args[opti];
13996            opti++;
13997            // Is this a package name?
13998            if ("android".equals(cmd) || cmd.contains(".")) {
13999                packageName = cmd;
14000                // When dumping a single package, we always dump all of its
14001                // filter information since the amount of data will be reasonable.
14002                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14003            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14004                dumpState.setDump(DumpState.DUMP_LIBS);
14005            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14006                dumpState.setDump(DumpState.DUMP_FEATURES);
14007            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14008                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14009            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14010                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14011            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14012                dumpState.setDump(DumpState.DUMP_PREFERRED);
14013            } else if ("preferred-xml".equals(cmd)) {
14014                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14015                if (opti < args.length && "--full".equals(args[opti])) {
14016                    fullPreferred = true;
14017                    opti++;
14018                }
14019            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14020                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14021            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14022                dumpState.setDump(DumpState.DUMP_PACKAGES);
14023            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14024                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14025            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14026                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14027            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14028                dumpState.setDump(DumpState.DUMP_MESSAGES);
14029            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14030                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14031            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14032                    || "intent-filter-verifiers".equals(cmd)) {
14033                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14034            } else if ("version".equals(cmd)) {
14035                dumpState.setDump(DumpState.DUMP_VERSION);
14036            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14037                dumpState.setDump(DumpState.DUMP_KEYSETS);
14038            } else if ("installs".equals(cmd)) {
14039                dumpState.setDump(DumpState.DUMP_INSTALLS);
14040            } else if ("write".equals(cmd)) {
14041                synchronized (mPackages) {
14042                    mSettings.writeLPr();
14043                    pw.println("Settings written.");
14044                    return;
14045                }
14046            }
14047        }
14048
14049        if (checkin) {
14050            pw.println("vers,1");
14051        }
14052
14053        // reader
14054        synchronized (mPackages) {
14055            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14056                if (!checkin) {
14057                    if (dumpState.onTitlePrinted())
14058                        pw.println();
14059                    pw.println("Database versions:");
14060                    pw.print("  SDK Version:");
14061                    pw.print(" internal=");
14062                    pw.print(mSettings.mInternalSdkPlatform);
14063                    pw.print(" external=");
14064                    pw.println(mSettings.mExternalSdkPlatform);
14065                    pw.print("  DB Version:");
14066                    pw.print(" internal=");
14067                    pw.print(mSettings.mInternalDatabaseVersion);
14068                    pw.print(" external=");
14069                    pw.println(mSettings.mExternalDatabaseVersion);
14070                }
14071            }
14072
14073            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14074                if (!checkin) {
14075                    if (dumpState.onTitlePrinted())
14076                        pw.println();
14077                    pw.println("Verifiers:");
14078                    pw.print("  Required: ");
14079                    pw.print(mRequiredVerifierPackage);
14080                    pw.print(" (uid=");
14081                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14082                    pw.println(")");
14083                } else if (mRequiredVerifierPackage != null) {
14084                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14085                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14086                }
14087            }
14088
14089            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14090                    packageName == null) {
14091                if (mIntentFilterVerifierComponent != null) {
14092                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14093                    if (!checkin) {
14094                        if (dumpState.onTitlePrinted())
14095                            pw.println();
14096                        pw.println("Intent Filter Verifier:");
14097                        pw.print("  Using: ");
14098                        pw.print(verifierPackageName);
14099                        pw.print(" (uid=");
14100                        pw.print(getPackageUid(verifierPackageName, 0));
14101                        pw.println(")");
14102                    } else if (verifierPackageName != null) {
14103                        pw.print("ifv,"); pw.print(verifierPackageName);
14104                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14105                    }
14106                } else {
14107                    pw.println();
14108                    pw.println("No Intent Filter Verifier available!");
14109                }
14110            }
14111
14112            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14113                boolean printedHeader = false;
14114                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14115                while (it.hasNext()) {
14116                    String name = it.next();
14117                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14118                    if (!checkin) {
14119                        if (!printedHeader) {
14120                            if (dumpState.onTitlePrinted())
14121                                pw.println();
14122                            pw.println("Libraries:");
14123                            printedHeader = true;
14124                        }
14125                        pw.print("  ");
14126                    } else {
14127                        pw.print("lib,");
14128                    }
14129                    pw.print(name);
14130                    if (!checkin) {
14131                        pw.print(" -> ");
14132                    }
14133                    if (ent.path != null) {
14134                        if (!checkin) {
14135                            pw.print("(jar) ");
14136                            pw.print(ent.path);
14137                        } else {
14138                            pw.print(",jar,");
14139                            pw.print(ent.path);
14140                        }
14141                    } else {
14142                        if (!checkin) {
14143                            pw.print("(apk) ");
14144                            pw.print(ent.apk);
14145                        } else {
14146                            pw.print(",apk,");
14147                            pw.print(ent.apk);
14148                        }
14149                    }
14150                    pw.println();
14151                }
14152            }
14153
14154            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14155                if (dumpState.onTitlePrinted())
14156                    pw.println();
14157                if (!checkin) {
14158                    pw.println("Features:");
14159                }
14160                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14161                while (it.hasNext()) {
14162                    String name = it.next();
14163                    if (!checkin) {
14164                        pw.print("  ");
14165                    } else {
14166                        pw.print("feat,");
14167                    }
14168                    pw.println(name);
14169                }
14170            }
14171
14172            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14173                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14174                        : "Activity Resolver Table:", "  ", packageName,
14175                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14176                    dumpState.setTitlePrinted(true);
14177                }
14178                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14179                        : "Receiver Resolver Table:", "  ", packageName,
14180                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14181                    dumpState.setTitlePrinted(true);
14182                }
14183                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14184                        : "Service Resolver Table:", "  ", packageName,
14185                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14186                    dumpState.setTitlePrinted(true);
14187                }
14188                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14189                        : "Provider Resolver Table:", "  ", packageName,
14190                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14191                    dumpState.setTitlePrinted(true);
14192                }
14193            }
14194
14195            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14196                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14197                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14198                    int user = mSettings.mPreferredActivities.keyAt(i);
14199                    if (pir.dump(pw,
14200                            dumpState.getTitlePrinted()
14201                                ? "\nPreferred Activities User " + user + ":"
14202                                : "Preferred Activities User " + user + ":", "  ",
14203                            packageName, true, false)) {
14204                        dumpState.setTitlePrinted(true);
14205                    }
14206                }
14207            }
14208
14209            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14210                pw.flush();
14211                FileOutputStream fout = new FileOutputStream(fd);
14212                BufferedOutputStream str = new BufferedOutputStream(fout);
14213                XmlSerializer serializer = new FastXmlSerializer();
14214                try {
14215                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14216                    serializer.startDocument(null, true);
14217                    serializer.setFeature(
14218                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14219                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14220                    serializer.endDocument();
14221                    serializer.flush();
14222                } catch (IllegalArgumentException e) {
14223                    pw.println("Failed writing: " + e);
14224                } catch (IllegalStateException e) {
14225                    pw.println("Failed writing: " + e);
14226                } catch (IOException e) {
14227                    pw.println("Failed writing: " + e);
14228                }
14229            }
14230
14231            if (!checkin
14232                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14233                    && packageName == null) {
14234                pw.println();
14235                int count = mSettings.mPackages.size();
14236                if (count == 0) {
14237                    pw.println("No domain preferred apps!");
14238                    pw.println();
14239                } else {
14240                    final String prefix = "  ";
14241                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14242                    if (allPackageSettings.size() == 0) {
14243                        pw.println("No domain preferred apps!");
14244                        pw.println();
14245                    } else {
14246                        pw.println("Domain preferred apps status:");
14247                        pw.println();
14248                        count = 0;
14249                        for (PackageSetting ps : allPackageSettings) {
14250                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14251                            if (ivi == null || ivi.getPackageName() == null) continue;
14252                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14253                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14254                            pw.println(prefix + "Status: " + ivi.getStatusString());
14255                            pw.println();
14256                            count++;
14257                        }
14258                        if (count == 0) {
14259                            pw.println(prefix + "No domain preferred app status!");
14260                            pw.println();
14261                        }
14262                        for (int userId : sUserManager.getUserIds()) {
14263                            pw.println("Domain preferred apps for User " + userId + ":");
14264                            pw.println();
14265                            count = 0;
14266                            for (PackageSetting ps : allPackageSettings) {
14267                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14268                                if (ivi == null || ivi.getPackageName() == null) {
14269                                    continue;
14270                                }
14271                                final int status = ps.getDomainVerificationStatusForUser(userId);
14272                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14273                                    continue;
14274                                }
14275                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14276                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14277                                String statusStr = IntentFilterVerificationInfo.
14278                                        getStatusStringFromValue(status);
14279                                pw.println(prefix + "Status: " + statusStr);
14280                                pw.println();
14281                                count++;
14282                            }
14283                            if (count == 0) {
14284                                pw.println(prefix + "No domain preferred apps!");
14285                                pw.println();
14286                            }
14287                        }
14288                    }
14289                }
14290            }
14291
14292            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14293                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14294                if (packageName == null) {
14295                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14296                        if (iperm == 0) {
14297                            if (dumpState.onTitlePrinted())
14298                                pw.println();
14299                            pw.println("AppOp Permissions:");
14300                        }
14301                        pw.print("  AppOp Permission ");
14302                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14303                        pw.println(":");
14304                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14305                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14306                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14307                        }
14308                    }
14309                }
14310            }
14311
14312            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14313                boolean printedSomething = false;
14314                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14315                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14316                        continue;
14317                    }
14318                    if (!printedSomething) {
14319                        if (dumpState.onTitlePrinted())
14320                            pw.println();
14321                        pw.println("Registered ContentProviders:");
14322                        printedSomething = true;
14323                    }
14324                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14325                    pw.print("    "); pw.println(p.toString());
14326                }
14327                printedSomething = false;
14328                for (Map.Entry<String, PackageParser.Provider> entry :
14329                        mProvidersByAuthority.entrySet()) {
14330                    PackageParser.Provider p = entry.getValue();
14331                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14332                        continue;
14333                    }
14334                    if (!printedSomething) {
14335                        if (dumpState.onTitlePrinted())
14336                            pw.println();
14337                        pw.println("ContentProvider Authorities:");
14338                        printedSomething = true;
14339                    }
14340                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14341                    pw.print("    "); pw.println(p.toString());
14342                    if (p.info != null && p.info.applicationInfo != null) {
14343                        final String appInfo = p.info.applicationInfo.toString();
14344                        pw.print("      applicationInfo="); pw.println(appInfo);
14345                    }
14346                }
14347            }
14348
14349            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14350                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14351            }
14352
14353            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14354                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14355            }
14356
14357            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14358                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14359            }
14360
14361            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14362                // XXX should handle packageName != null by dumping only install data that
14363                // the given package is involved with.
14364                if (dumpState.onTitlePrinted()) pw.println();
14365                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14366            }
14367
14368            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14369                if (dumpState.onTitlePrinted()) pw.println();
14370                mSettings.dumpReadMessagesLPr(pw, dumpState);
14371
14372                pw.println();
14373                pw.println("Package warning messages:");
14374                BufferedReader in = null;
14375                String line = null;
14376                try {
14377                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14378                    while ((line = in.readLine()) != null) {
14379                        if (line.contains("ignored: updated version")) continue;
14380                        pw.println(line);
14381                    }
14382                } catch (IOException ignored) {
14383                } finally {
14384                    IoUtils.closeQuietly(in);
14385                }
14386            }
14387
14388            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14389                BufferedReader in = null;
14390                String line = null;
14391                try {
14392                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14393                    while ((line = in.readLine()) != null) {
14394                        if (line.contains("ignored: updated version")) continue;
14395                        pw.print("msg,");
14396                        pw.println(line);
14397                    }
14398                } catch (IOException ignored) {
14399                } finally {
14400                    IoUtils.closeQuietly(in);
14401                }
14402            }
14403        }
14404    }
14405
14406    // ------- apps on sdcard specific code -------
14407    static final boolean DEBUG_SD_INSTALL = false;
14408
14409    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14410
14411    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14412
14413    private boolean mMediaMounted = false;
14414
14415    static String getEncryptKey() {
14416        try {
14417            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14418                    SD_ENCRYPTION_KEYSTORE_NAME);
14419            if (sdEncKey == null) {
14420                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14421                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14422                if (sdEncKey == null) {
14423                    Slog.e(TAG, "Failed to create encryption keys");
14424                    return null;
14425                }
14426            }
14427            return sdEncKey;
14428        } catch (NoSuchAlgorithmException nsae) {
14429            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14430            return null;
14431        } catch (IOException ioe) {
14432            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14433            return null;
14434        }
14435    }
14436
14437    /*
14438     * Update media status on PackageManager.
14439     */
14440    @Override
14441    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14442        int callingUid = Binder.getCallingUid();
14443        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14444            throw new SecurityException("Media status can only be updated by the system");
14445        }
14446        // reader; this apparently protects mMediaMounted, but should probably
14447        // be a different lock in that case.
14448        synchronized (mPackages) {
14449            Log.i(TAG, "Updating external media status from "
14450                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14451                    + (mediaStatus ? "mounted" : "unmounted"));
14452            if (DEBUG_SD_INSTALL)
14453                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14454                        + ", mMediaMounted=" + mMediaMounted);
14455            if (mediaStatus == mMediaMounted) {
14456                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14457                        : 0, -1);
14458                mHandler.sendMessage(msg);
14459                return;
14460            }
14461            mMediaMounted = mediaStatus;
14462        }
14463        // Queue up an async operation since the package installation may take a
14464        // little while.
14465        mHandler.post(new Runnable() {
14466            public void run() {
14467                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14468            }
14469        });
14470    }
14471
14472    /**
14473     * Called by MountService when the initial ASECs to scan are available.
14474     * Should block until all the ASEC containers are finished being scanned.
14475     */
14476    public void scanAvailableAsecs() {
14477        updateExternalMediaStatusInner(true, false, false);
14478        if (mShouldRestoreconData) {
14479            SELinuxMMAC.setRestoreconDone();
14480            mShouldRestoreconData = false;
14481        }
14482    }
14483
14484    /*
14485     * Collect information of applications on external media, map them against
14486     * existing containers and update information based on current mount status.
14487     * Please note that we always have to report status if reportStatus has been
14488     * set to true especially when unloading packages.
14489     */
14490    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14491            boolean externalStorage) {
14492        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14493        int[] uidArr = EmptyArray.INT;
14494
14495        final String[] list = PackageHelper.getSecureContainerList();
14496        if (ArrayUtils.isEmpty(list)) {
14497            Log.i(TAG, "No secure containers found");
14498        } else {
14499            // Process list of secure containers and categorize them
14500            // as active or stale based on their package internal state.
14501
14502            // reader
14503            synchronized (mPackages) {
14504                for (String cid : list) {
14505                    // Leave stages untouched for now; installer service owns them
14506                    if (PackageInstallerService.isStageName(cid)) continue;
14507
14508                    if (DEBUG_SD_INSTALL)
14509                        Log.i(TAG, "Processing container " + cid);
14510                    String pkgName = getAsecPackageName(cid);
14511                    if (pkgName == null) {
14512                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14513                        continue;
14514                    }
14515                    if (DEBUG_SD_INSTALL)
14516                        Log.i(TAG, "Looking for pkg : " + pkgName);
14517
14518                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14519                    if (ps == null) {
14520                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14521                        continue;
14522                    }
14523
14524                    /*
14525                     * Skip packages that are not external if we're unmounting
14526                     * external storage.
14527                     */
14528                    if (externalStorage && !isMounted && !isExternal(ps)) {
14529                        continue;
14530                    }
14531
14532                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14533                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14534                    // The package status is changed only if the code path
14535                    // matches between settings and the container id.
14536                    if (ps.codePathString != null
14537                            && ps.codePathString.startsWith(args.getCodePath())) {
14538                        if (DEBUG_SD_INSTALL) {
14539                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14540                                    + " at code path: " + ps.codePathString);
14541                        }
14542
14543                        // We do have a valid package installed on sdcard
14544                        processCids.put(args, ps.codePathString);
14545                        final int uid = ps.appId;
14546                        if (uid != -1) {
14547                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14548                        }
14549                    } else {
14550                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14551                                + ps.codePathString);
14552                    }
14553                }
14554            }
14555
14556            Arrays.sort(uidArr);
14557        }
14558
14559        // Process packages with valid entries.
14560        if (isMounted) {
14561            if (DEBUG_SD_INSTALL)
14562                Log.i(TAG, "Loading packages");
14563            loadMediaPackages(processCids, uidArr);
14564            startCleaningPackages();
14565            mInstallerService.onSecureContainersAvailable();
14566        } else {
14567            if (DEBUG_SD_INSTALL)
14568                Log.i(TAG, "Unloading packages");
14569            unloadMediaPackages(processCids, uidArr, reportStatus);
14570        }
14571    }
14572
14573    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14574            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14575        final int size = infos.size();
14576        final String[] packageNames = new String[size];
14577        final int[] packageUids = new int[size];
14578        for (int i = 0; i < size; i++) {
14579            final ApplicationInfo info = infos.get(i);
14580            packageNames[i] = info.packageName;
14581            packageUids[i] = info.uid;
14582        }
14583        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14584                finishedReceiver);
14585    }
14586
14587    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14588            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14589        sendResourcesChangedBroadcast(mediaStatus, replacing,
14590                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14591    }
14592
14593    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14594            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14595        int size = pkgList.length;
14596        if (size > 0) {
14597            // Send broadcasts here
14598            Bundle extras = new Bundle();
14599            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14600            if (uidArr != null) {
14601                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14602            }
14603            if (replacing) {
14604                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14605            }
14606            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14607                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14608            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14609        }
14610    }
14611
14612   /*
14613     * Look at potentially valid container ids from processCids If package
14614     * information doesn't match the one on record or package scanning fails,
14615     * the cid is added to list of removeCids. We currently don't delete stale
14616     * containers.
14617     */
14618    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14619        ArrayList<String> pkgList = new ArrayList<String>();
14620        Set<AsecInstallArgs> keys = processCids.keySet();
14621
14622        for (AsecInstallArgs args : keys) {
14623            String codePath = processCids.get(args);
14624            if (DEBUG_SD_INSTALL)
14625                Log.i(TAG, "Loading container : " + args.cid);
14626            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14627            try {
14628                // Make sure there are no container errors first.
14629                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14630                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14631                            + " when installing from sdcard");
14632                    continue;
14633                }
14634                // Check code path here.
14635                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14636                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14637                            + " does not match one in settings " + codePath);
14638                    continue;
14639                }
14640                // Parse package
14641                int parseFlags = mDefParseFlags;
14642                if (args.isExternalAsec()) {
14643                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14644                }
14645                if (args.isFwdLocked()) {
14646                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14647                }
14648
14649                synchronized (mInstallLock) {
14650                    PackageParser.Package pkg = null;
14651                    try {
14652                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14653                    } catch (PackageManagerException e) {
14654                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14655                    }
14656                    // Scan the package
14657                    if (pkg != null) {
14658                        /*
14659                         * TODO why is the lock being held? doPostInstall is
14660                         * called in other places without the lock. This needs
14661                         * to be straightened out.
14662                         */
14663                        // writer
14664                        synchronized (mPackages) {
14665                            retCode = PackageManager.INSTALL_SUCCEEDED;
14666                            pkgList.add(pkg.packageName);
14667                            // Post process args
14668                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14669                                    pkg.applicationInfo.uid);
14670                        }
14671                    } else {
14672                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14673                    }
14674                }
14675
14676            } finally {
14677                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14678                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14679                }
14680            }
14681        }
14682        // writer
14683        synchronized (mPackages) {
14684            // If the platform SDK has changed since the last time we booted,
14685            // we need to re-grant app permission to catch any new ones that
14686            // appear. This is really a hack, and means that apps can in some
14687            // cases get permissions that the user didn't initially explicitly
14688            // allow... it would be nice to have some better way to handle
14689            // this situation.
14690            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14691            if (regrantPermissions)
14692                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14693                        + mSdkVersion + "; regranting permissions for external storage");
14694            mSettings.mExternalSdkPlatform = mSdkVersion;
14695
14696            // Make sure group IDs have been assigned, and any permission
14697            // changes in other apps are accounted for
14698            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14699                    | (regrantPermissions
14700                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14701                            : 0));
14702
14703            mSettings.updateExternalDatabaseVersion();
14704
14705            // can downgrade to reader
14706            // Persist settings
14707            mSettings.writeLPr();
14708        }
14709        // Send a broadcast to let everyone know we are done processing
14710        if (pkgList.size() > 0) {
14711            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14712        }
14713    }
14714
14715   /*
14716     * Utility method to unload a list of specified containers
14717     */
14718    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14719        // Just unmount all valid containers.
14720        for (AsecInstallArgs arg : cidArgs) {
14721            synchronized (mInstallLock) {
14722                arg.doPostDeleteLI(false);
14723           }
14724       }
14725   }
14726
14727    /*
14728     * Unload packages mounted on external media. This involves deleting package
14729     * data from internal structures, sending broadcasts about diabled packages,
14730     * gc'ing to free up references, unmounting all secure containers
14731     * corresponding to packages on external media, and posting a
14732     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14733     * that we always have to post this message if status has been requested no
14734     * matter what.
14735     */
14736    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14737            final boolean reportStatus) {
14738        if (DEBUG_SD_INSTALL)
14739            Log.i(TAG, "unloading media packages");
14740        ArrayList<String> pkgList = new ArrayList<String>();
14741        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14742        final Set<AsecInstallArgs> keys = processCids.keySet();
14743        for (AsecInstallArgs args : keys) {
14744            String pkgName = args.getPackageName();
14745            if (DEBUG_SD_INSTALL)
14746                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14747            // Delete package internally
14748            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14749            synchronized (mInstallLock) {
14750                boolean res = deletePackageLI(pkgName, null, false, null, null,
14751                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14752                if (res) {
14753                    pkgList.add(pkgName);
14754                } else {
14755                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14756                    failedList.add(args);
14757                }
14758            }
14759        }
14760
14761        // reader
14762        synchronized (mPackages) {
14763            // We didn't update the settings after removing each package;
14764            // write them now for all packages.
14765            mSettings.writeLPr();
14766        }
14767
14768        // We have to absolutely send UPDATED_MEDIA_STATUS only
14769        // after confirming that all the receivers processed the ordered
14770        // broadcast when packages get disabled, force a gc to clean things up.
14771        // and unload all the containers.
14772        if (pkgList.size() > 0) {
14773            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14774                    new IIntentReceiver.Stub() {
14775                public void performReceive(Intent intent, int resultCode, String data,
14776                        Bundle extras, boolean ordered, boolean sticky,
14777                        int sendingUser) throws RemoteException {
14778                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14779                            reportStatus ? 1 : 0, 1, keys);
14780                    mHandler.sendMessage(msg);
14781                }
14782            });
14783        } else {
14784            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14785                    keys);
14786            mHandler.sendMessage(msg);
14787        }
14788    }
14789
14790    private void loadPrivatePackages(VolumeInfo vol) {
14791        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14792        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14793        synchronized (mInstallLock) {
14794        synchronized (mPackages) {
14795            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14796            for (PackageSetting ps : packages) {
14797                final PackageParser.Package pkg;
14798                try {
14799                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14800                    loaded.add(pkg.applicationInfo);
14801                } catch (PackageManagerException e) {
14802                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14803                }
14804            }
14805
14806            // TODO: regrant any permissions that changed based since original install
14807
14808            mSettings.writeLPr();
14809        }
14810        }
14811
14812        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14813        sendResourcesChangedBroadcast(true, false, loaded, null);
14814    }
14815
14816    private void unloadPrivatePackages(VolumeInfo vol) {
14817        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14818        synchronized (mInstallLock) {
14819        synchronized (mPackages) {
14820            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14821            for (PackageSetting ps : packages) {
14822                if (ps.pkg == null) continue;
14823
14824                final ApplicationInfo info = ps.pkg.applicationInfo;
14825                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14826                if (deletePackageLI(ps.name, null, false, null, null,
14827                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14828                    unloaded.add(info);
14829                } else {
14830                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14831                }
14832            }
14833
14834            mSettings.writeLPr();
14835        }
14836        }
14837
14838        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
14839        sendResourcesChangedBroadcast(false, false, unloaded, null);
14840    }
14841
14842    private void unfreezePackage(String packageName) {
14843        synchronized (mPackages) {
14844            final PackageSetting ps = mSettings.mPackages.get(packageName);
14845            if (ps != null) {
14846                ps.frozen = false;
14847            }
14848        }
14849    }
14850
14851    @Override
14852    public int movePackage(final String packageName, final String volumeUuid) {
14853        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14854
14855        final int moveId = mNextMoveId.getAndIncrement();
14856        try {
14857            movePackageInternal(packageName, volumeUuid, moveId);
14858        } catch (PackageManagerException e) {
14859            Slog.w(TAG, "Failed to move " + packageName, e);
14860            mMoveCallbacks.notifyStatusChanged(moveId,
14861                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14862        }
14863        return moveId;
14864    }
14865
14866    private void movePackageInternal(final String packageName, final String volumeUuid,
14867            final int moveId) throws PackageManagerException {
14868        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14869        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14870        final PackageManager pm = mContext.getPackageManager();
14871
14872        final boolean currentAsec;
14873        final String currentVolumeUuid;
14874        final File codeFile;
14875        final String installerPackageName;
14876        final String packageAbiOverride;
14877        final int appId;
14878        final String seinfo;
14879        final String label;
14880
14881        // reader
14882        synchronized (mPackages) {
14883            final PackageParser.Package pkg = mPackages.get(packageName);
14884            final PackageSetting ps = mSettings.mPackages.get(packageName);
14885            if (pkg == null || ps == null) {
14886                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14887            }
14888
14889            if (pkg.applicationInfo.isSystemApp()) {
14890                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14891                        "Cannot move system application");
14892            }
14893
14894            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14895                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14896                        "Package already moved to " + volumeUuid);
14897            }
14898
14899            final File probe = new File(pkg.codePath);
14900            final File probeOat = new File(probe, "oat");
14901            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14902                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14903                        "Move only supported for modern cluster style installs");
14904            }
14905
14906            if (ps.frozen) {
14907                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14908                        "Failed to move already frozen package");
14909            }
14910            ps.frozen = true;
14911
14912            currentAsec = pkg.applicationInfo.isForwardLocked()
14913                    || pkg.applicationInfo.isExternalAsec();
14914            currentVolumeUuid = ps.volumeUuid;
14915            codeFile = new File(pkg.codePath);
14916            installerPackageName = ps.installerPackageName;
14917            packageAbiOverride = ps.cpuAbiOverrideString;
14918            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14919            seinfo = pkg.applicationInfo.seinfo;
14920            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14921        }
14922
14923        // Now that we're guarded by frozen state, kill app during move
14924        killApplication(packageName, appId, "move pkg");
14925
14926        final Bundle extras = new Bundle();
14927        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14928        extras.putString(Intent.EXTRA_TITLE, label);
14929        mMoveCallbacks.notifyCreated(moveId, extras);
14930
14931        int installFlags;
14932        final boolean moveCompleteApp;
14933        final File measurePath;
14934
14935        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14936            installFlags = INSTALL_INTERNAL;
14937            moveCompleteApp = !currentAsec;
14938            measurePath = Environment.getDataAppDirectory(volumeUuid);
14939        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14940            installFlags = INSTALL_EXTERNAL;
14941            moveCompleteApp = false;
14942            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14943        } else {
14944            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14945            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14946                    || !volume.isMountedWritable()) {
14947                unfreezePackage(packageName);
14948                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14949                        "Move location not mounted private volume");
14950            }
14951
14952            Preconditions.checkState(!currentAsec);
14953
14954            installFlags = INSTALL_INTERNAL;
14955            moveCompleteApp = true;
14956            measurePath = Environment.getDataAppDirectory(volumeUuid);
14957        }
14958
14959        final PackageStats stats = new PackageStats(null, -1);
14960        synchronized (mInstaller) {
14961            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14962                unfreezePackage(packageName);
14963                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14964                        "Failed to measure package size");
14965            }
14966        }
14967
14968        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
14969                + stats.dataSize);
14970
14971        final long startFreeBytes = measurePath.getFreeSpace();
14972        final long sizeBytes;
14973        if (moveCompleteApp) {
14974            sizeBytes = stats.codeSize + stats.dataSize;
14975        } else {
14976            sizeBytes = stats.codeSize;
14977        }
14978
14979        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14980            unfreezePackage(packageName);
14981            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14982                    "Not enough free space to move");
14983        }
14984
14985        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14986
14987        final CountDownLatch installedLatch = new CountDownLatch(1);
14988        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14989            @Override
14990            public void onUserActionRequired(Intent intent) throws RemoteException {
14991                throw new IllegalStateException();
14992            }
14993
14994            @Override
14995            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14996                    Bundle extras) throws RemoteException {
14997                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
14998                        + PackageManager.installStatusToString(returnCode, msg));
14999
15000                installedLatch.countDown();
15001
15002                // Regardless of success or failure of the move operation,
15003                // always unfreeze the package
15004                unfreezePackage(packageName);
15005
15006                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15007                switch (status) {
15008                    case PackageInstaller.STATUS_SUCCESS:
15009                        mMoveCallbacks.notifyStatusChanged(moveId,
15010                                PackageManager.MOVE_SUCCEEDED);
15011                        break;
15012                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15013                        mMoveCallbacks.notifyStatusChanged(moveId,
15014                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15015                        break;
15016                    default:
15017                        mMoveCallbacks.notifyStatusChanged(moveId,
15018                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15019                        break;
15020                }
15021            }
15022        };
15023
15024        final MoveInfo move;
15025        if (moveCompleteApp) {
15026            // Kick off a thread to report progress estimates
15027            new Thread() {
15028                @Override
15029                public void run() {
15030                    while (true) {
15031                        try {
15032                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15033                                break;
15034                            }
15035                        } catch (InterruptedException ignored) {
15036                        }
15037
15038                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15039                        final int progress = 10 + (int) MathUtils.constrain(
15040                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15041                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15042                    }
15043                }
15044            }.start();
15045
15046            final String dataAppName = codeFile.getName();
15047            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15048                    dataAppName, appId, seinfo);
15049        } else {
15050            move = null;
15051        }
15052
15053        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15054
15055        final Message msg = mHandler.obtainMessage(INIT_COPY);
15056        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15057        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15058                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15059        mHandler.sendMessage(msg);
15060    }
15061
15062    @Override
15063    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15064        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15065
15066        final int realMoveId = mNextMoveId.getAndIncrement();
15067        final Bundle extras = new Bundle();
15068        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15069        mMoveCallbacks.notifyCreated(realMoveId, extras);
15070
15071        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15072            @Override
15073            public void onCreated(int moveId, Bundle extras) {
15074                // Ignored
15075            }
15076
15077            @Override
15078            public void onStatusChanged(int moveId, int status, long estMillis) {
15079                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15080            }
15081        };
15082
15083        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15084        storage.setPrimaryStorageUuid(volumeUuid, callback);
15085        return realMoveId;
15086    }
15087
15088    @Override
15089    public int getMoveStatus(int moveId) {
15090        mContext.enforceCallingOrSelfPermission(
15091                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15092        return mMoveCallbacks.mLastStatus.get(moveId);
15093    }
15094
15095    @Override
15096    public void registerMoveCallback(IPackageMoveObserver callback) {
15097        mContext.enforceCallingOrSelfPermission(
15098                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15099        mMoveCallbacks.register(callback);
15100    }
15101
15102    @Override
15103    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15104        mContext.enforceCallingOrSelfPermission(
15105                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15106        mMoveCallbacks.unregister(callback);
15107    }
15108
15109    @Override
15110    public boolean setInstallLocation(int loc) {
15111        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15112                null);
15113        if (getInstallLocation() == loc) {
15114            return true;
15115        }
15116        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15117                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15118            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15119                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15120            return true;
15121        }
15122        return false;
15123   }
15124
15125    @Override
15126    public int getInstallLocation() {
15127        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15128                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15129                PackageHelper.APP_INSTALL_AUTO);
15130    }
15131
15132    /** Called by UserManagerService */
15133    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15134        mDirtyUsers.remove(userHandle);
15135        mSettings.removeUserLPw(userHandle);
15136        mPendingBroadcasts.remove(userHandle);
15137        if (mInstaller != null) {
15138            // Technically, we shouldn't be doing this with the package lock
15139            // held.  However, this is very rare, and there is already so much
15140            // other disk I/O going on, that we'll let it slide for now.
15141            final StorageManager storage = StorageManager.from(mContext);
15142            final List<VolumeInfo> vols = storage.getVolumes();
15143            for (VolumeInfo vol : vols) {
15144                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15145                    final String volumeUuid = vol.getFsUuid();
15146                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15147                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15148                }
15149            }
15150        }
15151        mUserNeedsBadging.delete(userHandle);
15152        removeUnusedPackagesLILPw(userManager, userHandle);
15153    }
15154
15155    /**
15156     * We're removing userHandle and would like to remove any downloaded packages
15157     * that are no longer in use by any other user.
15158     * @param userHandle the user being removed
15159     */
15160    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15161        final boolean DEBUG_CLEAN_APKS = false;
15162        int [] users = userManager.getUserIdsLPr();
15163        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15164        while (psit.hasNext()) {
15165            PackageSetting ps = psit.next();
15166            if (ps.pkg == null) {
15167                continue;
15168            }
15169            final String packageName = ps.pkg.packageName;
15170            // Skip over if system app
15171            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15172                continue;
15173            }
15174            if (DEBUG_CLEAN_APKS) {
15175                Slog.i(TAG, "Checking package " + packageName);
15176            }
15177            boolean keep = false;
15178            for (int i = 0; i < users.length; i++) {
15179                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15180                    keep = true;
15181                    if (DEBUG_CLEAN_APKS) {
15182                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15183                                + users[i]);
15184                    }
15185                    break;
15186                }
15187            }
15188            if (!keep) {
15189                if (DEBUG_CLEAN_APKS) {
15190                    Slog.i(TAG, "  Removing package " + packageName);
15191                }
15192                mHandler.post(new Runnable() {
15193                    public void run() {
15194                        deletePackageX(packageName, userHandle, 0);
15195                    } //end run
15196                });
15197            }
15198        }
15199    }
15200
15201    /** Called by UserManagerService */
15202    void createNewUserLILPw(int userHandle, File path) {
15203        if (mInstaller != null) {
15204            mInstaller.createUserConfig(userHandle);
15205            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15206        }
15207    }
15208
15209    void newUserCreatedLILPw(final int userHandle) {
15210        // We cannot grant the default permissions with a lock held as
15211        // we query providers from other components for default handlers
15212        // such as enabled IMEs, etc.
15213        mHandler.post(new Runnable() {
15214            @Override
15215            public void run() {
15216                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15217            }
15218        });
15219    }
15220
15221    @Override
15222    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15223        mContext.enforceCallingOrSelfPermission(
15224                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15225                "Only package verification agents can read the verifier device identity");
15226
15227        synchronized (mPackages) {
15228            return mSettings.getVerifierDeviceIdentityLPw();
15229        }
15230    }
15231
15232    @Override
15233    public void setPermissionEnforced(String permission, boolean enforced) {
15234        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15235        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15236            synchronized (mPackages) {
15237                if (mSettings.mReadExternalStorageEnforced == null
15238                        || mSettings.mReadExternalStorageEnforced != enforced) {
15239                    mSettings.mReadExternalStorageEnforced = enforced;
15240                    mSettings.writeLPr();
15241                }
15242            }
15243            // kill any non-foreground processes so we restart them and
15244            // grant/revoke the GID.
15245            final IActivityManager am = ActivityManagerNative.getDefault();
15246            if (am != null) {
15247                final long token = Binder.clearCallingIdentity();
15248                try {
15249                    am.killProcessesBelowForeground("setPermissionEnforcement");
15250                } catch (RemoteException e) {
15251                } finally {
15252                    Binder.restoreCallingIdentity(token);
15253                }
15254            }
15255        } else {
15256            throw new IllegalArgumentException("No selective enforcement for " + permission);
15257        }
15258    }
15259
15260    @Override
15261    @Deprecated
15262    public boolean isPermissionEnforced(String permission) {
15263        return true;
15264    }
15265
15266    @Override
15267    public boolean isStorageLow() {
15268        final long token = Binder.clearCallingIdentity();
15269        try {
15270            final DeviceStorageMonitorInternal
15271                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15272            if (dsm != null) {
15273                return dsm.isMemoryLow();
15274            } else {
15275                return false;
15276            }
15277        } finally {
15278            Binder.restoreCallingIdentity(token);
15279        }
15280    }
15281
15282    @Override
15283    public IPackageInstaller getPackageInstaller() {
15284        return mInstallerService;
15285    }
15286
15287    private boolean userNeedsBadging(int userId) {
15288        int index = mUserNeedsBadging.indexOfKey(userId);
15289        if (index < 0) {
15290            final UserInfo userInfo;
15291            final long token = Binder.clearCallingIdentity();
15292            try {
15293                userInfo = sUserManager.getUserInfo(userId);
15294            } finally {
15295                Binder.restoreCallingIdentity(token);
15296            }
15297            final boolean b;
15298            if (userInfo != null && userInfo.isManagedProfile()) {
15299                b = true;
15300            } else {
15301                b = false;
15302            }
15303            mUserNeedsBadging.put(userId, b);
15304            return b;
15305        }
15306        return mUserNeedsBadging.valueAt(index);
15307    }
15308
15309    @Override
15310    public KeySet getKeySetByAlias(String packageName, String alias) {
15311        if (packageName == null || alias == null) {
15312            return null;
15313        }
15314        synchronized(mPackages) {
15315            final PackageParser.Package pkg = mPackages.get(packageName);
15316            if (pkg == null) {
15317                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15318                throw new IllegalArgumentException("Unknown package: " + packageName);
15319            }
15320            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15321            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15322        }
15323    }
15324
15325    @Override
15326    public KeySet getSigningKeySet(String packageName) {
15327        if (packageName == null) {
15328            return null;
15329        }
15330        synchronized(mPackages) {
15331            final PackageParser.Package pkg = mPackages.get(packageName);
15332            if (pkg == null) {
15333                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15334                throw new IllegalArgumentException("Unknown package: " + packageName);
15335            }
15336            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15337                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15338                throw new SecurityException("May not access signing KeySet of other apps.");
15339            }
15340            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15341            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15342        }
15343    }
15344
15345    @Override
15346    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15347        if (packageName == null || ks == null) {
15348            return false;
15349        }
15350        synchronized(mPackages) {
15351            final PackageParser.Package pkg = mPackages.get(packageName);
15352            if (pkg == null) {
15353                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15354                throw new IllegalArgumentException("Unknown package: " + packageName);
15355            }
15356            IBinder ksh = ks.getToken();
15357            if (ksh instanceof KeySetHandle) {
15358                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15359                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15360            }
15361            return false;
15362        }
15363    }
15364
15365    @Override
15366    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15367        if (packageName == null || ks == null) {
15368            return false;
15369        }
15370        synchronized(mPackages) {
15371            final PackageParser.Package pkg = mPackages.get(packageName);
15372            if (pkg == null) {
15373                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15374                throw new IllegalArgumentException("Unknown package: " + packageName);
15375            }
15376            IBinder ksh = ks.getToken();
15377            if (ksh instanceof KeySetHandle) {
15378                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15379                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15380            }
15381            return false;
15382        }
15383    }
15384
15385    public void getUsageStatsIfNoPackageUsageInfo() {
15386        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15387            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15388            if (usm == null) {
15389                throw new IllegalStateException("UsageStatsManager must be initialized");
15390            }
15391            long now = System.currentTimeMillis();
15392            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15393            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15394                String packageName = entry.getKey();
15395                PackageParser.Package pkg = mPackages.get(packageName);
15396                if (pkg == null) {
15397                    continue;
15398                }
15399                UsageStats usage = entry.getValue();
15400                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15401                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15402            }
15403        }
15404    }
15405
15406    /**
15407     * Check and throw if the given before/after packages would be considered a
15408     * downgrade.
15409     */
15410    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15411            throws PackageManagerException {
15412        if (after.versionCode < before.mVersionCode) {
15413            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15414                    "Update version code " + after.versionCode + " is older than current "
15415                    + before.mVersionCode);
15416        } else if (after.versionCode == before.mVersionCode) {
15417            if (after.baseRevisionCode < before.baseRevisionCode) {
15418                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15419                        "Update base revision code " + after.baseRevisionCode
15420                        + " is older than current " + before.baseRevisionCode);
15421            }
15422
15423            if (!ArrayUtils.isEmpty(after.splitNames)) {
15424                for (int i = 0; i < after.splitNames.length; i++) {
15425                    final String splitName = after.splitNames[i];
15426                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15427                    if (j != -1) {
15428                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15429                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15430                                    "Update split " + splitName + " revision code "
15431                                    + after.splitRevisionCodes[i] + " is older than current "
15432                                    + before.splitRevisionCodes[j]);
15433                        }
15434                    }
15435                }
15436            }
15437        }
15438    }
15439
15440    private static class MoveCallbacks extends Handler {
15441        private static final int MSG_CREATED = 1;
15442        private static final int MSG_STATUS_CHANGED = 2;
15443
15444        private final RemoteCallbackList<IPackageMoveObserver>
15445                mCallbacks = new RemoteCallbackList<>();
15446
15447        private final SparseIntArray mLastStatus = new SparseIntArray();
15448
15449        public MoveCallbacks(Looper looper) {
15450            super(looper);
15451        }
15452
15453        public void register(IPackageMoveObserver callback) {
15454            mCallbacks.register(callback);
15455        }
15456
15457        public void unregister(IPackageMoveObserver callback) {
15458            mCallbacks.unregister(callback);
15459        }
15460
15461        @Override
15462        public void handleMessage(Message msg) {
15463            final SomeArgs args = (SomeArgs) msg.obj;
15464            final int n = mCallbacks.beginBroadcast();
15465            for (int i = 0; i < n; i++) {
15466                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15467                try {
15468                    invokeCallback(callback, msg.what, args);
15469                } catch (RemoteException ignored) {
15470                }
15471            }
15472            mCallbacks.finishBroadcast();
15473            args.recycle();
15474        }
15475
15476        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15477                throws RemoteException {
15478            switch (what) {
15479                case MSG_CREATED: {
15480                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15481                    break;
15482                }
15483                case MSG_STATUS_CHANGED: {
15484                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15485                    break;
15486                }
15487            }
15488        }
15489
15490        private void notifyCreated(int moveId, Bundle extras) {
15491            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15492
15493            final SomeArgs args = SomeArgs.obtain();
15494            args.argi1 = moveId;
15495            args.arg2 = extras;
15496            obtainMessage(MSG_CREATED, args).sendToTarget();
15497        }
15498
15499        private void notifyStatusChanged(int moveId, int status) {
15500            notifyStatusChanged(moveId, status, -1);
15501        }
15502
15503        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15504            Slog.v(TAG, "Move " + moveId + " status " + status);
15505
15506            final SomeArgs args = SomeArgs.obtain();
15507            args.argi1 = moveId;
15508            args.argi2 = status;
15509            args.arg3 = estMillis;
15510            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15511
15512            synchronized (mLastStatus) {
15513                mLastStatus.put(moveId, status);
15514            }
15515        }
15516    }
15517
15518    private final class OnPermissionChangeListeners extends Handler {
15519        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15520
15521        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15522                new RemoteCallbackList<>();
15523
15524        public OnPermissionChangeListeners(Looper looper) {
15525            super(looper);
15526        }
15527
15528        @Override
15529        public void handleMessage(Message msg) {
15530            switch (msg.what) {
15531                case MSG_ON_PERMISSIONS_CHANGED: {
15532                    final int uid = msg.arg1;
15533                    handleOnPermissionsChanged(uid);
15534                } break;
15535            }
15536        }
15537
15538        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15539            mPermissionListeners.register(listener);
15540
15541        }
15542
15543        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15544            mPermissionListeners.unregister(listener);
15545        }
15546
15547        public void onPermissionsChanged(int uid) {
15548            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15549                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15550            }
15551        }
15552
15553        private void handleOnPermissionsChanged(int uid) {
15554            final int count = mPermissionListeners.beginBroadcast();
15555            try {
15556                for (int i = 0; i < count; i++) {
15557                    IOnPermissionsChangeListener callback = mPermissionListeners
15558                            .getBroadcastItem(i);
15559                    try {
15560                        callback.onPermissionsChanged(uid);
15561                    } catch (RemoteException e) {
15562                        Log.e(TAG, "Permission listener is dead", e);
15563                    }
15564                }
15565            } finally {
15566                mPermissionListeners.finishBroadcast();
15567            }
15568        }
15569    }
15570
15571    private class PackageManagerInternalImpl extends PackageManagerInternal {
15572        @Override
15573        public void setLocationPackagesProvider(PackagesProvider provider) {
15574            synchronized (mPackages) {
15575                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15576            }
15577        }
15578
15579        @Override
15580        public void setImePackagesProvider(PackagesProvider provider) {
15581            synchronized (mPackages) {
15582                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15583            }
15584        }
15585
15586        @Override
15587        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15588            synchronized (mPackages) {
15589                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15590            }
15591        }
15592    }
15593
15594    @Override
15595    public void grantDefaultPermissions(final int userId) {
15596        enforceSystemOrPhoneCaller("grantDefaultPermissions");
15597        long token = Binder.clearCallingIdentity();
15598        try {
15599            // We cannot grant the default permissions with a lock held as
15600            // we query providers from other components for default handlers
15601            // such as enabled IMEs, etc.
15602            mHandler.post(new Runnable() {
15603                @Override
15604                public void run() {
15605                    mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15606                }
15607            });
15608        } finally {
15609            Binder.restoreCallingIdentity(token);
15610        }
15611    }
15612
15613    @Override
15614    public void setCarrierAppPackagesProvider(final IPackagesProvider provider) {
15615        enforceSystemOrPhoneCaller("setCarrierAppPackagesProvider");
15616        long token = Binder.clearCallingIdentity();
15617        try {
15618            PackageManagerInternal.PackagesProvider wrapper =
15619                    new PackageManagerInternal.PackagesProvider() {
15620                @Override
15621                public String[] getPackages(int userId) {
15622                    try {
15623                        return provider.getPackages(userId);
15624                    } catch (RemoteException e) {
15625                        return null;
15626                    }
15627                }
15628            };
15629            synchronized (mPackages) {
15630                mDefaultPermissionPolicy.setCarrierAppPackagesProviderLPw(wrapper);
15631            }
15632        } finally {
15633            Binder.restoreCallingIdentity(token);
15634        }
15635    }
15636
15637    private static void enforceSystemOrPhoneCaller(String tag) {
15638        int callingUid = Binder.getCallingUid();
15639        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
15640            throw new SecurityException(
15641                    "Cannot call " + tag + " from UID " + callingUid);
15642        }
15643    }
15644}
15645