PackageManagerService.java revision 2a30be19006ede27ee524da89b6c4a1b551b1d76
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.FIRST_APPLICATION_UID;
59import static android.os.Process.PACKAGE_INFO_GID;
60import static android.os.Process.SYSTEM_UID;
61import static android.system.OsConstants.O_CREAT;
62import static android.system.OsConstants.O_RDWR;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
67import static com.android.internal.util.ArrayUtils.appendInt;
68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
73
74import android.Manifest;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IOnPermissionsChangeListener;
96import android.content.pm.IPackageDataObserver;
97import android.content.pm.IPackageDeleteObserver;
98import android.content.pm.IPackageDeleteObserver2;
99import android.content.pm.IPackageInstallObserver2;
100import android.content.pm.IPackageInstaller;
101import android.content.pm.IPackageManager;
102import android.content.pm.IPackageMoveObserver;
103import android.content.pm.IPackageStatsObserver;
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.PackageParser;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageStats;
119import android.content.pm.PackageUserState;
120import android.content.pm.ParceledListSlice;
121import android.content.pm.PermissionGroupInfo;
122import android.content.pm.PermissionInfo;
123import android.content.pm.ProviderInfo;
124import android.content.pm.ResolveInfo;
125import android.content.pm.ServiceInfo;
126import android.content.pm.Signature;
127import android.content.pm.UserInfo;
128import android.content.pm.VerificationParams;
129import android.content.pm.VerifierDeviceIdentity;
130import android.content.pm.VerifierInfo;
131import android.content.res.Resources;
132import android.hardware.display.DisplayManager;
133import android.net.Uri;
134import android.os.Binder;
135import android.os.Build;
136import android.os.Bundle;
137import android.os.Debug;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.FileUtils;
141import android.os.Handler;
142import android.os.IBinder;
143import android.os.Looper;
144import android.os.Message;
145import android.os.Parcel;
146import android.os.ParcelFileDescriptor;
147import android.os.Process;
148import android.os.RemoteCallbackList;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.os.storage.IMountService;
157import android.os.storage.StorageEventListener;
158import android.os.storage.StorageManager;
159import android.os.storage.VolumeInfo;
160import android.os.storage.VolumeRecord;
161import android.security.KeyStore;
162import android.security.SystemKeyStore;
163import android.system.ErrnoException;
164import android.system.Os;
165import android.system.StructStat;
166import android.text.TextUtils;
167import android.text.format.DateUtils;
168import android.util.ArrayMap;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.MathUtils;
177import android.util.PrintStreamPrinter;
178import android.util.Slog;
179import android.util.SparseArray;
180import android.util.SparseBooleanArray;
181import android.util.SparseIntArray;
182import android.util.Xml;
183import android.view.Display;
184
185import dalvik.system.DexFile;
186import dalvik.system.VMRuntime;
187
188import libcore.io.IoUtils;
189import libcore.util.EmptyArray;
190
191import com.android.internal.R;
192import com.android.internal.app.IMediaContainerService;
193import com.android.internal.app.ResolverActivity;
194import com.android.internal.content.NativeLibraryHelper;
195import com.android.internal.content.PackageHelper;
196import com.android.internal.os.IParcelFileDescriptorFactory;
197import com.android.internal.os.SomeArgs;
198import com.android.internal.util.ArrayUtils;
199import com.android.internal.util.FastPrintWriter;
200import com.android.internal.util.FastXmlSerializer;
201import com.android.internal.util.IndentingPrintWriter;
202import com.android.internal.util.Preconditions;
203import com.android.server.EventLogTags;
204import com.android.server.FgThread;
205import com.android.server.IntentResolver;
206import com.android.server.LocalServices;
207import com.android.server.ServiceThread;
208import com.android.server.SystemConfig;
209import com.android.server.Watchdog;
210import com.android.server.pm.Settings.DatabaseVersion;
211import com.android.server.pm.PermissionsState.PermissionState;
212import com.android.server.storage.DeviceStorageMonitorInternal;
213
214import org.xmlpull.v1.XmlPullParser;
215import org.xmlpull.v1.XmlSerializer;
216
217import java.io.BufferedInputStream;
218import java.io.BufferedOutputStream;
219import java.io.BufferedReader;
220import java.io.ByteArrayInputStream;
221import java.io.ByteArrayOutputStream;
222import java.io.File;
223import java.io.FileDescriptor;
224import java.io.FileNotFoundException;
225import java.io.FileOutputStream;
226import java.io.FileReader;
227import java.io.FilenameFilter;
228import java.io.IOException;
229import java.io.InputStream;
230import java.io.PrintWriter;
231import java.nio.charset.StandardCharsets;
232import java.security.NoSuchAlgorithmException;
233import java.security.PublicKey;
234import java.security.cert.CertificateEncodingException;
235import java.security.cert.CertificateException;
236import java.text.SimpleDateFormat;
237import java.util.ArrayList;
238import java.util.Arrays;
239import java.util.Collection;
240import java.util.Collections;
241import java.util.Comparator;
242import java.util.Date;
243import java.util.Iterator;
244import java.util.List;
245import java.util.Map;
246import java.util.Objects;
247import java.util.Set;
248import java.util.concurrent.CountDownLatch;
249import java.util.concurrent.TimeUnit;
250import java.util.concurrent.atomic.AtomicBoolean;
251import java.util.concurrent.atomic.AtomicInteger;
252import java.util.concurrent.atomic.AtomicLong;
253
254/**
255 * Keep track of all those .apks everywhere.
256 *
257 * This is very central to the platform's security; please run the unit
258 * tests whenever making modifications here:
259 *
260mmm frameworks/base/tests/AndroidTests
261adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
262adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
263 *
264 * {@hide}
265 */
266public class PackageManagerService extends IPackageManager.Stub {
267    static final String TAG = "PackageManager";
268    static final boolean DEBUG_SETTINGS = false;
269    static final boolean DEBUG_PREFERRED = false;
270    static final boolean DEBUG_UPGRADE = false;
271    private static final boolean DEBUG_BACKUP = true;
272    private static final boolean DEBUG_INSTALL = false;
273    private static final boolean DEBUG_REMOVE = false;
274    private static final boolean DEBUG_BROADCASTS = false;
275    private static final boolean DEBUG_SHOW_INFO = false;
276    private static final boolean DEBUG_PACKAGE_INFO = false;
277    private static final boolean DEBUG_INTENT_MATCHING = false;
278    private static final boolean DEBUG_PACKAGE_SCANNING = false;
279    private static final boolean DEBUG_VERIFY = false;
280    private static final boolean DEBUG_DEXOPT = false;
281    private static final boolean DEBUG_ABI_SELECTION = false;
282    private static final boolean DEBUG_DOMAIN_VERIFICATION = false;
283
284    private static final int RADIO_UID = Process.PHONE_UID;
285    private static final int LOG_UID = Process.LOG_UID;
286    private static final int NFC_UID = Process.NFC_UID;
287    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
288    private static final int SHELL_UID = Process.SHELL_UID;
289
290    // Cap the size of permission trees that 3rd party apps can define
291    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
292
293    // Suffix used during package installation when copying/moving
294    // package apks to install directory.
295    private static final String INSTALL_PACKAGE_SUFFIX = "-";
296
297    static final int SCAN_NO_DEX = 1<<1;
298    static final int SCAN_FORCE_DEX = 1<<2;
299    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
300    static final int SCAN_NEW_INSTALL = 1<<4;
301    static final int SCAN_NO_PATHS = 1<<5;
302    static final int SCAN_UPDATE_TIME = 1<<6;
303    static final int SCAN_DEFER_DEX = 1<<7;
304    static final int SCAN_BOOTING = 1<<8;
305    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
306    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
307    static final int SCAN_REQUIRE_KNOWN = 1<<12;
308    static final int SCAN_MOVE = 1<<13;
309
310    static final int REMOVE_CHATTY = 1<<16;
311
312    private static final int[] EMPTY_INT_ARRAY = new int[0];
313
314    /**
315     * Timeout (in milliseconds) after which the watchdog should declare that
316     * our handler thread is wedged.  The usual default for such things is one
317     * minute but we sometimes do very lengthy I/O operations on this thread,
318     * such as installing multi-gigabyte applications, so ours needs to be longer.
319     */
320    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
321
322    /**
323     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
324     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
325     * settings entry if available, otherwise we use the hardcoded default.  If it's been
326     * more than this long since the last fstrim, we force one during the boot sequence.
327     *
328     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
329     * one gets run at the next available charging+idle time.  This final mandatory
330     * no-fstrim check kicks in only of the other scheduling criteria is never met.
331     */
332    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
333
334    /**
335     * Whether verification is enabled by default.
336     */
337    private static final boolean DEFAULT_VERIFY_ENABLE = true;
338
339    /**
340     * The default maximum time to wait for the verification agent to return in
341     * milliseconds.
342     */
343    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
344
345    /**
346     * The default response for package verification timeout.
347     *
348     * This can be either PackageManager.VERIFICATION_ALLOW or
349     * PackageManager.VERIFICATION_REJECT.
350     */
351    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
352
353    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
354
355    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
356            DEFAULT_CONTAINER_PACKAGE,
357            "com.android.defcontainer.DefaultContainerService");
358
359    private static final String KILL_APP_REASON_GIDS_CHANGED =
360            "permission grant or revoke changed gids";
361
362    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
363            "permissions revoked";
364
365    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
366
367    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
368
369    /** Permission grant: not grant the permission. */
370    private static final int GRANT_DENIED = 1;
371
372    /** Permission grant: grant the permission as an install permission. */
373    private static final int GRANT_INSTALL = 2;
374
375    /** Permission grant: grant the permission as an install permission for a legacy app. */
376    private static final int GRANT_INSTALL_LEGACY = 3;
377
378    /** Permission grant: grant the permission as a runtime one. */
379    private static final int GRANT_RUNTIME = 4;
380
381    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
382    private static final int GRANT_UPGRADE = 5;
383
384    final ServiceThread mHandlerThread;
385
386    final PackageHandler mHandler;
387
388    /**
389     * Messages for {@link #mHandler} that need to wait for system ready before
390     * being dispatched.
391     */
392    private ArrayList<Message> mPostSystemReadyMessages;
393
394    final int mSdkVersion = Build.VERSION.SDK_INT;
395
396    final Context mContext;
397    final boolean mFactoryTest;
398    final boolean mOnlyCore;
399    final boolean mLazyDexOpt;
400    final long mDexOptLRUThresholdInMills;
401    final DisplayMetrics mMetrics;
402    final int mDefParseFlags;
403    final String[] mSeparateProcesses;
404    final boolean mIsUpgrade;
405
406    // This is where all application persistent data goes.
407    final File mAppDataDir;
408
409    // This is where all application persistent data goes for secondary users.
410    final File mUserAppDataDir;
411
412    /** The location for ASEC container files on internal storage. */
413    final String mAsecInternalPath;
414
415    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
416    // LOCK HELD.  Can be called with mInstallLock held.
417    final Installer mInstaller;
418
419    /** Directory where installed third-party apps stored */
420    final File mAppInstallDir;
421
422    /**
423     * Directory to which applications installed internally have their
424     * 32 bit native libraries copied.
425     */
426    private File mAppLib32InstallDir;
427
428    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
429    // apps.
430    final File mDrmAppPrivateInstallDir;
431
432    // ----------------------------------------------------------------
433
434    // Lock for state used when installing and doing other long running
435    // operations.  Methods that must be called with this lock held have
436    // the suffix "LI".
437    final Object mInstallLock = new Object();
438
439    // ----------------------------------------------------------------
440
441    // Keys are String (package name), values are Package.  This also serves
442    // as the lock for the global state.  Methods that must be called with
443    // this lock held have the prefix "LP".
444    final ArrayMap<String, PackageParser.Package> mPackages =
445            new ArrayMap<String, PackageParser.Package>();
446
447    // Tracks available target package names -> overlay package paths.
448    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
449        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
450
451    final Settings mSettings;
452    boolean mRestoredSettings;
453
454    // System configuration read by SystemConfig.
455    final int[] mGlobalGids;
456    final SparseArray<ArraySet<String>> mSystemPermissions;
457    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
458
459    // If mac_permissions.xml was found for seinfo labeling.
460    boolean mFoundPolicyFile;
461
462    // If a recursive restorecon of /data/data/<pkg> is needed.
463    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
464
465    public static final class SharedLibraryEntry {
466        public final String path;
467        public final String apk;
468
469        SharedLibraryEntry(String _path, String _apk) {
470            path = _path;
471            apk = _apk;
472        }
473    }
474
475    // Currently known shared libraries.
476    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
477            new ArrayMap<String, SharedLibraryEntry>();
478
479    // All available activities, for your resolving pleasure.
480    final ActivityIntentResolver mActivities =
481            new ActivityIntentResolver();
482
483    // All available receivers, for your resolving pleasure.
484    final ActivityIntentResolver mReceivers =
485            new ActivityIntentResolver();
486
487    // All available services, for your resolving pleasure.
488    final ServiceIntentResolver mServices = new ServiceIntentResolver();
489
490    // All available providers, for your resolving pleasure.
491    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
492
493    // Mapping from provider base names (first directory in content URI codePath)
494    // to the provider information.
495    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
496            new ArrayMap<String, PackageParser.Provider>();
497
498    // Mapping from instrumentation class names to info about them.
499    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
500            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
501
502    // Mapping from permission names to info about them.
503    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
504            new ArrayMap<String, PackageParser.PermissionGroup>();
505
506    // Packages whose data we have transfered into another package, thus
507    // should no longer exist.
508    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
509
510    // Broadcast actions that are only available to the system.
511    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
512
513    /** List of packages waiting for verification. */
514    final SparseArray<PackageVerificationState> mPendingVerification
515            = new SparseArray<PackageVerificationState>();
516
517    /** Set of packages associated with each app op permission. */
518    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
519
520    final PackageInstallerService mInstallerService;
521
522    private final PackageDexOptimizer mPackageDexOptimizer;
523
524    private AtomicInteger mNextMoveId = new AtomicInteger();
525    private final MoveCallbacks mMoveCallbacks;
526
527    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
528
529    // Cache of users who need badging.
530    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
531
532    /** Token for keys in mPendingVerification. */
533    private int mPendingVerificationToken = 0;
534
535    volatile boolean mSystemReady;
536    volatile boolean mSafeMode;
537    volatile boolean mHasSystemUidErrors;
538
539    ApplicationInfo mAndroidApplication;
540    final ActivityInfo mResolveActivity = new ActivityInfo();
541    final ResolveInfo mResolveInfo = new ResolveInfo();
542    ComponentName mResolveComponentName;
543    PackageParser.Package mPlatformPackage;
544    ComponentName mCustomResolverComponentName;
545
546    boolean mResolverReplaced = false;
547
548    private final ComponentName mIntentFilterVerifierComponent;
549    private int mIntentFilterVerificationToken = 0;
550
551    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
552            = new SparseArray<IntentFilterVerificationState>();
553
554    private interface IntentFilterVerifier<T extends IntentFilter> {
555        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
556                                               T filter, String packageName);
557        void startVerifications(int userId);
558        void receiveVerificationResponse(int verificationId);
559    }
560
561    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
562        private Context mContext;
563        private ComponentName mIntentFilterVerifierComponent;
564        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
565
566        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
567            mContext = context;
568            mIntentFilterVerifierComponent = verifierComponent;
569        }
570
571        private String getDefaultScheme() {
572            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
573            return IntentFilter.SCHEME_HTTP;
574        }
575
576        @Override
577        public void startVerifications(int userId) {
578            // Launch verifications requests
579            int count = mCurrentIntentFilterVerifications.size();
580            for (int n=0; n<count; n++) {
581                int verificationId = mCurrentIntentFilterVerifications.get(n);
582                final IntentFilterVerificationState ivs =
583                        mIntentFilterVerificationStates.get(verificationId);
584
585                String packageName = ivs.getPackageName();
586
587                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
588                final int filterCount = filters.size();
589                ArraySet<String> domainsSet = new ArraySet<>();
590                for (int m=0; m<filterCount; m++) {
591                    PackageParser.ActivityIntentInfo filter = filters.get(m);
592                    domainsSet.addAll(filter.getHostsList());
593                }
594                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
595                synchronized (mPackages) {
596                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
597                            packageName, domainsList) != null) {
598                        scheduleWriteSettingsLocked();
599                    }
600                }
601                sendVerificationRequest(userId, verificationId, ivs);
602            }
603            mCurrentIntentFilterVerifications.clear();
604        }
605
606        private void sendVerificationRequest(int userId, int verificationId,
607                IntentFilterVerificationState ivs) {
608
609            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
610            verificationIntent.putExtra(
611                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
612                    verificationId);
613            verificationIntent.putExtra(
614                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
615                    getDefaultScheme());
616            verificationIntent.putExtra(
617                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
618                    ivs.getHostsString());
619            verificationIntent.putExtra(
620                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
621                    ivs.getPackageName());
622            verificationIntent.setComponent(mIntentFilterVerifierComponent);
623            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
624
625            UserHandle user = new UserHandle(userId);
626            mContext.sendBroadcastAsUser(verificationIntent, user);
627            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
628                    "Sending IntenFilter verification broadcast");
629        }
630
631        public void receiveVerificationResponse(int verificationId) {
632            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
633
634            final boolean verified = ivs.isVerified();
635
636            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
637            final int count = filters.size();
638            for (int n=0; n<count; n++) {
639                PackageParser.ActivityIntentInfo filter = filters.get(n);
640                filter.setVerified(verified);
641
642                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
643                        + " verified with result:" + verified + " and hosts:"
644                        + ivs.getHostsString());
645            }
646
647            mIntentFilterVerificationStates.remove(verificationId);
648
649            final String packageName = ivs.getPackageName();
650            IntentFilterVerificationInfo ivi = null;
651
652            synchronized (mPackages) {
653                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
654            }
655            if (ivi == null) {
656                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
657                        + verificationId + " packageName:" + packageName);
658                return;
659            }
660            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
661                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
662
663            synchronized (mPackages) {
664                if (verified) {
665                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
666                } else {
667                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
668                }
669                scheduleWriteSettingsLocked();
670
671                final int userId = ivs.getUserId();
672                if (userId != UserHandle.USER_ALL) {
673                    final int userStatus =
674                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
675
676                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
677                    boolean needUpdate = false;
678
679                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
680                    // already been set by the User thru the Disambiguation dialog
681                    switch (userStatus) {
682                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
683                            if (verified) {
684                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
685                            } else {
686                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
687                            }
688                            needUpdate = true;
689                            break;
690
691                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
692                            if (verified) {
693                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
694                                needUpdate = true;
695                            }
696                            break;
697
698                        default:
699                            // Nothing to do
700                    }
701
702                    if (needUpdate) {
703                        mSettings.updateIntentFilterVerificationStatusLPw(
704                                packageName, updatedStatus, userId);
705                        scheduleWritePackageRestrictionsLocked(userId);
706                    }
707                }
708            }
709        }
710
711        @Override
712        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
713                    ActivityIntentInfo filter, String packageName) {
714            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
715                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
716                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
717                        "IntentFilter does not contain HTTP nor HTTPS data scheme");
718                return false;
719            }
720            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
721            if (ivs == null) {
722                ivs = createDomainVerificationState(verifierId, userId, verificationId,
723                        packageName);
724            }
725            if (!hasValidDomains(filter)) {
726                return false;
727            }
728            ivs.addFilter(filter);
729            return true;
730        }
731
732        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
733                int userId, int verificationId, String packageName) {
734            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
735                    verifierId, userId, packageName);
736            ivs.setPendingState();
737            synchronized (mPackages) {
738                mIntentFilterVerificationStates.append(verificationId, ivs);
739                mCurrentIntentFilterVerifications.add(verificationId);
740            }
741            return ivs;
742        }
743    }
744
745    private static boolean hasValidDomains(ActivityIntentInfo filter) {
746        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
747                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
748        if (!hasHTTPorHTTPS) {
749            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
750                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
751            return false;
752        }
753        return true;
754    }
755
756    private IntentFilterVerifier mIntentFilterVerifier;
757
758    // Set of pending broadcasts for aggregating enable/disable of components.
759    static class PendingPackageBroadcasts {
760        // for each user id, a map of <package name -> components within that package>
761        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
762
763        public PendingPackageBroadcasts() {
764            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
765        }
766
767        public ArrayList<String> get(int userId, String packageName) {
768            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
769            return packages.get(packageName);
770        }
771
772        public void put(int userId, String packageName, ArrayList<String> components) {
773            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
774            packages.put(packageName, components);
775        }
776
777        public void remove(int userId, String packageName) {
778            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
779            if (packages != null) {
780                packages.remove(packageName);
781            }
782        }
783
784        public void remove(int userId) {
785            mUidMap.remove(userId);
786        }
787
788        public int userIdCount() {
789            return mUidMap.size();
790        }
791
792        public int userIdAt(int n) {
793            return mUidMap.keyAt(n);
794        }
795
796        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
797            return mUidMap.get(userId);
798        }
799
800        public int size() {
801            // total number of pending broadcast entries across all userIds
802            int num = 0;
803            for (int i = 0; i< mUidMap.size(); i++) {
804                num += mUidMap.valueAt(i).size();
805            }
806            return num;
807        }
808
809        public void clear() {
810            mUidMap.clear();
811        }
812
813        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
814            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
815            if (map == null) {
816                map = new ArrayMap<String, ArrayList<String>>();
817                mUidMap.put(userId, map);
818            }
819            return map;
820        }
821    }
822    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
823
824    // Service Connection to remote media container service to copy
825    // package uri's from external media onto secure containers
826    // or internal storage.
827    private IMediaContainerService mContainerService = null;
828
829    static final int SEND_PENDING_BROADCAST = 1;
830    static final int MCS_BOUND = 3;
831    static final int END_COPY = 4;
832    static final int INIT_COPY = 5;
833    static final int MCS_UNBIND = 6;
834    static final int START_CLEANING_PACKAGE = 7;
835    static final int FIND_INSTALL_LOC = 8;
836    static final int POST_INSTALL = 9;
837    static final int MCS_RECONNECT = 10;
838    static final int MCS_GIVE_UP = 11;
839    static final int UPDATED_MEDIA_STATUS = 12;
840    static final int WRITE_SETTINGS = 13;
841    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
842    static final int PACKAGE_VERIFIED = 15;
843    static final int CHECK_PENDING_VERIFICATION = 16;
844    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
845    static final int INTENT_FILTER_VERIFIED = 18;
846
847    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
848
849    // Delay time in millisecs
850    static final int BROADCAST_DELAY = 10 * 1000;
851
852    static UserManagerService sUserManager;
853
854    // Stores a list of users whose package restrictions file needs to be updated
855    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
856
857    final private DefaultContainerConnection mDefContainerConn =
858            new DefaultContainerConnection();
859    class DefaultContainerConnection implements ServiceConnection {
860        public void onServiceConnected(ComponentName name, IBinder service) {
861            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
862            IMediaContainerService imcs =
863                IMediaContainerService.Stub.asInterface(service);
864            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
865        }
866
867        public void onServiceDisconnected(ComponentName name) {
868            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
869        }
870    };
871
872    // Recordkeeping of restore-after-install operations that are currently in flight
873    // between the Package Manager and the Backup Manager
874    class PostInstallData {
875        public InstallArgs args;
876        public PackageInstalledInfo res;
877
878        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
879            args = _a;
880            res = _r;
881        }
882    };
883    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
884    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
885
886    // backup/restore of preferred activity state
887    private static final String TAG_PREFERRED_BACKUP = "pa";
888
889    private final String mRequiredVerifierPackage;
890
891    private final PackageUsage mPackageUsage = new PackageUsage();
892
893    private class PackageUsage {
894        private static final int WRITE_INTERVAL
895            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
896
897        private final Object mFileLock = new Object();
898        private final AtomicLong mLastWritten = new AtomicLong(0);
899        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
900
901        private boolean mIsHistoricalPackageUsageAvailable = true;
902
903        boolean isHistoricalPackageUsageAvailable() {
904            return mIsHistoricalPackageUsageAvailable;
905        }
906
907        void write(boolean force) {
908            if (force) {
909                writeInternal();
910                return;
911            }
912            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
913                && !DEBUG_DEXOPT) {
914                return;
915            }
916            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
917                new Thread("PackageUsage_DiskWriter") {
918                    @Override
919                    public void run() {
920                        try {
921                            writeInternal();
922                        } finally {
923                            mBackgroundWriteRunning.set(false);
924                        }
925                    }
926                }.start();
927            }
928        }
929
930        private void writeInternal() {
931            synchronized (mPackages) {
932                synchronized (mFileLock) {
933                    AtomicFile file = getFile();
934                    FileOutputStream f = null;
935                    try {
936                        f = file.startWrite();
937                        BufferedOutputStream out = new BufferedOutputStream(f);
938                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
939                        StringBuilder sb = new StringBuilder();
940                        for (PackageParser.Package pkg : mPackages.values()) {
941                            if (pkg.mLastPackageUsageTimeInMills == 0) {
942                                continue;
943                            }
944                            sb.setLength(0);
945                            sb.append(pkg.packageName);
946                            sb.append(' ');
947                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
948                            sb.append('\n');
949                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
950                        }
951                        out.flush();
952                        file.finishWrite(f);
953                    } catch (IOException e) {
954                        if (f != null) {
955                            file.failWrite(f);
956                        }
957                        Log.e(TAG, "Failed to write package usage times", e);
958                    }
959                }
960            }
961            mLastWritten.set(SystemClock.elapsedRealtime());
962        }
963
964        void readLP() {
965            synchronized (mFileLock) {
966                AtomicFile file = getFile();
967                BufferedInputStream in = null;
968                try {
969                    in = new BufferedInputStream(file.openRead());
970                    StringBuffer sb = new StringBuffer();
971                    while (true) {
972                        String packageName = readToken(in, sb, ' ');
973                        if (packageName == null) {
974                            break;
975                        }
976                        String timeInMillisString = readToken(in, sb, '\n');
977                        if (timeInMillisString == null) {
978                            throw new IOException("Failed to find last usage time for package "
979                                                  + packageName);
980                        }
981                        PackageParser.Package pkg = mPackages.get(packageName);
982                        if (pkg == null) {
983                            continue;
984                        }
985                        long timeInMillis;
986                        try {
987                            timeInMillis = Long.parseLong(timeInMillisString.toString());
988                        } catch (NumberFormatException e) {
989                            throw new IOException("Failed to parse " + timeInMillisString
990                                                  + " as a long.", e);
991                        }
992                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
993                    }
994                } catch (FileNotFoundException expected) {
995                    mIsHistoricalPackageUsageAvailable = false;
996                } catch (IOException e) {
997                    Log.w(TAG, "Failed to read package usage times", e);
998                } finally {
999                    IoUtils.closeQuietly(in);
1000                }
1001            }
1002            mLastWritten.set(SystemClock.elapsedRealtime());
1003        }
1004
1005        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1006                throws IOException {
1007            sb.setLength(0);
1008            while (true) {
1009                int ch = in.read();
1010                if (ch == -1) {
1011                    if (sb.length() == 0) {
1012                        return null;
1013                    }
1014                    throw new IOException("Unexpected EOF");
1015                }
1016                if (ch == endOfToken) {
1017                    return sb.toString();
1018                }
1019                sb.append((char)ch);
1020            }
1021        }
1022
1023        private AtomicFile getFile() {
1024            File dataDir = Environment.getDataDirectory();
1025            File systemDir = new File(dataDir, "system");
1026            File fname = new File(systemDir, "package-usage.list");
1027            return new AtomicFile(fname);
1028        }
1029    }
1030
1031    class PackageHandler extends Handler {
1032        private boolean mBound = false;
1033        final ArrayList<HandlerParams> mPendingInstalls =
1034            new ArrayList<HandlerParams>();
1035
1036        private boolean connectToService() {
1037            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1038                    " DefaultContainerService");
1039            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1040            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1041            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1042                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1043                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1044                mBound = true;
1045                return true;
1046            }
1047            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1048            return false;
1049        }
1050
1051        private void disconnectService() {
1052            mContainerService = null;
1053            mBound = false;
1054            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1055            mContext.unbindService(mDefContainerConn);
1056            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1057        }
1058
1059        PackageHandler(Looper looper) {
1060            super(looper);
1061        }
1062
1063        public void handleMessage(Message msg) {
1064            try {
1065                doHandleMessage(msg);
1066            } finally {
1067                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1068            }
1069        }
1070
1071        void doHandleMessage(Message msg) {
1072            switch (msg.what) {
1073                case INIT_COPY: {
1074                    HandlerParams params = (HandlerParams) msg.obj;
1075                    int idx = mPendingInstalls.size();
1076                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1077                    // If a bind was already initiated we dont really
1078                    // need to do anything. The pending install
1079                    // will be processed later on.
1080                    if (!mBound) {
1081                        // If this is the only one pending we might
1082                        // have to bind to the service again.
1083                        if (!connectToService()) {
1084                            Slog.e(TAG, "Failed to bind to media container service");
1085                            params.serviceError();
1086                            return;
1087                        } else {
1088                            // Once we bind to the service, the first
1089                            // pending request will be processed.
1090                            mPendingInstalls.add(idx, params);
1091                        }
1092                    } else {
1093                        mPendingInstalls.add(idx, params);
1094                        // Already bound to the service. Just make
1095                        // sure we trigger off processing the first request.
1096                        if (idx == 0) {
1097                            mHandler.sendEmptyMessage(MCS_BOUND);
1098                        }
1099                    }
1100                    break;
1101                }
1102                case MCS_BOUND: {
1103                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1104                    if (msg.obj != null) {
1105                        mContainerService = (IMediaContainerService) msg.obj;
1106                    }
1107                    if (mContainerService == null) {
1108                        // Something seriously wrong. Bail out
1109                        Slog.e(TAG, "Cannot bind to media container service");
1110                        for (HandlerParams params : mPendingInstalls) {
1111                            // Indicate service bind error
1112                            params.serviceError();
1113                        }
1114                        mPendingInstalls.clear();
1115                    } else if (mPendingInstalls.size() > 0) {
1116                        HandlerParams params = mPendingInstalls.get(0);
1117                        if (params != null) {
1118                            if (params.startCopy()) {
1119                                // We are done...  look for more work or to
1120                                // go idle.
1121                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1122                                        "Checking for more work or unbind...");
1123                                // Delete pending install
1124                                if (mPendingInstalls.size() > 0) {
1125                                    mPendingInstalls.remove(0);
1126                                }
1127                                if (mPendingInstalls.size() == 0) {
1128                                    if (mBound) {
1129                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1130                                                "Posting delayed MCS_UNBIND");
1131                                        removeMessages(MCS_UNBIND);
1132                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1133                                        // Unbind after a little delay, to avoid
1134                                        // continual thrashing.
1135                                        sendMessageDelayed(ubmsg, 10000);
1136                                    }
1137                                } else {
1138                                    // There are more pending requests in queue.
1139                                    // Just post MCS_BOUND message to trigger processing
1140                                    // of next pending install.
1141                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1142                                            "Posting MCS_BOUND for next work");
1143                                    mHandler.sendEmptyMessage(MCS_BOUND);
1144                                }
1145                            }
1146                        }
1147                    } else {
1148                        // Should never happen ideally.
1149                        Slog.w(TAG, "Empty queue");
1150                    }
1151                    break;
1152                }
1153                case MCS_RECONNECT: {
1154                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1155                    if (mPendingInstalls.size() > 0) {
1156                        if (mBound) {
1157                            disconnectService();
1158                        }
1159                        if (!connectToService()) {
1160                            Slog.e(TAG, "Failed to bind to media container service");
1161                            for (HandlerParams params : mPendingInstalls) {
1162                                // Indicate service bind error
1163                                params.serviceError();
1164                            }
1165                            mPendingInstalls.clear();
1166                        }
1167                    }
1168                    break;
1169                }
1170                case MCS_UNBIND: {
1171                    // If there is no actual work left, then time to unbind.
1172                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1173
1174                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1175                        if (mBound) {
1176                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1177
1178                            disconnectService();
1179                        }
1180                    } else if (mPendingInstalls.size() > 0) {
1181                        // There are more pending requests in queue.
1182                        // Just post MCS_BOUND message to trigger processing
1183                        // of next pending install.
1184                        mHandler.sendEmptyMessage(MCS_BOUND);
1185                    }
1186
1187                    break;
1188                }
1189                case MCS_GIVE_UP: {
1190                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1191                    mPendingInstalls.remove(0);
1192                    break;
1193                }
1194                case SEND_PENDING_BROADCAST: {
1195                    String packages[];
1196                    ArrayList<String> components[];
1197                    int size = 0;
1198                    int uids[];
1199                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1200                    synchronized (mPackages) {
1201                        if (mPendingBroadcasts == null) {
1202                            return;
1203                        }
1204                        size = mPendingBroadcasts.size();
1205                        if (size <= 0) {
1206                            // Nothing to be done. Just return
1207                            return;
1208                        }
1209                        packages = new String[size];
1210                        components = new ArrayList[size];
1211                        uids = new int[size];
1212                        int i = 0;  // filling out the above arrays
1213
1214                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1215                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1216                            Iterator<Map.Entry<String, ArrayList<String>>> it
1217                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1218                                            .entrySet().iterator();
1219                            while (it.hasNext() && i < size) {
1220                                Map.Entry<String, ArrayList<String>> ent = it.next();
1221                                packages[i] = ent.getKey();
1222                                components[i] = ent.getValue();
1223                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1224                                uids[i] = (ps != null)
1225                                        ? UserHandle.getUid(packageUserId, ps.appId)
1226                                        : -1;
1227                                i++;
1228                            }
1229                        }
1230                        size = i;
1231                        mPendingBroadcasts.clear();
1232                    }
1233                    // Send broadcasts
1234                    for (int i = 0; i < size; i++) {
1235                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1236                    }
1237                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1238                    break;
1239                }
1240                case START_CLEANING_PACKAGE: {
1241                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1242                    final String packageName = (String)msg.obj;
1243                    final int userId = msg.arg1;
1244                    final boolean andCode = msg.arg2 != 0;
1245                    synchronized (mPackages) {
1246                        if (userId == UserHandle.USER_ALL) {
1247                            int[] users = sUserManager.getUserIds();
1248                            for (int user : users) {
1249                                mSettings.addPackageToCleanLPw(
1250                                        new PackageCleanItem(user, packageName, andCode));
1251                            }
1252                        } else {
1253                            mSettings.addPackageToCleanLPw(
1254                                    new PackageCleanItem(userId, packageName, andCode));
1255                        }
1256                    }
1257                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1258                    startCleaningPackages();
1259                } break;
1260                case POST_INSTALL: {
1261                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1262                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1263                    mRunningInstalls.delete(msg.arg1);
1264                    boolean deleteOld = false;
1265
1266                    if (data != null) {
1267                        InstallArgs args = data.args;
1268                        PackageInstalledInfo res = data.res;
1269
1270                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1271                            res.removedInfo.sendBroadcast(false, true, false);
1272                            Bundle extras = new Bundle(1);
1273                            extras.putInt(Intent.EXTRA_UID, res.uid);
1274
1275                            // Now that we successfully installed the package, grant runtime
1276                            // permissions if requested before broadcasting the install.
1277                            if ((args.installFlags
1278                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1279                                grantRequestedRuntimePermissions(res.pkg,
1280                                        args.user.getIdentifier());
1281                            }
1282
1283                            // Determine the set of users who are adding this
1284                            // package for the first time vs. those who are seeing
1285                            // an update.
1286                            int[] firstUsers;
1287                            int[] updateUsers = new int[0];
1288                            if (res.origUsers == null || res.origUsers.length == 0) {
1289                                firstUsers = res.newUsers;
1290                            } else {
1291                                firstUsers = new int[0];
1292                                for (int i=0; i<res.newUsers.length; i++) {
1293                                    int user = res.newUsers[i];
1294                                    boolean isNew = true;
1295                                    for (int j=0; j<res.origUsers.length; j++) {
1296                                        if (res.origUsers[j] == user) {
1297                                            isNew = false;
1298                                            break;
1299                                        }
1300                                    }
1301                                    if (isNew) {
1302                                        int[] newFirst = new int[firstUsers.length+1];
1303                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1304                                                firstUsers.length);
1305                                        newFirst[firstUsers.length] = user;
1306                                        firstUsers = newFirst;
1307                                    } else {
1308                                        int[] newUpdate = new int[updateUsers.length+1];
1309                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1310                                                updateUsers.length);
1311                                        newUpdate[updateUsers.length] = user;
1312                                        updateUsers = newUpdate;
1313                                    }
1314                                }
1315                            }
1316                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1317                                    res.pkg.applicationInfo.packageName,
1318                                    extras, null, null, firstUsers);
1319                            final boolean update = res.removedInfo.removedPackage != null;
1320                            if (update) {
1321                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1322                            }
1323                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1324                                    res.pkg.applicationInfo.packageName,
1325                                    extras, null, null, updateUsers);
1326                            if (update) {
1327                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1328                                        res.pkg.applicationInfo.packageName,
1329                                        extras, null, null, updateUsers);
1330                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1331                                        null, null,
1332                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1333
1334                                // treat asec-hosted packages like removable media on upgrade
1335                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1336                                    if (DEBUG_INSTALL) {
1337                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1338                                                + " is ASEC-hosted -> AVAILABLE");
1339                                    }
1340                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1341                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1342                                    pkgList.add(res.pkg.applicationInfo.packageName);
1343                                    sendResourcesChangedBroadcast(true, true,
1344                                            pkgList,uidArray, null);
1345                                }
1346                            }
1347                            if (res.removedInfo.args != null) {
1348                                // Remove the replaced package's older resources safely now
1349                                deleteOld = true;
1350                            }
1351
1352                            // Log current value of "unknown sources" setting
1353                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1354                                getUnknownSourcesSettings());
1355                        }
1356                        // Force a gc to clear up things
1357                        Runtime.getRuntime().gc();
1358                        // We delete after a gc for applications  on sdcard.
1359                        if (deleteOld) {
1360                            synchronized (mInstallLock) {
1361                                res.removedInfo.args.doPostDeleteLI(true);
1362                            }
1363                        }
1364                        if (args.observer != null) {
1365                            try {
1366                                Bundle extras = extrasForInstallResult(res);
1367                                args.observer.onPackageInstalled(res.name, res.returnCode,
1368                                        res.returnMsg, extras);
1369                            } catch (RemoteException e) {
1370                                Slog.i(TAG, "Observer no longer exists.");
1371                            }
1372                        }
1373                    } else {
1374                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1375                    }
1376                } break;
1377                case UPDATED_MEDIA_STATUS: {
1378                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1379                    boolean reportStatus = msg.arg1 == 1;
1380                    boolean doGc = msg.arg2 == 1;
1381                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1382                    if (doGc) {
1383                        // Force a gc to clear up stale containers.
1384                        Runtime.getRuntime().gc();
1385                    }
1386                    if (msg.obj != null) {
1387                        @SuppressWarnings("unchecked")
1388                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1389                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1390                        // Unload containers
1391                        unloadAllContainers(args);
1392                    }
1393                    if (reportStatus) {
1394                        try {
1395                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1396                            PackageHelper.getMountService().finishMediaUpdate();
1397                        } catch (RemoteException e) {
1398                            Log.e(TAG, "MountService not running?");
1399                        }
1400                    }
1401                } break;
1402                case WRITE_SETTINGS: {
1403                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1404                    synchronized (mPackages) {
1405                        removeMessages(WRITE_SETTINGS);
1406                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1407                        mSettings.writeLPr();
1408                        mDirtyUsers.clear();
1409                    }
1410                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1411                } break;
1412                case WRITE_PACKAGE_RESTRICTIONS: {
1413                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1414                    synchronized (mPackages) {
1415                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1416                        for (int userId : mDirtyUsers) {
1417                            mSettings.writePackageRestrictionsLPr(userId);
1418                        }
1419                        mDirtyUsers.clear();
1420                    }
1421                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422                } break;
1423                case CHECK_PENDING_VERIFICATION: {
1424                    final int verificationId = msg.arg1;
1425                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1426
1427                    if ((state != null) && !state.timeoutExtended()) {
1428                        final InstallArgs args = state.getInstallArgs();
1429                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1430
1431                        Slog.i(TAG, "Verification timed out for " + originUri);
1432                        mPendingVerification.remove(verificationId);
1433
1434                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1435
1436                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1437                            Slog.i(TAG, "Continuing with installation of " + originUri);
1438                            state.setVerifierResponse(Binder.getCallingUid(),
1439                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1440                            broadcastPackageVerified(verificationId, originUri,
1441                                    PackageManager.VERIFICATION_ALLOW,
1442                                    state.getInstallArgs().getUser());
1443                            try {
1444                                ret = args.copyApk(mContainerService, true);
1445                            } catch (RemoteException e) {
1446                                Slog.e(TAG, "Could not contact the ContainerService");
1447                            }
1448                        } else {
1449                            broadcastPackageVerified(verificationId, originUri,
1450                                    PackageManager.VERIFICATION_REJECT,
1451                                    state.getInstallArgs().getUser());
1452                        }
1453
1454                        processPendingInstall(args, ret);
1455                        mHandler.sendEmptyMessage(MCS_UNBIND);
1456                    }
1457                    break;
1458                }
1459                case PACKAGE_VERIFIED: {
1460                    final int verificationId = msg.arg1;
1461
1462                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1463                    if (state == null) {
1464                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1465                        break;
1466                    }
1467
1468                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1469
1470                    state.setVerifierResponse(response.callerUid, response.code);
1471
1472                    if (state.isVerificationComplete()) {
1473                        mPendingVerification.remove(verificationId);
1474
1475                        final InstallArgs args = state.getInstallArgs();
1476                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1477
1478                        int ret;
1479                        if (state.isInstallAllowed()) {
1480                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1481                            broadcastPackageVerified(verificationId, originUri,
1482                                    response.code, state.getInstallArgs().getUser());
1483                            try {
1484                                ret = args.copyApk(mContainerService, true);
1485                            } catch (RemoteException e) {
1486                                Slog.e(TAG, "Could not contact the ContainerService");
1487                            }
1488                        } else {
1489                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1490                        }
1491
1492                        processPendingInstall(args, ret);
1493
1494                        mHandler.sendEmptyMessage(MCS_UNBIND);
1495                    }
1496
1497                    break;
1498                }
1499                case START_INTENT_FILTER_VERIFICATIONS: {
1500                    int userId = msg.arg1;
1501                    int verifierUid = msg.arg2;
1502                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1503
1504                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1505                    break;
1506                }
1507                case INTENT_FILTER_VERIFIED: {
1508                    final int verificationId = msg.arg1;
1509
1510                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1511                            verificationId);
1512                    if (state == null) {
1513                        Slog.w(TAG, "Invalid IntentFilter verification token "
1514                                + verificationId + " received");
1515                        break;
1516                    }
1517
1518                    final int userId = state.getUserId();
1519
1520                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1521                            "Processing IntentFilter verification with token:"
1522                            + verificationId + " and userId:" + userId);
1523
1524                    final IntentFilterVerificationResponse response =
1525                            (IntentFilterVerificationResponse) msg.obj;
1526
1527                    state.setVerifierResponse(response.callerUid, response.code);
1528
1529                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1530                            "IntentFilter verification with token:" + verificationId
1531                            + " and userId:" + userId
1532                            + " is settings verifier response with response code:"
1533                            + response.code);
1534
1535                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1536                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1537                                + response.getFailedDomainsString());
1538                    }
1539
1540                    if (state.isVerificationComplete()) {
1541                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1542                    } else {
1543                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1544                                "IntentFilter verification with token:" + verificationId
1545                                + " was not said to be complete");
1546                    }
1547
1548                    break;
1549                }
1550            }
1551        }
1552    }
1553
1554    private StorageEventListener mStorageListener = new StorageEventListener() {
1555        @Override
1556        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1557            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1558                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1559                    // TODO: ensure that private directories exist for all active users
1560                    // TODO: remove user data whose serial number doesn't match
1561                    loadPrivatePackages(vol);
1562                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1563                    unloadPrivatePackages(vol);
1564                }
1565            }
1566
1567            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1568                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1569                    updateExternalMediaStatus(true, false);
1570                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1571                    updateExternalMediaStatus(false, false);
1572                }
1573            }
1574        }
1575
1576        @Override
1577        public void onVolumeForgotten(String fsUuid) {
1578            // TODO: remove all packages hosted on this uuid
1579        }
1580    };
1581
1582    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1583        if (userId >= UserHandle.USER_OWNER) {
1584            grantRequestedRuntimePermissionsForUser(pkg, userId);
1585        } else if (userId == UserHandle.USER_ALL) {
1586            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1587                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1588            }
1589        }
1590    }
1591
1592    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1593        SettingBase sb = (SettingBase) pkg.mExtras;
1594        if (sb == null) {
1595            return;
1596        }
1597
1598        PermissionsState permissionsState = sb.getPermissionsState();
1599
1600        for (String permission : pkg.requestedPermissions) {
1601            BasePermission bp = mSettings.mPermissions.get(permission);
1602            if (bp != null && bp.isRuntime()) {
1603                permissionsState.grantRuntimePermission(bp, userId);
1604            }
1605        }
1606    }
1607
1608    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1609        Bundle extras = null;
1610        switch (res.returnCode) {
1611            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1612                extras = new Bundle();
1613                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1614                        res.origPermission);
1615                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1616                        res.origPackage);
1617                break;
1618            }
1619            case PackageManager.INSTALL_SUCCEEDED: {
1620                extras = new Bundle();
1621                extras.putBoolean(Intent.EXTRA_REPLACING,
1622                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1623                break;
1624            }
1625        }
1626        return extras;
1627    }
1628
1629    void scheduleWriteSettingsLocked() {
1630        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1631            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1632        }
1633    }
1634
1635    void scheduleWritePackageRestrictionsLocked(int userId) {
1636        if (!sUserManager.exists(userId)) return;
1637        mDirtyUsers.add(userId);
1638        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1639            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1640        }
1641    }
1642
1643    public static PackageManagerService main(Context context, Installer installer,
1644            boolean factoryTest, boolean onlyCore) {
1645        PackageManagerService m = new PackageManagerService(context, installer,
1646                factoryTest, onlyCore);
1647        ServiceManager.addService("package", m);
1648        return m;
1649    }
1650
1651    static String[] splitString(String str, char sep) {
1652        int count = 1;
1653        int i = 0;
1654        while ((i=str.indexOf(sep, i)) >= 0) {
1655            count++;
1656            i++;
1657        }
1658
1659        String[] res = new String[count];
1660        i=0;
1661        count = 0;
1662        int lastI=0;
1663        while ((i=str.indexOf(sep, i)) >= 0) {
1664            res[count] = str.substring(lastI, i);
1665            count++;
1666            i++;
1667            lastI = i;
1668        }
1669        res[count] = str.substring(lastI, str.length());
1670        return res;
1671    }
1672
1673    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1674        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1675                Context.DISPLAY_SERVICE);
1676        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1677    }
1678
1679    public PackageManagerService(Context context, Installer installer,
1680            boolean factoryTest, boolean onlyCore) {
1681        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1682                SystemClock.uptimeMillis());
1683
1684        if (mSdkVersion <= 0) {
1685            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1686        }
1687
1688        mContext = context;
1689        mFactoryTest = factoryTest;
1690        mOnlyCore = onlyCore;
1691        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1692        mMetrics = new DisplayMetrics();
1693        mSettings = new Settings(mPackages);
1694        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1695                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1696        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1697                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1698        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1699                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1700        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1701                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1702        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1703                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1704        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1705                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1706
1707        // TODO: add a property to control this?
1708        long dexOptLRUThresholdInMinutes;
1709        if (mLazyDexOpt) {
1710            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1711        } else {
1712            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1713        }
1714        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1715
1716        String separateProcesses = SystemProperties.get("debug.separate_processes");
1717        if (separateProcesses != null && separateProcesses.length() > 0) {
1718            if ("*".equals(separateProcesses)) {
1719                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1720                mSeparateProcesses = null;
1721                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1722            } else {
1723                mDefParseFlags = 0;
1724                mSeparateProcesses = separateProcesses.split(",");
1725                Slog.w(TAG, "Running with debug.separate_processes: "
1726                        + separateProcesses);
1727            }
1728        } else {
1729            mDefParseFlags = 0;
1730            mSeparateProcesses = null;
1731        }
1732
1733        mInstaller = installer;
1734        mPackageDexOptimizer = new PackageDexOptimizer(this);
1735        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1736
1737        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1738                FgThread.get().getLooper());
1739
1740        getDefaultDisplayMetrics(context, mMetrics);
1741
1742        SystemConfig systemConfig = SystemConfig.getInstance();
1743        mGlobalGids = systemConfig.getGlobalGids();
1744        mSystemPermissions = systemConfig.getSystemPermissions();
1745        mAvailableFeatures = systemConfig.getAvailableFeatures();
1746
1747        synchronized (mInstallLock) {
1748        // writer
1749        synchronized (mPackages) {
1750            mHandlerThread = new ServiceThread(TAG,
1751                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1752            mHandlerThread.start();
1753            mHandler = new PackageHandler(mHandlerThread.getLooper());
1754            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1755
1756            File dataDir = Environment.getDataDirectory();
1757            mAppDataDir = new File(dataDir, "data");
1758            mAppInstallDir = new File(dataDir, "app");
1759            mAppLib32InstallDir = new File(dataDir, "app-lib");
1760            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1761            mUserAppDataDir = new File(dataDir, "user");
1762            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1763
1764            sUserManager = new UserManagerService(context, this,
1765                    mInstallLock, mPackages);
1766
1767            // Propagate permission configuration in to package manager.
1768            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1769                    = systemConfig.getPermissions();
1770            for (int i=0; i<permConfig.size(); i++) {
1771                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1772                BasePermission bp = mSettings.mPermissions.get(perm.name);
1773                if (bp == null) {
1774                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1775                    mSettings.mPermissions.put(perm.name, bp);
1776                }
1777                if (perm.gids != null) {
1778                    bp.setGids(perm.gids, perm.perUser);
1779                }
1780            }
1781
1782            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1783            for (int i=0; i<libConfig.size(); i++) {
1784                mSharedLibraries.put(libConfig.keyAt(i),
1785                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1786            }
1787
1788            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1789
1790            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1791                    mSdkVersion, mOnlyCore);
1792
1793            String customResolverActivity = Resources.getSystem().getString(
1794                    R.string.config_customResolverActivity);
1795            if (TextUtils.isEmpty(customResolverActivity)) {
1796                customResolverActivity = null;
1797            } else {
1798                mCustomResolverComponentName = ComponentName.unflattenFromString(
1799                        customResolverActivity);
1800            }
1801
1802            long startTime = SystemClock.uptimeMillis();
1803
1804            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1805                    startTime);
1806
1807            // Set flag to monitor and not change apk file paths when
1808            // scanning install directories.
1809            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1810
1811            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1812
1813            /**
1814             * Add everything in the in the boot class path to the
1815             * list of process files because dexopt will have been run
1816             * if necessary during zygote startup.
1817             */
1818            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1819            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1820
1821            if (bootClassPath != null) {
1822                String[] bootClassPathElements = splitString(bootClassPath, ':');
1823                for (String element : bootClassPathElements) {
1824                    alreadyDexOpted.add(element);
1825                }
1826            } else {
1827                Slog.w(TAG, "No BOOTCLASSPATH found!");
1828            }
1829
1830            if (systemServerClassPath != null) {
1831                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1832                for (String element : systemServerClassPathElements) {
1833                    alreadyDexOpted.add(element);
1834                }
1835            } else {
1836                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1837            }
1838
1839            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1840            final String[] dexCodeInstructionSets =
1841                    getDexCodeInstructionSets(
1842                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1843
1844            /**
1845             * Ensure all external libraries have had dexopt run on them.
1846             */
1847            if (mSharedLibraries.size() > 0) {
1848                // NOTE: For now, we're compiling these system "shared libraries"
1849                // (and framework jars) into all available architectures. It's possible
1850                // to compile them only when we come across an app that uses them (there's
1851                // already logic for that in scanPackageLI) but that adds some complexity.
1852                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1853                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1854                        final String lib = libEntry.path;
1855                        if (lib == null) {
1856                            continue;
1857                        }
1858
1859                        try {
1860                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1861                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1862                                alreadyDexOpted.add(lib);
1863                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1864                            }
1865                        } catch (FileNotFoundException e) {
1866                            Slog.w(TAG, "Library not found: " + lib);
1867                        } catch (IOException e) {
1868                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1869                                    + e.getMessage());
1870                        }
1871                    }
1872                }
1873            }
1874
1875            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1876
1877            // Gross hack for now: we know this file doesn't contain any
1878            // code, so don't dexopt it to avoid the resulting log spew.
1879            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1880
1881            // Gross hack for now: we know this file is only part of
1882            // the boot class path for art, so don't dexopt it to
1883            // avoid the resulting log spew.
1884            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1885
1886            /**
1887             * There are a number of commands implemented in Java, which
1888             * we currently need to do the dexopt on so that they can be
1889             * run from a non-root shell.
1890             */
1891            String[] frameworkFiles = frameworkDir.list();
1892            if (frameworkFiles != null) {
1893                // TODO: We could compile these only for the most preferred ABI. We should
1894                // first double check that the dex files for these commands are not referenced
1895                // by other system apps.
1896                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1897                    for (int i=0; i<frameworkFiles.length; i++) {
1898                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1899                        String path = libPath.getPath();
1900                        // Skip the file if we already did it.
1901                        if (alreadyDexOpted.contains(path)) {
1902                            continue;
1903                        }
1904                        // Skip the file if it is not a type we want to dexopt.
1905                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1906                            continue;
1907                        }
1908                        try {
1909                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1910                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1911                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1912                            }
1913                        } catch (FileNotFoundException e) {
1914                            Slog.w(TAG, "Jar not found: " + path);
1915                        } catch (IOException e) {
1916                            Slog.w(TAG, "Exception reading jar: " + path, e);
1917                        }
1918                    }
1919                }
1920            }
1921
1922            // Collect vendor overlay packages.
1923            // (Do this before scanning any apps.)
1924            // For security and version matching reason, only consider
1925            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1926            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1927            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1928                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1929
1930            // Find base frameworks (resource packages without code).
1931            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1932                    | PackageParser.PARSE_IS_SYSTEM_DIR
1933                    | PackageParser.PARSE_IS_PRIVILEGED,
1934                    scanFlags | SCAN_NO_DEX, 0);
1935
1936            // Collected privileged system packages.
1937            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1938            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1939                    | PackageParser.PARSE_IS_SYSTEM_DIR
1940                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1941
1942            // Collect ordinary system packages.
1943            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1944            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1945                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1946
1947            // Collect all vendor packages.
1948            File vendorAppDir = new File("/vendor/app");
1949            try {
1950                vendorAppDir = vendorAppDir.getCanonicalFile();
1951            } catch (IOException e) {
1952                // failed to look up canonical path, continue with original one
1953            }
1954            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1955                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1956
1957            // Collect all OEM packages.
1958            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1959            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1960                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1961
1962            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1963            mInstaller.moveFiles();
1964
1965            // Prune any system packages that no longer exist.
1966            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1967            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1968            if (!mOnlyCore) {
1969                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1970                while (psit.hasNext()) {
1971                    PackageSetting ps = psit.next();
1972
1973                    /*
1974                     * If this is not a system app, it can't be a
1975                     * disable system app.
1976                     */
1977                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1978                        continue;
1979                    }
1980
1981                    /*
1982                     * If the package is scanned, it's not erased.
1983                     */
1984                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1985                    if (scannedPkg != null) {
1986                        /*
1987                         * If the system app is both scanned and in the
1988                         * disabled packages list, then it must have been
1989                         * added via OTA. Remove it from the currently
1990                         * scanned package so the previously user-installed
1991                         * application can be scanned.
1992                         */
1993                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1994                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1995                                    + ps.name + "; removing system app.  Last known codePath="
1996                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1997                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1998                                    + scannedPkg.mVersionCode);
1999                            removePackageLI(ps, true);
2000                            expectingBetter.put(ps.name, ps.codePath);
2001                        }
2002
2003                        continue;
2004                    }
2005
2006                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2007                        psit.remove();
2008                        logCriticalInfo(Log.WARN, "System package " + ps.name
2009                                + " no longer exists; wiping its data");
2010                        removeDataDirsLI(null, ps.name);
2011                    } else {
2012                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2013                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2014                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2015                        }
2016                    }
2017                }
2018            }
2019
2020            //look for any incomplete package installations
2021            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2022            //clean up list
2023            for(int i = 0; i < deletePkgsList.size(); i++) {
2024                //clean up here
2025                cleanupInstallFailedPackage(deletePkgsList.get(i));
2026            }
2027            //delete tmp files
2028            deleteTempPackageFiles();
2029
2030            // Remove any shared userIDs that have no associated packages
2031            mSettings.pruneSharedUsersLPw();
2032
2033            if (!mOnlyCore) {
2034                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2035                        SystemClock.uptimeMillis());
2036                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2037
2038                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2039                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2040
2041                /**
2042                 * Remove disable package settings for any updated system
2043                 * apps that were removed via an OTA. If they're not a
2044                 * previously-updated app, remove them completely.
2045                 * Otherwise, just revoke their system-level permissions.
2046                 */
2047                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2048                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2049                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2050
2051                    String msg;
2052                    if (deletedPkg == null) {
2053                        msg = "Updated system package " + deletedAppName
2054                                + " no longer exists; wiping its data";
2055                        removeDataDirsLI(null, deletedAppName);
2056                    } else {
2057                        msg = "Updated system app + " + deletedAppName
2058                                + " no longer present; removing system privileges for "
2059                                + deletedAppName;
2060
2061                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2062
2063                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2064                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2065                    }
2066                    logCriticalInfo(Log.WARN, msg);
2067                }
2068
2069                /**
2070                 * Make sure all system apps that we expected to appear on
2071                 * the userdata partition actually showed up. If they never
2072                 * appeared, crawl back and revive the system version.
2073                 */
2074                for (int i = 0; i < expectingBetter.size(); i++) {
2075                    final String packageName = expectingBetter.keyAt(i);
2076                    if (!mPackages.containsKey(packageName)) {
2077                        final File scanFile = expectingBetter.valueAt(i);
2078
2079                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2080                                + " but never showed up; reverting to system");
2081
2082                        final int reparseFlags;
2083                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2084                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2085                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2086                                    | PackageParser.PARSE_IS_PRIVILEGED;
2087                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2088                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2089                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2090                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2091                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2092                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2093                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2094                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2095                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2096                        } else {
2097                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2098                            continue;
2099                        }
2100
2101                        mSettings.enableSystemPackageLPw(packageName);
2102
2103                        try {
2104                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2105                        } catch (PackageManagerException e) {
2106                            Slog.e(TAG, "Failed to parse original system package: "
2107                                    + e.getMessage());
2108                        }
2109                    }
2110                }
2111            }
2112
2113            // Now that we know all of the shared libraries, update all clients to have
2114            // the correct library paths.
2115            updateAllSharedLibrariesLPw();
2116
2117            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2118                // NOTE: We ignore potential failures here during a system scan (like
2119                // the rest of the commands above) because there's precious little we
2120                // can do about it. A settings error is reported, though.
2121                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2122                        false /* force dexopt */, false /* defer dexopt */);
2123            }
2124
2125            // Now that we know all the packages we are keeping,
2126            // read and update their last usage times.
2127            mPackageUsage.readLP();
2128
2129            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2130                    SystemClock.uptimeMillis());
2131            Slog.i(TAG, "Time to scan packages: "
2132                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2133                    + " seconds");
2134
2135            // If the platform SDK has changed since the last time we booted,
2136            // we need to re-grant app permission to catch any new ones that
2137            // appear.  This is really a hack, and means that apps can in some
2138            // cases get permissions that the user didn't initially explicitly
2139            // allow...  it would be nice to have some better way to handle
2140            // this situation.
2141            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2142                    != mSdkVersion;
2143            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2144                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2145                    + "; regranting permissions for internal storage");
2146            mSettings.mInternalSdkPlatform = mSdkVersion;
2147
2148            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2149                    | (regrantPermissions
2150                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2151                            : 0));
2152
2153            // If this is the first boot, and it is a normal boot, then
2154            // we need to initialize the default preferred apps.
2155            if (!mRestoredSettings && !onlyCore) {
2156                mSettings.readDefaultPreferredAppsLPw(this, 0);
2157            }
2158
2159            // If this is first boot after an OTA, and a normal boot, then
2160            // we need to clear code cache directories.
2161            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2162            if (mIsUpgrade && !onlyCore) {
2163                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2164                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2165                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2166                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2167                }
2168                mSettings.mFingerprint = Build.FINGERPRINT;
2169            }
2170
2171            primeDomainVerificationsLPw();
2172            checkDefaultBrowser();
2173
2174            // All the changes are done during package scanning.
2175            mSettings.updateInternalDatabaseVersion();
2176
2177            // can downgrade to reader
2178            mSettings.writeLPr();
2179
2180            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2181                    SystemClock.uptimeMillis());
2182
2183            mRequiredVerifierPackage = getRequiredVerifierLPr();
2184
2185            mInstallerService = new PackageInstallerService(context, this);
2186
2187            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2188            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2189                    mIntentFilterVerifierComponent);
2190
2191        } // synchronized (mPackages)
2192        } // synchronized (mInstallLock)
2193
2194        // Now after opening every single application zip, make sure they
2195        // are all flushed.  Not really needed, but keeps things nice and
2196        // tidy.
2197        Runtime.getRuntime().gc();
2198    }
2199
2200    @Override
2201    public boolean isFirstBoot() {
2202        return !mRestoredSettings;
2203    }
2204
2205    @Override
2206    public boolean isOnlyCoreApps() {
2207        return mOnlyCore;
2208    }
2209
2210    @Override
2211    public boolean isUpgrade() {
2212        return mIsUpgrade;
2213    }
2214
2215    private String getRequiredVerifierLPr() {
2216        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2217        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2218                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2219
2220        String requiredVerifier = null;
2221
2222        final int N = receivers.size();
2223        for (int i = 0; i < N; i++) {
2224            final ResolveInfo info = receivers.get(i);
2225
2226            if (info.activityInfo == null) {
2227                continue;
2228            }
2229
2230            final String packageName = info.activityInfo.packageName;
2231
2232            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2233                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2234                continue;
2235            }
2236
2237            if (requiredVerifier != null) {
2238                throw new RuntimeException("There can be only one required verifier");
2239            }
2240
2241            requiredVerifier = packageName;
2242        }
2243
2244        return requiredVerifier;
2245    }
2246
2247    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2248        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2249        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2250                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2251
2252        ComponentName verifierComponentName = null;
2253
2254        int priority = -1000;
2255        final int N = receivers.size();
2256        for (int i = 0; i < N; i++) {
2257            final ResolveInfo info = receivers.get(i);
2258
2259            if (info.activityInfo == null) {
2260                continue;
2261            }
2262
2263            final String packageName = info.activityInfo.packageName;
2264
2265            final PackageSetting ps = mSettings.mPackages.get(packageName);
2266            if (ps == null) {
2267                continue;
2268            }
2269
2270            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2271                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2272                continue;
2273            }
2274
2275            // Select the IntentFilterVerifier with the highest priority
2276            if (priority < info.priority) {
2277                priority = info.priority;
2278                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2279                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2280                        + verifierComponentName + " with priority: " + info.priority);
2281            }
2282        }
2283
2284        return verifierComponentName;
2285    }
2286
2287    private void primeDomainVerificationsLPw() {
2288        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2289        boolean updated = false;
2290        ArraySet<String> allHostsSet = new ArraySet<>();
2291        for (PackageParser.Package pkg : mPackages.values()) {
2292            final String packageName = pkg.packageName;
2293            if (!hasDomainURLs(pkg)) {
2294                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2295                            "package with no domain URLs: " + packageName);
2296                continue;
2297            }
2298            if (!pkg.isSystemApp()) {
2299                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2300                        "No priming domain verifications for a non system package : " +
2301                                packageName);
2302                continue;
2303            }
2304            for (PackageParser.Activity a : pkg.activities) {
2305                for (ActivityIntentInfo filter : a.intents) {
2306                    if (hasValidDomains(filter)) {
2307                        allHostsSet.addAll(filter.getHostsList());
2308                    }
2309                }
2310            }
2311            if (allHostsSet.size() == 0) {
2312                allHostsSet.add("*");
2313            }
2314            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2315            IntentFilterVerificationInfo ivi =
2316                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2317            if (ivi != null) {
2318                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2319                        "Priming domain verifications for package: " + packageName +
2320                        " with hosts:" + ivi.getDomainsString());
2321                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2322                updated = true;
2323            }
2324            else {
2325                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2326                        "No priming domain verifications for package: " + packageName);
2327            }
2328            allHostsSet.clear();
2329        }
2330        if (updated) {
2331            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2332                    "Will need to write primed domain verifications");
2333        }
2334        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2335    }
2336
2337    private void checkDefaultBrowser() {
2338        final int myUserId = UserHandle.myUserId();
2339        final String packageName = getDefaultBrowserPackageName(myUserId);
2340        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2341        if (info == null) {
2342            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2343                    packageName);
2344            setDefaultBrowserPackageName(null, myUserId);
2345        }
2346    }
2347
2348    @Override
2349    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2350            throws RemoteException {
2351        try {
2352            return super.onTransact(code, data, reply, flags);
2353        } catch (RuntimeException e) {
2354            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2355                Slog.wtf(TAG, "Package Manager Crash", e);
2356            }
2357            throw e;
2358        }
2359    }
2360
2361    void cleanupInstallFailedPackage(PackageSetting ps) {
2362        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2363
2364        removeDataDirsLI(ps.volumeUuid, ps.name);
2365        if (ps.codePath != null) {
2366            if (ps.codePath.isDirectory()) {
2367                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2368            } else {
2369                ps.codePath.delete();
2370            }
2371        }
2372        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2373            if (ps.resourcePath.isDirectory()) {
2374                FileUtils.deleteContents(ps.resourcePath);
2375            }
2376            ps.resourcePath.delete();
2377        }
2378        mSettings.removePackageLPw(ps.name);
2379    }
2380
2381    static int[] appendInts(int[] cur, int[] add) {
2382        if (add == null) return cur;
2383        if (cur == null) return add;
2384        final int N = add.length;
2385        for (int i=0; i<N; i++) {
2386            cur = appendInt(cur, add[i]);
2387        }
2388        return cur;
2389    }
2390
2391    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2392        if (!sUserManager.exists(userId)) return null;
2393        final PackageSetting ps = (PackageSetting) p.mExtras;
2394        if (ps == null) {
2395            return null;
2396        }
2397
2398        final PermissionsState permissionsState = ps.getPermissionsState();
2399
2400        final int[] gids = permissionsState.computeGids(userId);
2401        final Set<String> permissions = permissionsState.getPermissions(userId);
2402        final PackageUserState state = ps.readUserState(userId);
2403
2404        return PackageParser.generatePackageInfo(p, gids, flags,
2405                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2406    }
2407
2408    @Override
2409    public boolean isPackageFrozen(String packageName) {
2410        synchronized (mPackages) {
2411            final PackageSetting ps = mSettings.mPackages.get(packageName);
2412            if (ps != null) {
2413                return ps.frozen;
2414            }
2415        }
2416        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2417        return true;
2418    }
2419
2420    @Override
2421    public boolean isPackageAvailable(String packageName, int userId) {
2422        if (!sUserManager.exists(userId)) return false;
2423        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2424        synchronized (mPackages) {
2425            PackageParser.Package p = mPackages.get(packageName);
2426            if (p != null) {
2427                final PackageSetting ps = (PackageSetting) p.mExtras;
2428                if (ps != null) {
2429                    final PackageUserState state = ps.readUserState(userId);
2430                    if (state != null) {
2431                        return PackageParser.isAvailable(state);
2432                    }
2433                }
2434            }
2435        }
2436        return false;
2437    }
2438
2439    @Override
2440    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2441        if (!sUserManager.exists(userId)) return null;
2442        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2443        // reader
2444        synchronized (mPackages) {
2445            PackageParser.Package p = mPackages.get(packageName);
2446            if (DEBUG_PACKAGE_INFO)
2447                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2448            if (p != null) {
2449                return generatePackageInfo(p, flags, userId);
2450            }
2451            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2452                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2453            }
2454        }
2455        return null;
2456    }
2457
2458    @Override
2459    public String[] currentToCanonicalPackageNames(String[] names) {
2460        String[] out = new String[names.length];
2461        // reader
2462        synchronized (mPackages) {
2463            for (int i=names.length-1; i>=0; i--) {
2464                PackageSetting ps = mSettings.mPackages.get(names[i]);
2465                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2466            }
2467        }
2468        return out;
2469    }
2470
2471    @Override
2472    public String[] canonicalToCurrentPackageNames(String[] names) {
2473        String[] out = new String[names.length];
2474        // reader
2475        synchronized (mPackages) {
2476            for (int i=names.length-1; i>=0; i--) {
2477                String cur = mSettings.mRenamedPackages.get(names[i]);
2478                out[i] = cur != null ? cur : names[i];
2479            }
2480        }
2481        return out;
2482    }
2483
2484    @Override
2485    public int getPackageUid(String packageName, int userId) {
2486        if (!sUserManager.exists(userId)) return -1;
2487        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2488
2489        // reader
2490        synchronized (mPackages) {
2491            PackageParser.Package p = mPackages.get(packageName);
2492            if(p != null) {
2493                return UserHandle.getUid(userId, p.applicationInfo.uid);
2494            }
2495            PackageSetting ps = mSettings.mPackages.get(packageName);
2496            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2497                return -1;
2498            }
2499            p = ps.pkg;
2500            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2501        }
2502    }
2503
2504    @Override
2505    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2506        if (!sUserManager.exists(userId)) {
2507            return null;
2508        }
2509
2510        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2511                "getPackageGids");
2512
2513        // reader
2514        synchronized (mPackages) {
2515            PackageParser.Package p = mPackages.get(packageName);
2516            if (DEBUG_PACKAGE_INFO) {
2517                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2518            }
2519            if (p != null) {
2520                PackageSetting ps = (PackageSetting) p.mExtras;
2521                return ps.getPermissionsState().computeGids(userId);
2522            }
2523        }
2524
2525        return null;
2526    }
2527
2528    static PermissionInfo generatePermissionInfo(
2529            BasePermission bp, int flags) {
2530        if (bp.perm != null) {
2531            return PackageParser.generatePermissionInfo(bp.perm, flags);
2532        }
2533        PermissionInfo pi = new PermissionInfo();
2534        pi.name = bp.name;
2535        pi.packageName = bp.sourcePackage;
2536        pi.nonLocalizedLabel = bp.name;
2537        pi.protectionLevel = bp.protectionLevel;
2538        return pi;
2539    }
2540
2541    @Override
2542    public PermissionInfo getPermissionInfo(String name, int flags) {
2543        // reader
2544        synchronized (mPackages) {
2545            final BasePermission p = mSettings.mPermissions.get(name);
2546            if (p != null) {
2547                return generatePermissionInfo(p, flags);
2548            }
2549            return null;
2550        }
2551    }
2552
2553    @Override
2554    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2555        // reader
2556        synchronized (mPackages) {
2557            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2558            for (BasePermission p : mSettings.mPermissions.values()) {
2559                if (group == null) {
2560                    if (p.perm == null || p.perm.info.group == null) {
2561                        out.add(generatePermissionInfo(p, flags));
2562                    }
2563                } else {
2564                    if (p.perm != null && group.equals(p.perm.info.group)) {
2565                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2566                    }
2567                }
2568            }
2569
2570            if (out.size() > 0) {
2571                return out;
2572            }
2573            return mPermissionGroups.containsKey(group) ? out : null;
2574        }
2575    }
2576
2577    @Override
2578    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2579        // reader
2580        synchronized (mPackages) {
2581            return PackageParser.generatePermissionGroupInfo(
2582                    mPermissionGroups.get(name), flags);
2583        }
2584    }
2585
2586    @Override
2587    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2588        // reader
2589        synchronized (mPackages) {
2590            final int N = mPermissionGroups.size();
2591            ArrayList<PermissionGroupInfo> out
2592                    = new ArrayList<PermissionGroupInfo>(N);
2593            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2594                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2595            }
2596            return out;
2597        }
2598    }
2599
2600    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2601            int userId) {
2602        if (!sUserManager.exists(userId)) return null;
2603        PackageSetting ps = mSettings.mPackages.get(packageName);
2604        if (ps != null) {
2605            if (ps.pkg == null) {
2606                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2607                        flags, userId);
2608                if (pInfo != null) {
2609                    return pInfo.applicationInfo;
2610                }
2611                return null;
2612            }
2613            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2614                    ps.readUserState(userId), userId);
2615        }
2616        return null;
2617    }
2618
2619    private PackageInfo generatePackageInfoFromSettingsLPw(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            PackageParser.Package pkg = ps.pkg;
2625            if (pkg == null) {
2626                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2627                    return null;
2628                }
2629                // Only data remains, so we aren't worried about code paths
2630                pkg = new PackageParser.Package(packageName);
2631                pkg.applicationInfo.packageName = packageName;
2632                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2633                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2634                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2635                        packageName, userId).getAbsolutePath();
2636                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2637                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2638            }
2639            return generatePackageInfo(pkg, flags, userId);
2640        }
2641        return null;
2642    }
2643
2644    @Override
2645    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2646        if (!sUserManager.exists(userId)) return null;
2647        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2648        // writer
2649        synchronized (mPackages) {
2650            PackageParser.Package p = mPackages.get(packageName);
2651            if (DEBUG_PACKAGE_INFO) Log.v(
2652                    TAG, "getApplicationInfo " + packageName
2653                    + ": " + p);
2654            if (p != null) {
2655                PackageSetting ps = mSettings.mPackages.get(packageName);
2656                if (ps == null) return null;
2657                // Note: isEnabledLP() does not apply here - always return info
2658                return PackageParser.generateApplicationInfo(
2659                        p, flags, ps.readUserState(userId), userId);
2660            }
2661            if ("android".equals(packageName)||"system".equals(packageName)) {
2662                return mAndroidApplication;
2663            }
2664            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2665                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2666            }
2667        }
2668        return null;
2669    }
2670
2671    @Override
2672    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2673            final IPackageDataObserver observer) {
2674        mContext.enforceCallingOrSelfPermission(
2675                android.Manifest.permission.CLEAR_APP_CACHE, null);
2676        // Queue up an async operation since clearing cache may take a little while.
2677        mHandler.post(new Runnable() {
2678            public void run() {
2679                mHandler.removeCallbacks(this);
2680                int retCode = -1;
2681                synchronized (mInstallLock) {
2682                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2683                    if (retCode < 0) {
2684                        Slog.w(TAG, "Couldn't clear application caches");
2685                    }
2686                }
2687                if (observer != null) {
2688                    try {
2689                        observer.onRemoveCompleted(null, (retCode >= 0));
2690                    } catch (RemoteException e) {
2691                        Slog.w(TAG, "RemoveException when invoking call back");
2692                    }
2693                }
2694            }
2695        });
2696    }
2697
2698    @Override
2699    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2700            final IntentSender pi) {
2701        mContext.enforceCallingOrSelfPermission(
2702                android.Manifest.permission.CLEAR_APP_CACHE, null);
2703        // Queue up an async operation since clearing cache may take a little while.
2704        mHandler.post(new Runnable() {
2705            public void run() {
2706                mHandler.removeCallbacks(this);
2707                int retCode = -1;
2708                synchronized (mInstallLock) {
2709                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2710                    if (retCode < 0) {
2711                        Slog.w(TAG, "Couldn't clear application caches");
2712                    }
2713                }
2714                if(pi != null) {
2715                    try {
2716                        // Callback via pending intent
2717                        int code = (retCode >= 0) ? 1 : 0;
2718                        pi.sendIntent(null, code, null,
2719                                null, null);
2720                    } catch (SendIntentException e1) {
2721                        Slog.i(TAG, "Failed to send pending intent");
2722                    }
2723                }
2724            }
2725        });
2726    }
2727
2728    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2729        synchronized (mInstallLock) {
2730            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2731                throw new IOException("Failed to free enough space");
2732            }
2733        }
2734    }
2735
2736    @Override
2737    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2738        if (!sUserManager.exists(userId)) return null;
2739        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2740        synchronized (mPackages) {
2741            PackageParser.Activity a = mActivities.mActivities.get(component);
2742
2743            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2744            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2745                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2746                if (ps == null) return null;
2747                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2748                        userId);
2749            }
2750            if (mResolveComponentName.equals(component)) {
2751                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2752                        new PackageUserState(), userId);
2753            }
2754        }
2755        return null;
2756    }
2757
2758    @Override
2759    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2760            String resolvedType) {
2761        synchronized (mPackages) {
2762            PackageParser.Activity a = mActivities.mActivities.get(component);
2763            if (a == null) {
2764                return false;
2765            }
2766            for (int i=0; i<a.intents.size(); i++) {
2767                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2768                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2769                    return true;
2770                }
2771            }
2772            return false;
2773        }
2774    }
2775
2776    @Override
2777    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2778        if (!sUserManager.exists(userId)) return null;
2779        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2780        synchronized (mPackages) {
2781            PackageParser.Activity a = mReceivers.mActivities.get(component);
2782            if (DEBUG_PACKAGE_INFO) Log.v(
2783                TAG, "getReceiverInfo " + component + ": " + a);
2784            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2785                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2786                if (ps == null) return null;
2787                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2788                        userId);
2789            }
2790        }
2791        return null;
2792    }
2793
2794    @Override
2795    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2796        if (!sUserManager.exists(userId)) return null;
2797        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2798        synchronized (mPackages) {
2799            PackageParser.Service s = mServices.mServices.get(component);
2800            if (DEBUG_PACKAGE_INFO) Log.v(
2801                TAG, "getServiceInfo " + component + ": " + s);
2802            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2803                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2804                if (ps == null) return null;
2805                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2806                        userId);
2807            }
2808        }
2809        return null;
2810    }
2811
2812    @Override
2813    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2814        if (!sUserManager.exists(userId)) return null;
2815        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2816        synchronized (mPackages) {
2817            PackageParser.Provider p = mProviders.mProviders.get(component);
2818            if (DEBUG_PACKAGE_INFO) Log.v(
2819                TAG, "getProviderInfo " + component + ": " + p);
2820            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2821                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2822                if (ps == null) return null;
2823                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2824                        userId);
2825            }
2826        }
2827        return null;
2828    }
2829
2830    @Override
2831    public String[] getSystemSharedLibraryNames() {
2832        Set<String> libSet;
2833        synchronized (mPackages) {
2834            libSet = mSharedLibraries.keySet();
2835            int size = libSet.size();
2836            if (size > 0) {
2837                String[] libs = new String[size];
2838                libSet.toArray(libs);
2839                return libs;
2840            }
2841        }
2842        return null;
2843    }
2844
2845    /**
2846     * @hide
2847     */
2848    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2849        synchronized (mPackages) {
2850            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2851            if (lib != null && lib.apk != null) {
2852                return mPackages.get(lib.apk);
2853            }
2854        }
2855        return null;
2856    }
2857
2858    @Override
2859    public FeatureInfo[] getSystemAvailableFeatures() {
2860        Collection<FeatureInfo> featSet;
2861        synchronized (mPackages) {
2862            featSet = mAvailableFeatures.values();
2863            int size = featSet.size();
2864            if (size > 0) {
2865                FeatureInfo[] features = new FeatureInfo[size+1];
2866                featSet.toArray(features);
2867                FeatureInfo fi = new FeatureInfo();
2868                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2869                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2870                features[size] = fi;
2871                return features;
2872            }
2873        }
2874        return null;
2875    }
2876
2877    @Override
2878    public boolean hasSystemFeature(String name) {
2879        synchronized (mPackages) {
2880            return mAvailableFeatures.containsKey(name);
2881        }
2882    }
2883
2884    private void checkValidCaller(int uid, int userId) {
2885        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2886            return;
2887
2888        throw new SecurityException("Caller uid=" + uid
2889                + " is not privileged to communicate with user=" + userId);
2890    }
2891
2892    @Override
2893    public int checkPermission(String permName, String pkgName, int userId) {
2894        if (!sUserManager.exists(userId)) {
2895            return PackageManager.PERMISSION_DENIED;
2896        }
2897
2898        synchronized (mPackages) {
2899            final PackageParser.Package p = mPackages.get(pkgName);
2900            if (p != null && p.mExtras != null) {
2901                final PackageSetting ps = (PackageSetting) p.mExtras;
2902                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2903                    return PackageManager.PERMISSION_GRANTED;
2904                }
2905            }
2906        }
2907
2908        return PackageManager.PERMISSION_DENIED;
2909    }
2910
2911    @Override
2912    public int checkUidPermission(String permName, int uid) {
2913        final int userId = UserHandle.getUserId(uid);
2914
2915        if (!sUserManager.exists(userId)) {
2916            return PackageManager.PERMISSION_DENIED;
2917        }
2918
2919        synchronized (mPackages) {
2920            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2921            if (obj != null) {
2922                final SettingBase ps = (SettingBase) obj;
2923                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2924                    return PackageManager.PERMISSION_GRANTED;
2925                }
2926            } else {
2927                ArraySet<String> perms = mSystemPermissions.get(uid);
2928                if (perms != null && perms.contains(permName)) {
2929                    return PackageManager.PERMISSION_GRANTED;
2930                }
2931            }
2932        }
2933
2934        return PackageManager.PERMISSION_DENIED;
2935    }
2936
2937    /**
2938     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2939     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2940     * @param checkShell TODO(yamasani):
2941     * @param message the message to log on security exception
2942     */
2943    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2944            boolean checkShell, String message) {
2945        if (userId < 0) {
2946            throw new IllegalArgumentException("Invalid userId " + userId);
2947        }
2948        if (checkShell) {
2949            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2950        }
2951        if (userId == UserHandle.getUserId(callingUid)) return;
2952        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2953            if (requireFullPermission) {
2954                mContext.enforceCallingOrSelfPermission(
2955                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2956            } else {
2957                try {
2958                    mContext.enforceCallingOrSelfPermission(
2959                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2960                } catch (SecurityException se) {
2961                    mContext.enforceCallingOrSelfPermission(
2962                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2963                }
2964            }
2965        }
2966    }
2967
2968    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2969        if (callingUid == Process.SHELL_UID) {
2970            if (userHandle >= 0
2971                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2972                throw new SecurityException("Shell does not have permission to access user "
2973                        + userHandle);
2974            } else if (userHandle < 0) {
2975                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2976                        + Debug.getCallers(3));
2977            }
2978        }
2979    }
2980
2981    private BasePermission findPermissionTreeLP(String permName) {
2982        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2983            if (permName.startsWith(bp.name) &&
2984                    permName.length() > bp.name.length() &&
2985                    permName.charAt(bp.name.length()) == '.') {
2986                return bp;
2987            }
2988        }
2989        return null;
2990    }
2991
2992    private BasePermission checkPermissionTreeLP(String permName) {
2993        if (permName != null) {
2994            BasePermission bp = findPermissionTreeLP(permName);
2995            if (bp != null) {
2996                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2997                    return bp;
2998                }
2999                throw new SecurityException("Calling uid "
3000                        + Binder.getCallingUid()
3001                        + " is not allowed to add to permission tree "
3002                        + bp.name + " owned by uid " + bp.uid);
3003            }
3004        }
3005        throw new SecurityException("No permission tree found for " + permName);
3006    }
3007
3008    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3009        if (s1 == null) {
3010            return s2 == null;
3011        }
3012        if (s2 == null) {
3013            return false;
3014        }
3015        if (s1.getClass() != s2.getClass()) {
3016            return false;
3017        }
3018        return s1.equals(s2);
3019    }
3020
3021    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3022        if (pi1.icon != pi2.icon) return false;
3023        if (pi1.logo != pi2.logo) return false;
3024        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3025        if (!compareStrings(pi1.name, pi2.name)) return false;
3026        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3027        // We'll take care of setting this one.
3028        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3029        // These are not currently stored in settings.
3030        //if (!compareStrings(pi1.group, pi2.group)) return false;
3031        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3032        //if (pi1.labelRes != pi2.labelRes) return false;
3033        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3034        return true;
3035    }
3036
3037    int permissionInfoFootprint(PermissionInfo info) {
3038        int size = info.name.length();
3039        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3040        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3041        return size;
3042    }
3043
3044    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3045        int size = 0;
3046        for (BasePermission perm : mSettings.mPermissions.values()) {
3047            if (perm.uid == tree.uid) {
3048                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3049            }
3050        }
3051        return size;
3052    }
3053
3054    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3055        // We calculate the max size of permissions defined by this uid and throw
3056        // if that plus the size of 'info' would exceed our stated maximum.
3057        if (tree.uid != Process.SYSTEM_UID) {
3058            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3059            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3060                throw new SecurityException("Permission tree size cap exceeded");
3061            }
3062        }
3063    }
3064
3065    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3066        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3067            throw new SecurityException("Label must be specified in permission");
3068        }
3069        BasePermission tree = checkPermissionTreeLP(info.name);
3070        BasePermission bp = mSettings.mPermissions.get(info.name);
3071        boolean added = bp == null;
3072        boolean changed = true;
3073        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3074        if (added) {
3075            enforcePermissionCapLocked(info, tree);
3076            bp = new BasePermission(info.name, tree.sourcePackage,
3077                    BasePermission.TYPE_DYNAMIC);
3078        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3079            throw new SecurityException(
3080                    "Not allowed to modify non-dynamic permission "
3081                    + info.name);
3082        } else {
3083            if (bp.protectionLevel == fixedLevel
3084                    && bp.perm.owner.equals(tree.perm.owner)
3085                    && bp.uid == tree.uid
3086                    && comparePermissionInfos(bp.perm.info, info)) {
3087                changed = false;
3088            }
3089        }
3090        bp.protectionLevel = fixedLevel;
3091        info = new PermissionInfo(info);
3092        info.protectionLevel = fixedLevel;
3093        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3094        bp.perm.info.packageName = tree.perm.info.packageName;
3095        bp.uid = tree.uid;
3096        if (added) {
3097            mSettings.mPermissions.put(info.name, bp);
3098        }
3099        if (changed) {
3100            if (!async) {
3101                mSettings.writeLPr();
3102            } else {
3103                scheduleWriteSettingsLocked();
3104            }
3105        }
3106        return added;
3107    }
3108
3109    @Override
3110    public boolean addPermission(PermissionInfo info) {
3111        synchronized (mPackages) {
3112            return addPermissionLocked(info, false);
3113        }
3114    }
3115
3116    @Override
3117    public boolean addPermissionAsync(PermissionInfo info) {
3118        synchronized (mPackages) {
3119            return addPermissionLocked(info, true);
3120        }
3121    }
3122
3123    @Override
3124    public void removePermission(String name) {
3125        synchronized (mPackages) {
3126            checkPermissionTreeLP(name);
3127            BasePermission bp = mSettings.mPermissions.get(name);
3128            if (bp != null) {
3129                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3130                    throw new SecurityException(
3131                            "Not allowed to modify non-dynamic permission "
3132                            + name);
3133                }
3134                mSettings.mPermissions.remove(name);
3135                mSettings.writeLPr();
3136            }
3137        }
3138    }
3139
3140    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3141            BasePermission bp) {
3142        int index = pkg.requestedPermissions.indexOf(bp.name);
3143        if (index == -1) {
3144            throw new SecurityException("Package " + pkg.packageName
3145                    + " has not requested permission " + bp.name);
3146        }
3147        if (!bp.isRuntime()) {
3148            throw new SecurityException("Permission " + bp.name
3149                    + " is not a changeable permission type");
3150        }
3151    }
3152
3153    @Override
3154    public void grantRuntimePermission(String packageName, String name, int userId) {
3155        if (!sUserManager.exists(userId)) {
3156            Log.e(TAG, "No such user:" + userId);
3157            return;
3158        }
3159
3160        mContext.enforceCallingOrSelfPermission(
3161                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3162                "grantRuntimePermission");
3163
3164        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3165                "grantRuntimePermission");
3166
3167        boolean gidsChanged = false;
3168        final SettingBase sb;
3169
3170        synchronized (mPackages) {
3171            final PackageParser.Package pkg = mPackages.get(packageName);
3172            if (pkg == null) {
3173                throw new IllegalArgumentException("Unknown package: " + packageName);
3174            }
3175
3176            final BasePermission bp = mSettings.mPermissions.get(name);
3177            if (bp == null) {
3178                throw new IllegalArgumentException("Unknown permission: " + name);
3179            }
3180
3181            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3182
3183            sb = (SettingBase) pkg.mExtras;
3184            if (sb == null) {
3185                throw new IllegalArgumentException("Unknown package: " + packageName);
3186            }
3187
3188            final PermissionsState permissionsState = sb.getPermissionsState();
3189
3190            final int flags = permissionsState.getPermissionFlags(name, userId);
3191            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3192                throw new SecurityException("Cannot grant system fixed permission: "
3193                        + name + " for package: " + packageName);
3194            }
3195
3196            final int result = permissionsState.grantRuntimePermission(bp, userId);
3197            switch (result) {
3198                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3199                    return;
3200                }
3201
3202                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3203                    gidsChanged = true;
3204                } break;
3205            }
3206
3207            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3208
3209            // Not critical if that is lost - app has to request again.
3210            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3211        }
3212
3213        if (gidsChanged) {
3214            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3215        }
3216    }
3217
3218    @Override
3219    public void revokeRuntimePermission(String packageName, String name, int userId) {
3220        if (!sUserManager.exists(userId)) {
3221            Log.e(TAG, "No such user:" + userId);
3222            return;
3223        }
3224
3225        mContext.enforceCallingOrSelfPermission(
3226                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3227                "revokeRuntimePermission");
3228
3229        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3230                "revokeRuntimePermission");
3231
3232        final SettingBase sb;
3233
3234        synchronized (mPackages) {
3235            final PackageParser.Package pkg = mPackages.get(packageName);
3236            if (pkg == null) {
3237                throw new IllegalArgumentException("Unknown package: " + packageName);
3238            }
3239
3240            final BasePermission bp = mSettings.mPermissions.get(name);
3241            if (bp == null) {
3242                throw new IllegalArgumentException("Unknown permission: " + name);
3243            }
3244
3245            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3246
3247            sb = (SettingBase) pkg.mExtras;
3248            if (sb == null) {
3249                throw new IllegalArgumentException("Unknown package: " + packageName);
3250            }
3251
3252            final PermissionsState permissionsState = sb.getPermissionsState();
3253
3254            final int flags = permissionsState.getPermissionFlags(name, userId);
3255            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3256                throw new SecurityException("Cannot revoke system fixed permission: "
3257                        + name + " for package: " + packageName);
3258            }
3259
3260            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3261                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3262                return;
3263            }
3264
3265            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3266
3267            // Critical, after this call app should never have the permission.
3268            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3269        }
3270
3271        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3272    }
3273
3274    @Override
3275    public int getPermissionFlags(String name, String packageName, int userId) {
3276        if (!sUserManager.exists(userId)) {
3277            return 0;
3278        }
3279
3280        mContext.enforceCallingOrSelfPermission(
3281                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3282                "getPermissionFlags");
3283
3284        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3285                "getPermissionFlags");
3286
3287        synchronized (mPackages) {
3288            final PackageParser.Package pkg = mPackages.get(packageName);
3289            if (pkg == null) {
3290                throw new IllegalArgumentException("Unknown package: " + packageName);
3291            }
3292
3293            final BasePermission bp = mSettings.mPermissions.get(name);
3294            if (bp == null) {
3295                throw new IllegalArgumentException("Unknown permission: " + name);
3296            }
3297
3298            SettingBase sb = (SettingBase) pkg.mExtras;
3299            if (sb == null) {
3300                throw new IllegalArgumentException("Unknown package: " + packageName);
3301            }
3302
3303            PermissionsState permissionsState = sb.getPermissionsState();
3304            return permissionsState.getPermissionFlags(name, userId);
3305        }
3306    }
3307
3308    @Override
3309    public void updatePermissionFlags(String name, String packageName, int flagMask,
3310            int flagValues, int userId) {
3311        if (!sUserManager.exists(userId)) {
3312            return;
3313        }
3314
3315        mContext.enforceCallingOrSelfPermission(
3316                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3317                "updatePermissionFlags");
3318
3319        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3320                "updatePermissionFlags");
3321
3322        // Only the system can change policy flags.
3323        if (getCallingUid() != Process.SYSTEM_UID) {
3324            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3325            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3326        }
3327
3328        // Only the package manager can change system flags.
3329        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3330        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3331
3332        synchronized (mPackages) {
3333            final PackageParser.Package pkg = mPackages.get(packageName);
3334            if (pkg == null) {
3335                throw new IllegalArgumentException("Unknown package: " + packageName);
3336            }
3337
3338            final BasePermission bp = mSettings.mPermissions.get(name);
3339            if (bp == null) {
3340                throw new IllegalArgumentException("Unknown permission: " + name);
3341            }
3342
3343            SettingBase sb = (SettingBase) pkg.mExtras;
3344            if (sb == null) {
3345                throw new IllegalArgumentException("Unknown package: " + packageName);
3346            }
3347
3348            PermissionsState permissionsState = sb.getPermissionsState();
3349
3350            // Only the package manager can change flags for system component permissions.
3351            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3352            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3353                return;
3354            }
3355
3356            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3357                // Install and runtime permissions are stored in different places,
3358                // so figure out what permission changed and persist the change.
3359                if (permissionsState.getInstallPermissionState(name) != null) {
3360                    scheduleWriteSettingsLocked();
3361                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3362                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3363                }
3364            }
3365        }
3366    }
3367
3368    @Override
3369    public boolean shouldShowRequestPermissionRationale(String permissionName,
3370            String packageName, int userId) {
3371        if (UserHandle.getCallingUserId() != userId) {
3372            mContext.enforceCallingPermission(
3373                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3374                    "canShowRequestPermissionRationale for user " + userId);
3375        }
3376
3377        final int uid = getPackageUid(packageName, userId);
3378        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3379            return false;
3380        }
3381
3382        if (checkPermission(permissionName, packageName, userId)
3383                == PackageManager.PERMISSION_GRANTED) {
3384            return false;
3385        }
3386
3387        final int flags;
3388
3389        final long identity = Binder.clearCallingIdentity();
3390        try {
3391            flags = getPermissionFlags(permissionName,
3392                    packageName, userId);
3393        } finally {
3394            Binder.restoreCallingIdentity(identity);
3395        }
3396
3397        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3398                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3399                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3400
3401        if ((flags & fixedFlags) != 0) {
3402            return false;
3403        }
3404
3405        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3406    }
3407
3408    @Override
3409    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3410        mContext.enforceCallingOrSelfPermission(
3411                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3412                "addOnPermissionsChangeListener");
3413
3414        synchronized (mPackages) {
3415            mOnPermissionChangeListeners.addListenerLocked(listener);
3416        }
3417    }
3418
3419    @Override
3420    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3421        synchronized (mPackages) {
3422            mOnPermissionChangeListeners.removeListenerLocked(listener);
3423        }
3424    }
3425
3426    @Override
3427    public boolean isProtectedBroadcast(String actionName) {
3428        synchronized (mPackages) {
3429            return mProtectedBroadcasts.contains(actionName);
3430        }
3431    }
3432
3433    @Override
3434    public int checkSignatures(String pkg1, String pkg2) {
3435        synchronized (mPackages) {
3436            final PackageParser.Package p1 = mPackages.get(pkg1);
3437            final PackageParser.Package p2 = mPackages.get(pkg2);
3438            if (p1 == null || p1.mExtras == null
3439                    || p2 == null || p2.mExtras == null) {
3440                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3441            }
3442            return compareSignatures(p1.mSignatures, p2.mSignatures);
3443        }
3444    }
3445
3446    @Override
3447    public int checkUidSignatures(int uid1, int uid2) {
3448        // Map to base uids.
3449        uid1 = UserHandle.getAppId(uid1);
3450        uid2 = UserHandle.getAppId(uid2);
3451        // reader
3452        synchronized (mPackages) {
3453            Signature[] s1;
3454            Signature[] s2;
3455            Object obj = mSettings.getUserIdLPr(uid1);
3456            if (obj != null) {
3457                if (obj instanceof SharedUserSetting) {
3458                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3459                } else if (obj instanceof PackageSetting) {
3460                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3461                } else {
3462                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3463                }
3464            } else {
3465                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3466            }
3467            obj = mSettings.getUserIdLPr(uid2);
3468            if (obj != null) {
3469                if (obj instanceof SharedUserSetting) {
3470                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3471                } else if (obj instanceof PackageSetting) {
3472                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3473                } else {
3474                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3475                }
3476            } else {
3477                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3478            }
3479            return compareSignatures(s1, s2);
3480        }
3481    }
3482
3483    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3484        final long identity = Binder.clearCallingIdentity();
3485        try {
3486            if (sb instanceof SharedUserSetting) {
3487                SharedUserSetting sus = (SharedUserSetting) sb;
3488                final int packageCount = sus.packages.size();
3489                for (int i = 0; i < packageCount; i++) {
3490                    PackageSetting susPs = sus.packages.valueAt(i);
3491                    if (userId == UserHandle.USER_ALL) {
3492                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3493                    } else {
3494                        final int uid = UserHandle.getUid(userId, susPs.appId);
3495                        killUid(uid, reason);
3496                    }
3497                }
3498            } else if (sb instanceof PackageSetting) {
3499                PackageSetting ps = (PackageSetting) sb;
3500                if (userId == UserHandle.USER_ALL) {
3501                    killApplication(ps.pkg.packageName, ps.appId, reason);
3502                } else {
3503                    final int uid = UserHandle.getUid(userId, ps.appId);
3504                    killUid(uid, reason);
3505                }
3506            }
3507        } finally {
3508            Binder.restoreCallingIdentity(identity);
3509        }
3510    }
3511
3512    private static void killUid(int uid, String reason) {
3513        IActivityManager am = ActivityManagerNative.getDefault();
3514        if (am != null) {
3515            try {
3516                am.killUid(uid, reason);
3517            } catch (RemoteException e) {
3518                /* ignore - same process */
3519            }
3520        }
3521    }
3522
3523    /**
3524     * Compares two sets of signatures. Returns:
3525     * <br />
3526     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3527     * <br />
3528     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3529     * <br />
3530     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3531     * <br />
3532     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3533     * <br />
3534     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3535     */
3536    static int compareSignatures(Signature[] s1, Signature[] s2) {
3537        if (s1 == null) {
3538            return s2 == null
3539                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3540                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3541        }
3542
3543        if (s2 == null) {
3544            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3545        }
3546
3547        if (s1.length != s2.length) {
3548            return PackageManager.SIGNATURE_NO_MATCH;
3549        }
3550
3551        // Since both signature sets are of size 1, we can compare without HashSets.
3552        if (s1.length == 1) {
3553            return s1[0].equals(s2[0]) ?
3554                    PackageManager.SIGNATURE_MATCH :
3555                    PackageManager.SIGNATURE_NO_MATCH;
3556        }
3557
3558        ArraySet<Signature> set1 = new ArraySet<Signature>();
3559        for (Signature sig : s1) {
3560            set1.add(sig);
3561        }
3562        ArraySet<Signature> set2 = new ArraySet<Signature>();
3563        for (Signature sig : s2) {
3564            set2.add(sig);
3565        }
3566        // Make sure s2 contains all signatures in s1.
3567        if (set1.equals(set2)) {
3568            return PackageManager.SIGNATURE_MATCH;
3569        }
3570        return PackageManager.SIGNATURE_NO_MATCH;
3571    }
3572
3573    /**
3574     * If the database version for this type of package (internal storage or
3575     * external storage) is less than the version where package signatures
3576     * were updated, return true.
3577     */
3578    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3579        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3580                DatabaseVersion.SIGNATURE_END_ENTITY))
3581                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3582                        DatabaseVersion.SIGNATURE_END_ENTITY));
3583    }
3584
3585    /**
3586     * Used for backward compatibility to make sure any packages with
3587     * certificate chains get upgraded to the new style. {@code existingSigs}
3588     * will be in the old format (since they were stored on disk from before the
3589     * system upgrade) and {@code scannedSigs} will be in the newer format.
3590     */
3591    private int compareSignaturesCompat(PackageSignatures existingSigs,
3592            PackageParser.Package scannedPkg) {
3593        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3594            return PackageManager.SIGNATURE_NO_MATCH;
3595        }
3596
3597        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3598        for (Signature sig : existingSigs.mSignatures) {
3599            existingSet.add(sig);
3600        }
3601        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3602        for (Signature sig : scannedPkg.mSignatures) {
3603            try {
3604                Signature[] chainSignatures = sig.getChainSignatures();
3605                for (Signature chainSig : chainSignatures) {
3606                    scannedCompatSet.add(chainSig);
3607                }
3608            } catch (CertificateEncodingException e) {
3609                scannedCompatSet.add(sig);
3610            }
3611        }
3612        /*
3613         * Make sure the expanded scanned set contains all signatures in the
3614         * existing one.
3615         */
3616        if (scannedCompatSet.equals(existingSet)) {
3617            // Migrate the old signatures to the new scheme.
3618            existingSigs.assignSignatures(scannedPkg.mSignatures);
3619            // The new KeySets will be re-added later in the scanning process.
3620            synchronized (mPackages) {
3621                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3622            }
3623            return PackageManager.SIGNATURE_MATCH;
3624        }
3625        return PackageManager.SIGNATURE_NO_MATCH;
3626    }
3627
3628    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3629        if (isExternal(scannedPkg)) {
3630            return mSettings.isExternalDatabaseVersionOlderThan(
3631                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3632        } else {
3633            return mSettings.isInternalDatabaseVersionOlderThan(
3634                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3635        }
3636    }
3637
3638    private int compareSignaturesRecover(PackageSignatures existingSigs,
3639            PackageParser.Package scannedPkg) {
3640        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3641            return PackageManager.SIGNATURE_NO_MATCH;
3642        }
3643
3644        String msg = null;
3645        try {
3646            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3647                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3648                        + scannedPkg.packageName);
3649                return PackageManager.SIGNATURE_MATCH;
3650            }
3651        } catch (CertificateException e) {
3652            msg = e.getMessage();
3653        }
3654
3655        logCriticalInfo(Log.INFO,
3656                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3657        return PackageManager.SIGNATURE_NO_MATCH;
3658    }
3659
3660    @Override
3661    public String[] getPackagesForUid(int uid) {
3662        uid = UserHandle.getAppId(uid);
3663        // reader
3664        synchronized (mPackages) {
3665            Object obj = mSettings.getUserIdLPr(uid);
3666            if (obj instanceof SharedUserSetting) {
3667                final SharedUserSetting sus = (SharedUserSetting) obj;
3668                final int N = sus.packages.size();
3669                final String[] res = new String[N];
3670                final Iterator<PackageSetting> it = sus.packages.iterator();
3671                int i = 0;
3672                while (it.hasNext()) {
3673                    res[i++] = it.next().name;
3674                }
3675                return res;
3676            } else if (obj instanceof PackageSetting) {
3677                final PackageSetting ps = (PackageSetting) obj;
3678                return new String[] { ps.name };
3679            }
3680        }
3681        return null;
3682    }
3683
3684    @Override
3685    public String getNameForUid(int uid) {
3686        // reader
3687        synchronized (mPackages) {
3688            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3689            if (obj instanceof SharedUserSetting) {
3690                final SharedUserSetting sus = (SharedUserSetting) obj;
3691                return sus.name + ":" + sus.userId;
3692            } else if (obj instanceof PackageSetting) {
3693                final PackageSetting ps = (PackageSetting) obj;
3694                return ps.name;
3695            }
3696        }
3697        return null;
3698    }
3699
3700    @Override
3701    public int getUidForSharedUser(String sharedUserName) {
3702        if(sharedUserName == null) {
3703            return -1;
3704        }
3705        // reader
3706        synchronized (mPackages) {
3707            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3708            if (suid == null) {
3709                return -1;
3710            }
3711            return suid.userId;
3712        }
3713    }
3714
3715    @Override
3716    public int getFlagsForUid(int uid) {
3717        synchronized (mPackages) {
3718            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3719            if (obj instanceof SharedUserSetting) {
3720                final SharedUserSetting sus = (SharedUserSetting) obj;
3721                return sus.pkgFlags;
3722            } else if (obj instanceof PackageSetting) {
3723                final PackageSetting ps = (PackageSetting) obj;
3724                return ps.pkgFlags;
3725            }
3726        }
3727        return 0;
3728    }
3729
3730    @Override
3731    public int getPrivateFlagsForUid(int uid) {
3732        synchronized (mPackages) {
3733            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3734            if (obj instanceof SharedUserSetting) {
3735                final SharedUserSetting sus = (SharedUserSetting) obj;
3736                return sus.pkgPrivateFlags;
3737            } else if (obj instanceof PackageSetting) {
3738                final PackageSetting ps = (PackageSetting) obj;
3739                return ps.pkgPrivateFlags;
3740            }
3741        }
3742        return 0;
3743    }
3744
3745    @Override
3746    public boolean isUidPrivileged(int uid) {
3747        uid = UserHandle.getAppId(uid);
3748        // reader
3749        synchronized (mPackages) {
3750            Object obj = mSettings.getUserIdLPr(uid);
3751            if (obj instanceof SharedUserSetting) {
3752                final SharedUserSetting sus = (SharedUserSetting) obj;
3753                final Iterator<PackageSetting> it = sus.packages.iterator();
3754                while (it.hasNext()) {
3755                    if (it.next().isPrivileged()) {
3756                        return true;
3757                    }
3758                }
3759            } else if (obj instanceof PackageSetting) {
3760                final PackageSetting ps = (PackageSetting) obj;
3761                return ps.isPrivileged();
3762            }
3763        }
3764        return false;
3765    }
3766
3767    @Override
3768    public String[] getAppOpPermissionPackages(String permissionName) {
3769        synchronized (mPackages) {
3770            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3771            if (pkgs == null) {
3772                return null;
3773            }
3774            return pkgs.toArray(new String[pkgs.size()]);
3775        }
3776    }
3777
3778    @Override
3779    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3780            int flags, int userId) {
3781        if (!sUserManager.exists(userId)) return null;
3782        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3783        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3784        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3785    }
3786
3787    @Override
3788    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3789            IntentFilter filter, int match, ComponentName activity) {
3790        final int userId = UserHandle.getCallingUserId();
3791        if (DEBUG_PREFERRED) {
3792            Log.v(TAG, "setLastChosenActivity intent=" + intent
3793                + " resolvedType=" + resolvedType
3794                + " flags=" + flags
3795                + " filter=" + filter
3796                + " match=" + match
3797                + " activity=" + activity);
3798            filter.dump(new PrintStreamPrinter(System.out), "    ");
3799        }
3800        intent.setComponent(null);
3801        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3802        // Find any earlier preferred or last chosen entries and nuke them
3803        findPreferredActivity(intent, resolvedType,
3804                flags, query, 0, false, true, false, userId);
3805        // Add the new activity as the last chosen for this filter
3806        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3807                "Setting last chosen");
3808    }
3809
3810    @Override
3811    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3812        final int userId = UserHandle.getCallingUserId();
3813        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3814        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3815        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3816                false, false, false, userId);
3817    }
3818
3819    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3820            int flags, List<ResolveInfo> query, int userId) {
3821        if (query != null) {
3822            final int N = query.size();
3823            if (N == 1) {
3824                return query.get(0);
3825            } else if (N > 1) {
3826                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3827                // If there is more than one activity with the same priority,
3828                // then let the user decide between them.
3829                ResolveInfo r0 = query.get(0);
3830                ResolveInfo r1 = query.get(1);
3831                if (DEBUG_INTENT_MATCHING || debug) {
3832                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3833                            + r1.activityInfo.name + "=" + r1.priority);
3834                }
3835                // If the first activity has a higher priority, or a different
3836                // default, then it is always desireable to pick it.
3837                if (r0.priority != r1.priority
3838                        || r0.preferredOrder != r1.preferredOrder
3839                        || r0.isDefault != r1.isDefault) {
3840                    return query.get(0);
3841                }
3842                // If we have saved a preference for a preferred activity for
3843                // this Intent, use that.
3844                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3845                        flags, query, r0.priority, true, false, debug, userId);
3846                if (ri != null) {
3847                    return ri;
3848                }
3849                if (userId != 0) {
3850                    ri = new ResolveInfo(mResolveInfo);
3851                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3852                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3853                            ri.activityInfo.applicationInfo);
3854                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3855                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3856                    return ri;
3857                }
3858                return mResolveInfo;
3859            }
3860        }
3861        return null;
3862    }
3863
3864    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3865            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3866        final int N = query.size();
3867        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3868                .get(userId);
3869        // Get the list of persistent preferred activities that handle the intent
3870        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3871        List<PersistentPreferredActivity> pprefs = ppir != null
3872                ? ppir.queryIntent(intent, resolvedType,
3873                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3874                : null;
3875        if (pprefs != null && pprefs.size() > 0) {
3876            final int M = pprefs.size();
3877            for (int i=0; i<M; i++) {
3878                final PersistentPreferredActivity ppa = pprefs.get(i);
3879                if (DEBUG_PREFERRED || debug) {
3880                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3881                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3882                            + "\n  component=" + ppa.mComponent);
3883                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3884                }
3885                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3886                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3887                if (DEBUG_PREFERRED || debug) {
3888                    Slog.v(TAG, "Found persistent preferred activity:");
3889                    if (ai != null) {
3890                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3891                    } else {
3892                        Slog.v(TAG, "  null");
3893                    }
3894                }
3895                if (ai == null) {
3896                    // This previously registered persistent preferred activity
3897                    // component is no longer known. Ignore it and do NOT remove it.
3898                    continue;
3899                }
3900                for (int j=0; j<N; j++) {
3901                    final ResolveInfo ri = query.get(j);
3902                    if (!ri.activityInfo.applicationInfo.packageName
3903                            .equals(ai.applicationInfo.packageName)) {
3904                        continue;
3905                    }
3906                    if (!ri.activityInfo.name.equals(ai.name)) {
3907                        continue;
3908                    }
3909                    //  Found a persistent preference that can handle the intent.
3910                    if (DEBUG_PREFERRED || debug) {
3911                        Slog.v(TAG, "Returning persistent preferred activity: " +
3912                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3913                    }
3914                    return ri;
3915                }
3916            }
3917        }
3918        return null;
3919    }
3920
3921    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3922            List<ResolveInfo> query, int priority, boolean always,
3923            boolean removeMatches, boolean debug, int userId) {
3924        if (!sUserManager.exists(userId)) return null;
3925        // writer
3926        synchronized (mPackages) {
3927            if (intent.getSelector() != null) {
3928                intent = intent.getSelector();
3929            }
3930            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3931
3932            // Try to find a matching persistent preferred activity.
3933            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3934                    debug, userId);
3935
3936            // If a persistent preferred activity matched, use it.
3937            if (pri != null) {
3938                return pri;
3939            }
3940
3941            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3942            // Get the list of preferred activities that handle the intent
3943            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3944            List<PreferredActivity> prefs = pir != null
3945                    ? pir.queryIntent(intent, resolvedType,
3946                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3947                    : null;
3948            if (prefs != null && prefs.size() > 0) {
3949                boolean changed = false;
3950                try {
3951                    // First figure out how good the original match set is.
3952                    // We will only allow preferred activities that came
3953                    // from the same match quality.
3954                    int match = 0;
3955
3956                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3957
3958                    final int N = query.size();
3959                    for (int j=0; j<N; j++) {
3960                        final ResolveInfo ri = query.get(j);
3961                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3962                                + ": 0x" + Integer.toHexString(match));
3963                        if (ri.match > match) {
3964                            match = ri.match;
3965                        }
3966                    }
3967
3968                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3969                            + Integer.toHexString(match));
3970
3971                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3972                    final int M = prefs.size();
3973                    for (int i=0; i<M; i++) {
3974                        final PreferredActivity pa = prefs.get(i);
3975                        if (DEBUG_PREFERRED || debug) {
3976                            Slog.v(TAG, "Checking PreferredActivity ds="
3977                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3978                                    + "\n  component=" + pa.mPref.mComponent);
3979                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3980                        }
3981                        if (pa.mPref.mMatch != match) {
3982                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3983                                    + Integer.toHexString(pa.mPref.mMatch));
3984                            continue;
3985                        }
3986                        // If it's not an "always" type preferred activity and that's what we're
3987                        // looking for, skip it.
3988                        if (always && !pa.mPref.mAlways) {
3989                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3990                            continue;
3991                        }
3992                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3993                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3994                        if (DEBUG_PREFERRED || debug) {
3995                            Slog.v(TAG, "Found preferred activity:");
3996                            if (ai != null) {
3997                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3998                            } else {
3999                                Slog.v(TAG, "  null");
4000                            }
4001                        }
4002                        if (ai == null) {
4003                            // This previously registered preferred activity
4004                            // component is no longer known.  Most likely an update
4005                            // to the app was installed and in the new version this
4006                            // component no longer exists.  Clean it up by removing
4007                            // it from the preferred activities list, and skip it.
4008                            Slog.w(TAG, "Removing dangling preferred activity: "
4009                                    + pa.mPref.mComponent);
4010                            pir.removeFilter(pa);
4011                            changed = true;
4012                            continue;
4013                        }
4014                        for (int j=0; j<N; j++) {
4015                            final ResolveInfo ri = query.get(j);
4016                            if (!ri.activityInfo.applicationInfo.packageName
4017                                    .equals(ai.applicationInfo.packageName)) {
4018                                continue;
4019                            }
4020                            if (!ri.activityInfo.name.equals(ai.name)) {
4021                                continue;
4022                            }
4023
4024                            if (removeMatches) {
4025                                pir.removeFilter(pa);
4026                                changed = true;
4027                                if (DEBUG_PREFERRED) {
4028                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4029                                }
4030                                break;
4031                            }
4032
4033                            // Okay we found a previously set preferred or last chosen app.
4034                            // If the result set is different from when this
4035                            // was created, we need to clear it and re-ask the
4036                            // user their preference, if we're looking for an "always" type entry.
4037                            if (always && !pa.mPref.sameSet(query)) {
4038                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4039                                        + intent + " type " + resolvedType);
4040                                if (DEBUG_PREFERRED) {
4041                                    Slog.v(TAG, "Removing preferred activity since set changed "
4042                                            + pa.mPref.mComponent);
4043                                }
4044                                pir.removeFilter(pa);
4045                                // Re-add the filter as a "last chosen" entry (!always)
4046                                PreferredActivity lastChosen = new PreferredActivity(
4047                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4048                                pir.addFilter(lastChosen);
4049                                changed = true;
4050                                return null;
4051                            }
4052
4053                            // Yay! Either the set matched or we're looking for the last chosen
4054                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4055                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4056                            return ri;
4057                        }
4058                    }
4059                } finally {
4060                    if (changed) {
4061                        if (DEBUG_PREFERRED) {
4062                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4063                        }
4064                        scheduleWritePackageRestrictionsLocked(userId);
4065                    }
4066                }
4067            }
4068        }
4069        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4070        return null;
4071    }
4072
4073    /*
4074     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4075     */
4076    @Override
4077    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4078            int targetUserId) {
4079        mContext.enforceCallingOrSelfPermission(
4080                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4081        List<CrossProfileIntentFilter> matches =
4082                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4083        if (matches != null) {
4084            int size = matches.size();
4085            for (int i = 0; i < size; i++) {
4086                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4087            }
4088        }
4089        return false;
4090    }
4091
4092    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4093            String resolvedType, int userId) {
4094        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4095        if (resolver != null) {
4096            return resolver.queryIntent(intent, resolvedType, false, userId);
4097        }
4098        return null;
4099    }
4100
4101    @Override
4102    public List<ResolveInfo> queryIntentActivities(Intent intent,
4103            String resolvedType, int flags, int userId) {
4104        if (!sUserManager.exists(userId)) return Collections.emptyList();
4105        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4106        ComponentName comp = intent.getComponent();
4107        if (comp == null) {
4108            if (intent.getSelector() != null) {
4109                intent = intent.getSelector();
4110                comp = intent.getComponent();
4111            }
4112        }
4113
4114        if (comp != null) {
4115            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4116            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4117            if (ai != null) {
4118                final ResolveInfo ri = new ResolveInfo();
4119                ri.activityInfo = ai;
4120                list.add(ri);
4121            }
4122            return list;
4123        }
4124
4125        // reader
4126        synchronized (mPackages) {
4127            final String pkgName = intent.getPackage();
4128            if (pkgName == null) {
4129                List<CrossProfileIntentFilter> matchingFilters =
4130                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4131                // Check for results that need to skip the current profile.
4132                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4133                        resolvedType, flags, userId);
4134                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4135                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4136                    result.add(resolveInfo);
4137                    return filterIfNotPrimaryUser(result, userId);
4138                }
4139
4140                // Check for results in the current profile.
4141                List<ResolveInfo> result = mActivities.queryIntent(
4142                        intent, resolvedType, flags, userId);
4143
4144                // Check for cross profile results.
4145                resolveInfo = queryCrossProfileIntents(
4146                        matchingFilters, intent, resolvedType, flags, userId);
4147                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4148                    result.add(resolveInfo);
4149                    Collections.sort(result, mResolvePrioritySorter);
4150                }
4151                result = filterIfNotPrimaryUser(result, userId);
4152                if (result.size() > 1 && hasWebURI(intent)) {
4153                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4154                }
4155                return result;
4156            }
4157            final PackageParser.Package pkg = mPackages.get(pkgName);
4158            if (pkg != null) {
4159                return filterIfNotPrimaryUser(
4160                        mActivities.queryIntentForPackage(
4161                                intent, resolvedType, flags, pkg.activities, userId),
4162                        userId);
4163            }
4164            return new ArrayList<ResolveInfo>();
4165        }
4166    }
4167
4168    private boolean isUserEnabled(int userId) {
4169        long callingId = Binder.clearCallingIdentity();
4170        try {
4171            UserInfo userInfo = sUserManager.getUserInfo(userId);
4172            return userInfo != null && userInfo.isEnabled();
4173        } finally {
4174            Binder.restoreCallingIdentity(callingId);
4175        }
4176    }
4177
4178    /**
4179     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4180     *
4181     * @return filtered list
4182     */
4183    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4184        if (userId == UserHandle.USER_OWNER) {
4185            return resolveInfos;
4186        }
4187        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4188            ResolveInfo info = resolveInfos.get(i);
4189            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4190                resolveInfos.remove(i);
4191            }
4192        }
4193        return resolveInfos;
4194    }
4195
4196    private static boolean hasWebURI(Intent intent) {
4197        if (intent.getData() == null) {
4198            return false;
4199        }
4200        final String scheme = intent.getScheme();
4201        if (TextUtils.isEmpty(scheme)) {
4202            return false;
4203        }
4204        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4205    }
4206
4207    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4208            int flags, List<ResolveInfo> candidates) {
4209        if (DEBUG_PREFERRED) {
4210            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4211                    candidates.size());
4212        }
4213
4214        final int userId = UserHandle.getCallingUserId();
4215        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4216        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4217        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4218        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4219        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4220
4221        synchronized (mPackages) {
4222            final int count = candidates.size();
4223            // First, try to use the domain prefered App. Partition the candidates into four lists:
4224            // one for the final results, one for the "do not use ever", one for "undefined status"
4225            // and finally one for "Browser App type".
4226            for (int n=0; n<count; n++) {
4227                ResolveInfo info = candidates.get(n);
4228                String packageName = info.activityInfo.packageName;
4229                PackageSetting ps = mSettings.mPackages.get(packageName);
4230                if (ps != null) {
4231                    // Add to the special match all list (Browser use case)
4232                    if (info.handleAllWebDataURI) {
4233                        matchAllList.add(info);
4234                        continue;
4235                    }
4236                    // Try to get the status from User settings first
4237                    int status = getDomainVerificationStatusLPr(ps, userId);
4238                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4239                        alwaysList.add(info);
4240                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4241                        neverList.add(info);
4242                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4243                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4244                        undefinedList.add(info);
4245                    }
4246                }
4247            }
4248            // First try to add the "always" if there is any
4249            if (alwaysList.size() > 0) {
4250                result.addAll(alwaysList);
4251            } else {
4252                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4253                result.addAll(undefinedList);
4254                // Also add Browsers (all of them or only the default one)
4255                if ((flags & MATCH_ALL) != 0) {
4256                    result.addAll(matchAllList);
4257                } else {
4258                    // Try to add the Default Browser if we can
4259                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4260                            UserHandle.myUserId());
4261                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4262                        boolean defaultBrowserFound = false;
4263                        final int browserCount = matchAllList.size();
4264                        for (int n=0; n<browserCount; n++) {
4265                            ResolveInfo browser = matchAllList.get(n);
4266                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4267                                result.add(browser);
4268                                defaultBrowserFound = true;
4269                                break;
4270                            }
4271                        }
4272                        if (!defaultBrowserFound) {
4273                            result.addAll(matchAllList);
4274                        }
4275                    } else {
4276                        result.addAll(matchAllList);
4277                    }
4278                }
4279
4280                // If there is nothing selected, add all candidates and remove the ones that the User
4281                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4282                if (result.size() == 0) {
4283                    result.addAll(candidates);
4284                    result.removeAll(neverList);
4285                }
4286            }
4287        }
4288        if (DEBUG_PREFERRED) {
4289            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4290                    result.size());
4291        }
4292        return result;
4293    }
4294
4295    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4296        int status = ps.getDomainVerificationStatusForUser(userId);
4297        // if none available, get the master status
4298        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4299            if (ps.getIntentFilterVerificationInfo() != null) {
4300                status = ps.getIntentFilterVerificationInfo().getStatus();
4301            }
4302        }
4303        return status;
4304    }
4305
4306    private ResolveInfo querySkipCurrentProfileIntents(
4307            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4308            int flags, int sourceUserId) {
4309        if (matchingFilters != null) {
4310            int size = matchingFilters.size();
4311            for (int i = 0; i < size; i ++) {
4312                CrossProfileIntentFilter filter = matchingFilters.get(i);
4313                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4314                    // Checking if there are activities in the target user that can handle the
4315                    // intent.
4316                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4317                            flags, sourceUserId);
4318                    if (resolveInfo != null) {
4319                        return resolveInfo;
4320                    }
4321                }
4322            }
4323        }
4324        return null;
4325    }
4326
4327    // Return matching ResolveInfo if any for skip current profile intent filters.
4328    private ResolveInfo queryCrossProfileIntents(
4329            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4330            int flags, int sourceUserId) {
4331        if (matchingFilters != null) {
4332            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4333            // match the same intent. For performance reasons, it is better not to
4334            // run queryIntent twice for the same userId
4335            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4336            int size = matchingFilters.size();
4337            for (int i = 0; i < size; i++) {
4338                CrossProfileIntentFilter filter = matchingFilters.get(i);
4339                int targetUserId = filter.getTargetUserId();
4340                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4341                        && !alreadyTriedUserIds.get(targetUserId)) {
4342                    // Checking if there are activities in the target user that can handle the
4343                    // intent.
4344                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4345                            flags, sourceUserId);
4346                    if (resolveInfo != null) return resolveInfo;
4347                    alreadyTriedUserIds.put(targetUserId, true);
4348                }
4349            }
4350        }
4351        return null;
4352    }
4353
4354    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4355            String resolvedType, int flags, int sourceUserId) {
4356        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4357                resolvedType, flags, filter.getTargetUserId());
4358        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4359            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4360        }
4361        return null;
4362    }
4363
4364    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4365            int sourceUserId, int targetUserId) {
4366        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4367        String className;
4368        if (targetUserId == UserHandle.USER_OWNER) {
4369            className = FORWARD_INTENT_TO_USER_OWNER;
4370        } else {
4371            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4372        }
4373        ComponentName forwardingActivityComponentName = new ComponentName(
4374                mAndroidApplication.packageName, className);
4375        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4376                sourceUserId);
4377        if (targetUserId == UserHandle.USER_OWNER) {
4378            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4379            forwardingResolveInfo.noResourceId = true;
4380        }
4381        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4382        forwardingResolveInfo.priority = 0;
4383        forwardingResolveInfo.preferredOrder = 0;
4384        forwardingResolveInfo.match = 0;
4385        forwardingResolveInfo.isDefault = true;
4386        forwardingResolveInfo.filter = filter;
4387        forwardingResolveInfo.targetUserId = targetUserId;
4388        return forwardingResolveInfo;
4389    }
4390
4391    @Override
4392    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4393            Intent[] specifics, String[] specificTypes, Intent intent,
4394            String resolvedType, int flags, int userId) {
4395        if (!sUserManager.exists(userId)) return Collections.emptyList();
4396        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4397                false, "query intent activity options");
4398        final String resultsAction = intent.getAction();
4399
4400        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4401                | PackageManager.GET_RESOLVED_FILTER, userId);
4402
4403        if (DEBUG_INTENT_MATCHING) {
4404            Log.v(TAG, "Query " + intent + ": " + results);
4405        }
4406
4407        int specificsPos = 0;
4408        int N;
4409
4410        // todo: note that the algorithm used here is O(N^2).  This
4411        // isn't a problem in our current environment, but if we start running
4412        // into situations where we have more than 5 or 10 matches then this
4413        // should probably be changed to something smarter...
4414
4415        // First we go through and resolve each of the specific items
4416        // that were supplied, taking care of removing any corresponding
4417        // duplicate items in the generic resolve list.
4418        if (specifics != null) {
4419            for (int i=0; i<specifics.length; i++) {
4420                final Intent sintent = specifics[i];
4421                if (sintent == null) {
4422                    continue;
4423                }
4424
4425                if (DEBUG_INTENT_MATCHING) {
4426                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4427                }
4428
4429                String action = sintent.getAction();
4430                if (resultsAction != null && resultsAction.equals(action)) {
4431                    // If this action was explicitly requested, then don't
4432                    // remove things that have it.
4433                    action = null;
4434                }
4435
4436                ResolveInfo ri = null;
4437                ActivityInfo ai = null;
4438
4439                ComponentName comp = sintent.getComponent();
4440                if (comp == null) {
4441                    ri = resolveIntent(
4442                        sintent,
4443                        specificTypes != null ? specificTypes[i] : null,
4444                            flags, userId);
4445                    if (ri == null) {
4446                        continue;
4447                    }
4448                    if (ri == mResolveInfo) {
4449                        // ACK!  Must do something better with this.
4450                    }
4451                    ai = ri.activityInfo;
4452                    comp = new ComponentName(ai.applicationInfo.packageName,
4453                            ai.name);
4454                } else {
4455                    ai = getActivityInfo(comp, flags, userId);
4456                    if (ai == null) {
4457                        continue;
4458                    }
4459                }
4460
4461                // Look for any generic query activities that are duplicates
4462                // of this specific one, and remove them from the results.
4463                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4464                N = results.size();
4465                int j;
4466                for (j=specificsPos; j<N; j++) {
4467                    ResolveInfo sri = results.get(j);
4468                    if ((sri.activityInfo.name.equals(comp.getClassName())
4469                            && sri.activityInfo.applicationInfo.packageName.equals(
4470                                    comp.getPackageName()))
4471                        || (action != null && sri.filter.matchAction(action))) {
4472                        results.remove(j);
4473                        if (DEBUG_INTENT_MATCHING) Log.v(
4474                            TAG, "Removing duplicate item from " + j
4475                            + " due to specific " + specificsPos);
4476                        if (ri == null) {
4477                            ri = sri;
4478                        }
4479                        j--;
4480                        N--;
4481                    }
4482                }
4483
4484                // Add this specific item to its proper place.
4485                if (ri == null) {
4486                    ri = new ResolveInfo();
4487                    ri.activityInfo = ai;
4488                }
4489                results.add(specificsPos, ri);
4490                ri.specificIndex = i;
4491                specificsPos++;
4492            }
4493        }
4494
4495        // Now we go through the remaining generic results and remove any
4496        // duplicate actions that are found here.
4497        N = results.size();
4498        for (int i=specificsPos; i<N-1; i++) {
4499            final ResolveInfo rii = results.get(i);
4500            if (rii.filter == null) {
4501                continue;
4502            }
4503
4504            // Iterate over all of the actions of this result's intent
4505            // filter...  typically this should be just one.
4506            final Iterator<String> it = rii.filter.actionsIterator();
4507            if (it == null) {
4508                continue;
4509            }
4510            while (it.hasNext()) {
4511                final String action = it.next();
4512                if (resultsAction != null && resultsAction.equals(action)) {
4513                    // If this action was explicitly requested, then don't
4514                    // remove things that have it.
4515                    continue;
4516                }
4517                for (int j=i+1; j<N; j++) {
4518                    final ResolveInfo rij = results.get(j);
4519                    if (rij.filter != null && rij.filter.hasAction(action)) {
4520                        results.remove(j);
4521                        if (DEBUG_INTENT_MATCHING) Log.v(
4522                            TAG, "Removing duplicate item from " + j
4523                            + " due to action " + action + " at " + i);
4524                        j--;
4525                        N--;
4526                    }
4527                }
4528            }
4529
4530            // If the caller didn't request filter information, drop it now
4531            // so we don't have to marshall/unmarshall it.
4532            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4533                rii.filter = null;
4534            }
4535        }
4536
4537        // Filter out the caller activity if so requested.
4538        if (caller != null) {
4539            N = results.size();
4540            for (int i=0; i<N; i++) {
4541                ActivityInfo ainfo = results.get(i).activityInfo;
4542                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4543                        && caller.getClassName().equals(ainfo.name)) {
4544                    results.remove(i);
4545                    break;
4546                }
4547            }
4548        }
4549
4550        // If the caller didn't request filter information,
4551        // drop them now so we don't have to
4552        // marshall/unmarshall it.
4553        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4554            N = results.size();
4555            for (int i=0; i<N; i++) {
4556                results.get(i).filter = null;
4557            }
4558        }
4559
4560        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4561        return results;
4562    }
4563
4564    @Override
4565    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4566            int userId) {
4567        if (!sUserManager.exists(userId)) return Collections.emptyList();
4568        ComponentName comp = intent.getComponent();
4569        if (comp == null) {
4570            if (intent.getSelector() != null) {
4571                intent = intent.getSelector();
4572                comp = intent.getComponent();
4573            }
4574        }
4575        if (comp != null) {
4576            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4577            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4578            if (ai != null) {
4579                ResolveInfo ri = new ResolveInfo();
4580                ri.activityInfo = ai;
4581                list.add(ri);
4582            }
4583            return list;
4584        }
4585
4586        // reader
4587        synchronized (mPackages) {
4588            String pkgName = intent.getPackage();
4589            if (pkgName == null) {
4590                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4591            }
4592            final PackageParser.Package pkg = mPackages.get(pkgName);
4593            if (pkg != null) {
4594                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4595                        userId);
4596            }
4597            return null;
4598        }
4599    }
4600
4601    @Override
4602    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4603        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4604        if (!sUserManager.exists(userId)) return null;
4605        if (query != null) {
4606            if (query.size() >= 1) {
4607                // If there is more than one service with the same priority,
4608                // just arbitrarily pick the first one.
4609                return query.get(0);
4610            }
4611        }
4612        return null;
4613    }
4614
4615    @Override
4616    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4617            int userId) {
4618        if (!sUserManager.exists(userId)) return Collections.emptyList();
4619        ComponentName comp = intent.getComponent();
4620        if (comp == null) {
4621            if (intent.getSelector() != null) {
4622                intent = intent.getSelector();
4623                comp = intent.getComponent();
4624            }
4625        }
4626        if (comp != null) {
4627            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4628            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4629            if (si != null) {
4630                final ResolveInfo ri = new ResolveInfo();
4631                ri.serviceInfo = si;
4632                list.add(ri);
4633            }
4634            return list;
4635        }
4636
4637        // reader
4638        synchronized (mPackages) {
4639            String pkgName = intent.getPackage();
4640            if (pkgName == null) {
4641                return mServices.queryIntent(intent, resolvedType, flags, userId);
4642            }
4643            final PackageParser.Package pkg = mPackages.get(pkgName);
4644            if (pkg != null) {
4645                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4646                        userId);
4647            }
4648            return null;
4649        }
4650    }
4651
4652    @Override
4653    public List<ResolveInfo> queryIntentContentProviders(
4654            Intent intent, String resolvedType, int flags, int userId) {
4655        if (!sUserManager.exists(userId)) return Collections.emptyList();
4656        ComponentName comp = intent.getComponent();
4657        if (comp == null) {
4658            if (intent.getSelector() != null) {
4659                intent = intent.getSelector();
4660                comp = intent.getComponent();
4661            }
4662        }
4663        if (comp != null) {
4664            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4665            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4666            if (pi != null) {
4667                final ResolveInfo ri = new ResolveInfo();
4668                ri.providerInfo = pi;
4669                list.add(ri);
4670            }
4671            return list;
4672        }
4673
4674        // reader
4675        synchronized (mPackages) {
4676            String pkgName = intent.getPackage();
4677            if (pkgName == null) {
4678                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4679            }
4680            final PackageParser.Package pkg = mPackages.get(pkgName);
4681            if (pkg != null) {
4682                return mProviders.queryIntentForPackage(
4683                        intent, resolvedType, flags, pkg.providers, userId);
4684            }
4685            return null;
4686        }
4687    }
4688
4689    @Override
4690    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4691        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4692
4693        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4694
4695        // writer
4696        synchronized (mPackages) {
4697            ArrayList<PackageInfo> list;
4698            if (listUninstalled) {
4699                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4700                for (PackageSetting ps : mSettings.mPackages.values()) {
4701                    PackageInfo pi;
4702                    if (ps.pkg != null) {
4703                        pi = generatePackageInfo(ps.pkg, flags, userId);
4704                    } else {
4705                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4706                    }
4707                    if (pi != null) {
4708                        list.add(pi);
4709                    }
4710                }
4711            } else {
4712                list = new ArrayList<PackageInfo>(mPackages.size());
4713                for (PackageParser.Package p : mPackages.values()) {
4714                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4715                    if (pi != null) {
4716                        list.add(pi);
4717                    }
4718                }
4719            }
4720
4721            return new ParceledListSlice<PackageInfo>(list);
4722        }
4723    }
4724
4725    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4726            String[] permissions, boolean[] tmp, int flags, int userId) {
4727        int numMatch = 0;
4728        final PermissionsState permissionsState = ps.getPermissionsState();
4729        for (int i=0; i<permissions.length; i++) {
4730            final String permission = permissions[i];
4731            if (permissionsState.hasPermission(permission, userId)) {
4732                tmp[i] = true;
4733                numMatch++;
4734            } else {
4735                tmp[i] = false;
4736            }
4737        }
4738        if (numMatch == 0) {
4739            return;
4740        }
4741        PackageInfo pi;
4742        if (ps.pkg != null) {
4743            pi = generatePackageInfo(ps.pkg, flags, userId);
4744        } else {
4745            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4746        }
4747        // The above might return null in cases of uninstalled apps or install-state
4748        // skew across users/profiles.
4749        if (pi != null) {
4750            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4751                if (numMatch == permissions.length) {
4752                    pi.requestedPermissions = permissions;
4753                } else {
4754                    pi.requestedPermissions = new String[numMatch];
4755                    numMatch = 0;
4756                    for (int i=0; i<permissions.length; i++) {
4757                        if (tmp[i]) {
4758                            pi.requestedPermissions[numMatch] = permissions[i];
4759                            numMatch++;
4760                        }
4761                    }
4762                }
4763            }
4764            list.add(pi);
4765        }
4766    }
4767
4768    @Override
4769    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4770            String[] permissions, int flags, int userId) {
4771        if (!sUserManager.exists(userId)) return null;
4772        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4773
4774        // writer
4775        synchronized (mPackages) {
4776            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4777            boolean[] tmpBools = new boolean[permissions.length];
4778            if (listUninstalled) {
4779                for (PackageSetting ps : mSettings.mPackages.values()) {
4780                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4781                }
4782            } else {
4783                for (PackageParser.Package pkg : mPackages.values()) {
4784                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4785                    if (ps != null) {
4786                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4787                                userId);
4788                    }
4789                }
4790            }
4791
4792            return new ParceledListSlice<PackageInfo>(list);
4793        }
4794    }
4795
4796    @Override
4797    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4798        if (!sUserManager.exists(userId)) return null;
4799        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4800
4801        // writer
4802        synchronized (mPackages) {
4803            ArrayList<ApplicationInfo> list;
4804            if (listUninstalled) {
4805                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4806                for (PackageSetting ps : mSettings.mPackages.values()) {
4807                    ApplicationInfo ai;
4808                    if (ps.pkg != null) {
4809                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4810                                ps.readUserState(userId), userId);
4811                    } else {
4812                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4813                    }
4814                    if (ai != null) {
4815                        list.add(ai);
4816                    }
4817                }
4818            } else {
4819                list = new ArrayList<ApplicationInfo>(mPackages.size());
4820                for (PackageParser.Package p : mPackages.values()) {
4821                    if (p.mExtras != null) {
4822                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4823                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4824                        if (ai != null) {
4825                            list.add(ai);
4826                        }
4827                    }
4828                }
4829            }
4830
4831            return new ParceledListSlice<ApplicationInfo>(list);
4832        }
4833    }
4834
4835    public List<ApplicationInfo> getPersistentApplications(int flags) {
4836        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4837
4838        // reader
4839        synchronized (mPackages) {
4840            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4841            final int userId = UserHandle.getCallingUserId();
4842            while (i.hasNext()) {
4843                final PackageParser.Package p = i.next();
4844                if (p.applicationInfo != null
4845                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4846                        && (!mSafeMode || isSystemApp(p))) {
4847                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4848                    if (ps != null) {
4849                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4850                                ps.readUserState(userId), userId);
4851                        if (ai != null) {
4852                            finalList.add(ai);
4853                        }
4854                    }
4855                }
4856            }
4857        }
4858
4859        return finalList;
4860    }
4861
4862    @Override
4863    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4864        if (!sUserManager.exists(userId)) return null;
4865        // reader
4866        synchronized (mPackages) {
4867            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4868            PackageSetting ps = provider != null
4869                    ? mSettings.mPackages.get(provider.owner.packageName)
4870                    : null;
4871            return ps != null
4872                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4873                    && (!mSafeMode || (provider.info.applicationInfo.flags
4874                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4875                    ? PackageParser.generateProviderInfo(provider, flags,
4876                            ps.readUserState(userId), userId)
4877                    : null;
4878        }
4879    }
4880
4881    /**
4882     * @deprecated
4883     */
4884    @Deprecated
4885    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4886        // reader
4887        synchronized (mPackages) {
4888            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4889                    .entrySet().iterator();
4890            final int userId = UserHandle.getCallingUserId();
4891            while (i.hasNext()) {
4892                Map.Entry<String, PackageParser.Provider> entry = i.next();
4893                PackageParser.Provider p = entry.getValue();
4894                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4895
4896                if (ps != null && p.syncable
4897                        && (!mSafeMode || (p.info.applicationInfo.flags
4898                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4899                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4900                            ps.readUserState(userId), userId);
4901                    if (info != null) {
4902                        outNames.add(entry.getKey());
4903                        outInfo.add(info);
4904                    }
4905                }
4906            }
4907        }
4908    }
4909
4910    @Override
4911    public List<ProviderInfo> queryContentProviders(String processName,
4912            int uid, int flags) {
4913        ArrayList<ProviderInfo> finalList = null;
4914        // reader
4915        synchronized (mPackages) {
4916            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4917            final int userId = processName != null ?
4918                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4919            while (i.hasNext()) {
4920                final PackageParser.Provider p = i.next();
4921                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4922                if (ps != null && p.info.authority != null
4923                        && (processName == null
4924                                || (p.info.processName.equals(processName)
4925                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4926                        && mSettings.isEnabledLPr(p.info, flags, userId)
4927                        && (!mSafeMode
4928                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4929                    if (finalList == null) {
4930                        finalList = new ArrayList<ProviderInfo>(3);
4931                    }
4932                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4933                            ps.readUserState(userId), userId);
4934                    if (info != null) {
4935                        finalList.add(info);
4936                    }
4937                }
4938            }
4939        }
4940
4941        if (finalList != null) {
4942            Collections.sort(finalList, mProviderInitOrderSorter);
4943        }
4944
4945        return finalList;
4946    }
4947
4948    @Override
4949    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4950            int flags) {
4951        // reader
4952        synchronized (mPackages) {
4953            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4954            return PackageParser.generateInstrumentationInfo(i, flags);
4955        }
4956    }
4957
4958    @Override
4959    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4960            int flags) {
4961        ArrayList<InstrumentationInfo> finalList =
4962            new ArrayList<InstrumentationInfo>();
4963
4964        // reader
4965        synchronized (mPackages) {
4966            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4967            while (i.hasNext()) {
4968                final PackageParser.Instrumentation p = i.next();
4969                if (targetPackage == null
4970                        || targetPackage.equals(p.info.targetPackage)) {
4971                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4972                            flags);
4973                    if (ii != null) {
4974                        finalList.add(ii);
4975                    }
4976                }
4977            }
4978        }
4979
4980        return finalList;
4981    }
4982
4983    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4984        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4985        if (overlays == null) {
4986            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4987            return;
4988        }
4989        for (PackageParser.Package opkg : overlays.values()) {
4990            // Not much to do if idmap fails: we already logged the error
4991            // and we certainly don't want to abort installation of pkg simply
4992            // because an overlay didn't fit properly. For these reasons,
4993            // ignore the return value of createIdmapForPackagePairLI.
4994            createIdmapForPackagePairLI(pkg, opkg);
4995        }
4996    }
4997
4998    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4999            PackageParser.Package opkg) {
5000        if (!opkg.mTrustedOverlay) {
5001            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5002                    opkg.baseCodePath + ": overlay not trusted");
5003            return false;
5004        }
5005        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5006        if (overlaySet == null) {
5007            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5008                    opkg.baseCodePath + " but target package has no known overlays");
5009            return false;
5010        }
5011        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5012        // TODO: generate idmap for split APKs
5013        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5014            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5015                    + opkg.baseCodePath);
5016            return false;
5017        }
5018        PackageParser.Package[] overlayArray =
5019            overlaySet.values().toArray(new PackageParser.Package[0]);
5020        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5021            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5022                return p1.mOverlayPriority - p2.mOverlayPriority;
5023            }
5024        };
5025        Arrays.sort(overlayArray, cmp);
5026
5027        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5028        int i = 0;
5029        for (PackageParser.Package p : overlayArray) {
5030            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5031        }
5032        return true;
5033    }
5034
5035    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5036        final File[] files = dir.listFiles();
5037        if (ArrayUtils.isEmpty(files)) {
5038            Log.d(TAG, "No files in app dir " + dir);
5039            return;
5040        }
5041
5042        if (DEBUG_PACKAGE_SCANNING) {
5043            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5044                    + " flags=0x" + Integer.toHexString(parseFlags));
5045        }
5046
5047        for (File file : files) {
5048            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5049                    && !PackageInstallerService.isStageName(file.getName());
5050            if (!isPackage) {
5051                // Ignore entries which are not packages
5052                continue;
5053            }
5054            try {
5055                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5056                        scanFlags, currentTime, null);
5057            } catch (PackageManagerException e) {
5058                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5059
5060                // Delete invalid userdata apps
5061                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5062                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5063                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5064                    if (file.isDirectory()) {
5065                        mInstaller.rmPackageDir(file.getAbsolutePath());
5066                    } else {
5067                        file.delete();
5068                    }
5069                }
5070            }
5071        }
5072    }
5073
5074    private static File getSettingsProblemFile() {
5075        File dataDir = Environment.getDataDirectory();
5076        File systemDir = new File(dataDir, "system");
5077        File fname = new File(systemDir, "uiderrors.txt");
5078        return fname;
5079    }
5080
5081    static void reportSettingsProblem(int priority, String msg) {
5082        logCriticalInfo(priority, msg);
5083    }
5084
5085    static void logCriticalInfo(int priority, String msg) {
5086        Slog.println(priority, TAG, msg);
5087        EventLogTags.writePmCriticalInfo(msg);
5088        try {
5089            File fname = getSettingsProblemFile();
5090            FileOutputStream out = new FileOutputStream(fname, true);
5091            PrintWriter pw = new FastPrintWriter(out);
5092            SimpleDateFormat formatter = new SimpleDateFormat();
5093            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5094            pw.println(dateString + ": " + msg);
5095            pw.close();
5096            FileUtils.setPermissions(
5097                    fname.toString(),
5098                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5099                    -1, -1);
5100        } catch (java.io.IOException e) {
5101        }
5102    }
5103
5104    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5105            PackageParser.Package pkg, File srcFile, int parseFlags)
5106            throws PackageManagerException {
5107        if (ps != null
5108                && ps.codePath.equals(srcFile)
5109                && ps.timeStamp == srcFile.lastModified()
5110                && !isCompatSignatureUpdateNeeded(pkg)
5111                && !isRecoverSignatureUpdateNeeded(pkg)) {
5112            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5113            if (ps.signatures.mSignatures != null
5114                    && ps.signatures.mSignatures.length != 0
5115                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
5116                // Optimization: reuse the existing cached certificates
5117                // if the package appears to be unchanged.
5118                pkg.mSignatures = ps.signatures.mSignatures;
5119                KeySetManagerService ksms = mSettings.mKeySetManagerService;
5120                synchronized (mPackages) {
5121                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5122                }
5123                return;
5124            }
5125
5126            Slog.w(TAG, "PackageSetting for " + ps.name
5127                    + " is missing signatures.  Collecting certs again to recover them.");
5128        } else {
5129            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5130        }
5131
5132        try {
5133            pp.collectCertificates(pkg, parseFlags);
5134            pp.collectManifestDigest(pkg);
5135        } catch (PackageParserException e) {
5136            throw PackageManagerException.from(e);
5137        }
5138    }
5139
5140    /*
5141     *  Scan a package and return the newly parsed package.
5142     *  Returns null in case of errors and the error code is stored in mLastScanError
5143     */
5144    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5145            long currentTime, UserHandle user) throws PackageManagerException {
5146        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5147        parseFlags |= mDefParseFlags;
5148        PackageParser pp = new PackageParser();
5149        pp.setSeparateProcesses(mSeparateProcesses);
5150        pp.setOnlyCoreApps(mOnlyCore);
5151        pp.setDisplayMetrics(mMetrics);
5152
5153        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5154            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5155        }
5156
5157        final PackageParser.Package pkg;
5158        try {
5159            pkg = pp.parsePackage(scanFile, parseFlags);
5160        } catch (PackageParserException e) {
5161            throw PackageManagerException.from(e);
5162        }
5163
5164        PackageSetting ps = null;
5165        PackageSetting updatedPkg;
5166        // reader
5167        synchronized (mPackages) {
5168            // Look to see if we already know about this package.
5169            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5170            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5171                // This package has been renamed to its original name.  Let's
5172                // use that.
5173                ps = mSettings.peekPackageLPr(oldName);
5174            }
5175            // If there was no original package, see one for the real package name.
5176            if (ps == null) {
5177                ps = mSettings.peekPackageLPr(pkg.packageName);
5178            }
5179            // Check to see if this package could be hiding/updating a system
5180            // package.  Must look for it either under the original or real
5181            // package name depending on our state.
5182            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5183            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5184        }
5185        boolean updatedPkgBetter = false;
5186        // First check if this is a system package that may involve an update
5187        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5188            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5189            // it needs to drop FLAG_PRIVILEGED.
5190            if (locationIsPrivileged(scanFile)) {
5191                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5192            } else {
5193                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5194            }
5195
5196            if (ps != null && !ps.codePath.equals(scanFile)) {
5197                // The path has changed from what was last scanned...  check the
5198                // version of the new path against what we have stored to determine
5199                // what to do.
5200                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5201                if (pkg.mVersionCode <= ps.versionCode) {
5202                    // The system package has been updated and the code path does not match
5203                    // Ignore entry. Skip it.
5204                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5205                            + " ignored: updated version " + ps.versionCode
5206                            + " better than this " + pkg.mVersionCode);
5207                    if (!updatedPkg.codePath.equals(scanFile)) {
5208                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5209                                + ps.name + " changing from " + updatedPkg.codePathString
5210                                + " to " + scanFile);
5211                        updatedPkg.codePath = scanFile;
5212                        updatedPkg.codePathString = scanFile.toString();
5213                        updatedPkg.resourcePath = scanFile;
5214                        updatedPkg.resourcePathString = scanFile.toString();
5215                    }
5216                    updatedPkg.pkg = pkg;
5217                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5218                } else {
5219                    // The current app on the system partition is better than
5220                    // what we have updated to on the data partition; switch
5221                    // back to the system partition version.
5222                    // At this point, its safely assumed that package installation for
5223                    // apps in system partition will go through. If not there won't be a working
5224                    // version of the app
5225                    // writer
5226                    synchronized (mPackages) {
5227                        // Just remove the loaded entries from package lists.
5228                        mPackages.remove(ps.name);
5229                    }
5230
5231                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5232                            + " reverting from " + ps.codePathString
5233                            + ": new version " + pkg.mVersionCode
5234                            + " better than installed " + ps.versionCode);
5235
5236                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5237                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5238                    synchronized (mInstallLock) {
5239                        args.cleanUpResourcesLI();
5240                    }
5241                    synchronized (mPackages) {
5242                        mSettings.enableSystemPackageLPw(ps.name);
5243                    }
5244                    updatedPkgBetter = true;
5245                }
5246            }
5247        }
5248
5249        if (updatedPkg != null) {
5250            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5251            // initially
5252            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5253
5254            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5255            // flag set initially
5256            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5257                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5258            }
5259        }
5260
5261        // Verify certificates against what was last scanned
5262        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5263
5264        /*
5265         * A new system app appeared, but we already had a non-system one of the
5266         * same name installed earlier.
5267         */
5268        boolean shouldHideSystemApp = false;
5269        if (updatedPkg == null && ps != null
5270                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5271            /*
5272             * Check to make sure the signatures match first. If they don't,
5273             * wipe the installed application and its data.
5274             */
5275            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5276                    != PackageManager.SIGNATURE_MATCH) {
5277                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5278                        + " signatures don't match existing userdata copy; removing");
5279                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5280                ps = null;
5281            } else {
5282                /*
5283                 * If the newly-added system app is an older version than the
5284                 * already installed version, hide it. It will be scanned later
5285                 * and re-added like an update.
5286                 */
5287                if (pkg.mVersionCode <= ps.versionCode) {
5288                    shouldHideSystemApp = true;
5289                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5290                            + " but new version " + pkg.mVersionCode + " better than installed "
5291                            + ps.versionCode + "; hiding system");
5292                } else {
5293                    /*
5294                     * The newly found system app is a newer version that the
5295                     * one previously installed. Simply remove the
5296                     * already-installed application and replace it with our own
5297                     * while keeping the application data.
5298                     */
5299                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5300                            + " reverting from " + ps.codePathString + ": new version "
5301                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5302                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5303                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5304                    synchronized (mInstallLock) {
5305                        args.cleanUpResourcesLI();
5306                    }
5307                }
5308            }
5309        }
5310
5311        // The apk is forward locked (not public) if its code and resources
5312        // are kept in different files. (except for app in either system or
5313        // vendor path).
5314        // TODO grab this value from PackageSettings
5315        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5316            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5317                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5318            }
5319        }
5320
5321        // TODO: extend to support forward-locked splits
5322        String resourcePath = null;
5323        String baseResourcePath = null;
5324        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5325            if (ps != null && ps.resourcePathString != null) {
5326                resourcePath = ps.resourcePathString;
5327                baseResourcePath = ps.resourcePathString;
5328            } else {
5329                // Should not happen at all. Just log an error.
5330                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5331            }
5332        } else {
5333            resourcePath = pkg.codePath;
5334            baseResourcePath = pkg.baseCodePath;
5335        }
5336
5337        // Set application objects path explicitly.
5338        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5339        pkg.applicationInfo.setCodePath(pkg.codePath);
5340        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5341        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5342        pkg.applicationInfo.setResourcePath(resourcePath);
5343        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5344        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5345
5346        // Note that we invoke the following method only if we are about to unpack an application
5347        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5348                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5349
5350        /*
5351         * If the system app should be overridden by a previously installed
5352         * data, hide the system app now and let the /data/app scan pick it up
5353         * again.
5354         */
5355        if (shouldHideSystemApp) {
5356            synchronized (mPackages) {
5357                /*
5358                 * We have to grant systems permissions before we hide, because
5359                 * grantPermissions will assume the package update is trying to
5360                 * expand its permissions.
5361                 */
5362                grantPermissionsLPw(pkg, true, pkg.packageName);
5363                mSettings.disableSystemPackageLPw(pkg.packageName);
5364            }
5365        }
5366
5367        return scannedPkg;
5368    }
5369
5370    private static String fixProcessName(String defProcessName,
5371            String processName, int uid) {
5372        if (processName == null) {
5373            return defProcessName;
5374        }
5375        return processName;
5376    }
5377
5378    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5379            throws PackageManagerException {
5380        if (pkgSetting.signatures.mSignatures != null) {
5381            // Already existing package. Make sure signatures match
5382            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5383                    == PackageManager.SIGNATURE_MATCH;
5384            if (!match) {
5385                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5386                        == PackageManager.SIGNATURE_MATCH;
5387            }
5388            if (!match) {
5389                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5390                        == PackageManager.SIGNATURE_MATCH;
5391            }
5392            if (!match) {
5393                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5394                        + pkg.packageName + " signatures do not match the "
5395                        + "previously installed version; ignoring!");
5396            }
5397        }
5398
5399        // Check for shared user signatures
5400        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5401            // Already existing package. Make sure signatures match
5402            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5403                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5404            if (!match) {
5405                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5406                        == PackageManager.SIGNATURE_MATCH;
5407            }
5408            if (!match) {
5409                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5410                        == PackageManager.SIGNATURE_MATCH;
5411            }
5412            if (!match) {
5413                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5414                        "Package " + pkg.packageName
5415                        + " has no signatures that match those in shared user "
5416                        + pkgSetting.sharedUser.name + "; ignoring!");
5417            }
5418        }
5419    }
5420
5421    /**
5422     * Enforces that only the system UID or root's UID can call a method exposed
5423     * via Binder.
5424     *
5425     * @param message used as message if SecurityException is thrown
5426     * @throws SecurityException if the caller is not system or root
5427     */
5428    private static final void enforceSystemOrRoot(String message) {
5429        final int uid = Binder.getCallingUid();
5430        if (uid != Process.SYSTEM_UID && uid != 0) {
5431            throw new SecurityException(message);
5432        }
5433    }
5434
5435    @Override
5436    public void performBootDexOpt() {
5437        enforceSystemOrRoot("Only the system can request dexopt be performed");
5438
5439        // Before everything else, see whether we need to fstrim.
5440        try {
5441            IMountService ms = PackageHelper.getMountService();
5442            if (ms != null) {
5443                final boolean isUpgrade = isUpgrade();
5444                boolean doTrim = isUpgrade;
5445                if (doTrim) {
5446                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5447                } else {
5448                    final long interval = android.provider.Settings.Global.getLong(
5449                            mContext.getContentResolver(),
5450                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5451                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5452                    if (interval > 0) {
5453                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5454                        if (timeSinceLast > interval) {
5455                            doTrim = true;
5456                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5457                                    + "; running immediately");
5458                        }
5459                    }
5460                }
5461                if (doTrim) {
5462                    if (!isFirstBoot()) {
5463                        try {
5464                            ActivityManagerNative.getDefault().showBootMessage(
5465                                    mContext.getResources().getString(
5466                                            R.string.android_upgrading_fstrim), true);
5467                        } catch (RemoteException e) {
5468                        }
5469                    }
5470                    ms.runMaintenance();
5471                }
5472            } else {
5473                Slog.e(TAG, "Mount service unavailable!");
5474            }
5475        } catch (RemoteException e) {
5476            // Can't happen; MountService is local
5477        }
5478
5479        final ArraySet<PackageParser.Package> pkgs;
5480        synchronized (mPackages) {
5481            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5482        }
5483
5484        if (pkgs != null) {
5485            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5486            // in case the device runs out of space.
5487            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5488            // Give priority to core apps.
5489            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5490                PackageParser.Package pkg = it.next();
5491                if (pkg.coreApp) {
5492                    if (DEBUG_DEXOPT) {
5493                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5494                    }
5495                    sortedPkgs.add(pkg);
5496                    it.remove();
5497                }
5498            }
5499            // Give priority to system apps that listen for pre boot complete.
5500            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5501            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5502            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5503                PackageParser.Package pkg = it.next();
5504                if (pkgNames.contains(pkg.packageName)) {
5505                    if (DEBUG_DEXOPT) {
5506                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5507                    }
5508                    sortedPkgs.add(pkg);
5509                    it.remove();
5510                }
5511            }
5512            // Give priority to system apps.
5513            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5514                PackageParser.Package pkg = it.next();
5515                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5516                    if (DEBUG_DEXOPT) {
5517                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5518                    }
5519                    sortedPkgs.add(pkg);
5520                    it.remove();
5521                }
5522            }
5523            // Give priority to updated system apps.
5524            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5525                PackageParser.Package pkg = it.next();
5526                if (pkg.isUpdatedSystemApp()) {
5527                    if (DEBUG_DEXOPT) {
5528                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5529                    }
5530                    sortedPkgs.add(pkg);
5531                    it.remove();
5532                }
5533            }
5534            // Give priority to apps that listen for boot complete.
5535            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5536            pkgNames = getPackageNamesForIntent(intent);
5537            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5538                PackageParser.Package pkg = it.next();
5539                if (pkgNames.contains(pkg.packageName)) {
5540                    if (DEBUG_DEXOPT) {
5541                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5542                    }
5543                    sortedPkgs.add(pkg);
5544                    it.remove();
5545                }
5546            }
5547            // Filter out packages that aren't recently used.
5548            filterRecentlyUsedApps(pkgs);
5549            // Add all remaining apps.
5550            for (PackageParser.Package pkg : pkgs) {
5551                if (DEBUG_DEXOPT) {
5552                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5553                }
5554                sortedPkgs.add(pkg);
5555            }
5556
5557            // If we want to be lazy, filter everything that wasn't recently used.
5558            if (mLazyDexOpt) {
5559                filterRecentlyUsedApps(sortedPkgs);
5560            }
5561
5562            int i = 0;
5563            int total = sortedPkgs.size();
5564            File dataDir = Environment.getDataDirectory();
5565            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5566            if (lowThreshold == 0) {
5567                throw new IllegalStateException("Invalid low memory threshold");
5568            }
5569            for (PackageParser.Package pkg : sortedPkgs) {
5570                long usableSpace = dataDir.getUsableSpace();
5571                if (usableSpace < lowThreshold) {
5572                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5573                    break;
5574                }
5575                performBootDexOpt(pkg, ++i, total);
5576            }
5577        }
5578    }
5579
5580    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5581        // Filter out packages that aren't recently used.
5582        //
5583        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5584        // should do a full dexopt.
5585        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5586            int total = pkgs.size();
5587            int skipped = 0;
5588            long now = System.currentTimeMillis();
5589            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5590                PackageParser.Package pkg = i.next();
5591                long then = pkg.mLastPackageUsageTimeInMills;
5592                if (then + mDexOptLRUThresholdInMills < now) {
5593                    if (DEBUG_DEXOPT) {
5594                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5595                              ((then == 0) ? "never" : new Date(then)));
5596                    }
5597                    i.remove();
5598                    skipped++;
5599                }
5600            }
5601            if (DEBUG_DEXOPT) {
5602                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5603            }
5604        }
5605    }
5606
5607    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5608        List<ResolveInfo> ris = null;
5609        try {
5610            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5611                    intent, null, 0, UserHandle.USER_OWNER);
5612        } catch (RemoteException e) {
5613        }
5614        ArraySet<String> pkgNames = new ArraySet<String>();
5615        if (ris != null) {
5616            for (ResolveInfo ri : ris) {
5617                pkgNames.add(ri.activityInfo.packageName);
5618            }
5619        }
5620        return pkgNames;
5621    }
5622
5623    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5624        if (DEBUG_DEXOPT) {
5625            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5626        }
5627        if (!isFirstBoot()) {
5628            try {
5629                ActivityManagerNative.getDefault().showBootMessage(
5630                        mContext.getResources().getString(R.string.android_upgrading_apk,
5631                                curr, total), true);
5632            } catch (RemoteException e) {
5633            }
5634        }
5635        PackageParser.Package p = pkg;
5636        synchronized (mInstallLock) {
5637            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5638                    false /* force dex */, false /* defer */, true /* include dependencies */);
5639        }
5640    }
5641
5642    @Override
5643    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5644        return performDexOpt(packageName, instructionSet, false);
5645    }
5646
5647    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5648        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5649        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5650        if (!dexopt && !updateUsage) {
5651            // We aren't going to dexopt or update usage, so bail early.
5652            return false;
5653        }
5654        PackageParser.Package p;
5655        final String targetInstructionSet;
5656        synchronized (mPackages) {
5657            p = mPackages.get(packageName);
5658            if (p == null) {
5659                return false;
5660            }
5661            if (updateUsage) {
5662                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5663            }
5664            mPackageUsage.write(false);
5665            if (!dexopt) {
5666                // We aren't going to dexopt, so bail early.
5667                return false;
5668            }
5669
5670            targetInstructionSet = instructionSet != null ? instructionSet :
5671                    getPrimaryInstructionSet(p.applicationInfo);
5672            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5673                return false;
5674            }
5675        }
5676
5677        synchronized (mInstallLock) {
5678            final String[] instructionSets = new String[] { targetInstructionSet };
5679            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5680                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5681            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5682        }
5683    }
5684
5685    public ArraySet<String> getPackagesThatNeedDexOpt() {
5686        ArraySet<String> pkgs = null;
5687        synchronized (mPackages) {
5688            for (PackageParser.Package p : mPackages.values()) {
5689                if (DEBUG_DEXOPT) {
5690                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5691                }
5692                if (!p.mDexOptPerformed.isEmpty()) {
5693                    continue;
5694                }
5695                if (pkgs == null) {
5696                    pkgs = new ArraySet<String>();
5697                }
5698                pkgs.add(p.packageName);
5699            }
5700        }
5701        return pkgs;
5702    }
5703
5704    public void shutdown() {
5705        mPackageUsage.write(true);
5706    }
5707
5708    @Override
5709    public void forceDexOpt(String packageName) {
5710        enforceSystemOrRoot("forceDexOpt");
5711
5712        PackageParser.Package pkg;
5713        synchronized (mPackages) {
5714            pkg = mPackages.get(packageName);
5715            if (pkg == null) {
5716                throw new IllegalArgumentException("Missing package: " + packageName);
5717            }
5718        }
5719
5720        synchronized (mInstallLock) {
5721            final String[] instructionSets = new String[] {
5722                    getPrimaryInstructionSet(pkg.applicationInfo) };
5723            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5724                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5725            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5726                throw new IllegalStateException("Failed to dexopt: " + res);
5727            }
5728        }
5729    }
5730
5731    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5732        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5733            Slog.w(TAG, "Unable to update from " + oldPkg.name
5734                    + " to " + newPkg.packageName
5735                    + ": old package not in system partition");
5736            return false;
5737        } else if (mPackages.get(oldPkg.name) != null) {
5738            Slog.w(TAG, "Unable to update from " + oldPkg.name
5739                    + " to " + newPkg.packageName
5740                    + ": old package still exists");
5741            return false;
5742        }
5743        return true;
5744    }
5745
5746    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5747        int[] users = sUserManager.getUserIds();
5748        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5749        if (res < 0) {
5750            return res;
5751        }
5752        for (int user : users) {
5753            if (user != 0) {
5754                res = mInstaller.createUserData(volumeUuid, packageName,
5755                        UserHandle.getUid(user, uid), user, seinfo);
5756                if (res < 0) {
5757                    return res;
5758                }
5759            }
5760        }
5761        return res;
5762    }
5763
5764    private int removeDataDirsLI(String volumeUuid, String packageName) {
5765        int[] users = sUserManager.getUserIds();
5766        int res = 0;
5767        for (int user : users) {
5768            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5769            if (resInner < 0) {
5770                res = resInner;
5771            }
5772        }
5773
5774        return res;
5775    }
5776
5777    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5778        int[] users = sUserManager.getUserIds();
5779        int res = 0;
5780        for (int user : users) {
5781            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5782            if (resInner < 0) {
5783                res = resInner;
5784            }
5785        }
5786        return res;
5787    }
5788
5789    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5790            PackageParser.Package changingLib) {
5791        if (file.path != null) {
5792            usesLibraryFiles.add(file.path);
5793            return;
5794        }
5795        PackageParser.Package p = mPackages.get(file.apk);
5796        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5797            // If we are doing this while in the middle of updating a library apk,
5798            // then we need to make sure to use that new apk for determining the
5799            // dependencies here.  (We haven't yet finished committing the new apk
5800            // to the package manager state.)
5801            if (p == null || p.packageName.equals(changingLib.packageName)) {
5802                p = changingLib;
5803            }
5804        }
5805        if (p != null) {
5806            usesLibraryFiles.addAll(p.getAllCodePaths());
5807        }
5808    }
5809
5810    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5811            PackageParser.Package changingLib) throws PackageManagerException {
5812        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5813            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5814            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5815            for (int i=0; i<N; i++) {
5816                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5817                if (file == null) {
5818                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5819                            "Package " + pkg.packageName + " requires unavailable shared library "
5820                            + pkg.usesLibraries.get(i) + "; failing!");
5821                }
5822                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5823            }
5824            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5825            for (int i=0; i<N; i++) {
5826                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5827                if (file == null) {
5828                    Slog.w(TAG, "Package " + pkg.packageName
5829                            + " desires unavailable shared library "
5830                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5831                } else {
5832                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5833                }
5834            }
5835            N = usesLibraryFiles.size();
5836            if (N > 0) {
5837                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5838            } else {
5839                pkg.usesLibraryFiles = null;
5840            }
5841        }
5842    }
5843
5844    private static boolean hasString(List<String> list, List<String> which) {
5845        if (list == null) {
5846            return false;
5847        }
5848        for (int i=list.size()-1; i>=0; i--) {
5849            for (int j=which.size()-1; j>=0; j--) {
5850                if (which.get(j).equals(list.get(i))) {
5851                    return true;
5852                }
5853            }
5854        }
5855        return false;
5856    }
5857
5858    private void updateAllSharedLibrariesLPw() {
5859        for (PackageParser.Package pkg : mPackages.values()) {
5860            try {
5861                updateSharedLibrariesLPw(pkg, null);
5862            } catch (PackageManagerException e) {
5863                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5864            }
5865        }
5866    }
5867
5868    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5869            PackageParser.Package changingPkg) {
5870        ArrayList<PackageParser.Package> res = null;
5871        for (PackageParser.Package pkg : mPackages.values()) {
5872            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5873                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5874                if (res == null) {
5875                    res = new ArrayList<PackageParser.Package>();
5876                }
5877                res.add(pkg);
5878                try {
5879                    updateSharedLibrariesLPw(pkg, changingPkg);
5880                } catch (PackageManagerException e) {
5881                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5882                }
5883            }
5884        }
5885        return res;
5886    }
5887
5888    /**
5889     * Derive the value of the {@code cpuAbiOverride} based on the provided
5890     * value and an optional stored value from the package settings.
5891     */
5892    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5893        String cpuAbiOverride = null;
5894
5895        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5896            cpuAbiOverride = null;
5897        } else if (abiOverride != null) {
5898            cpuAbiOverride = abiOverride;
5899        } else if (settings != null) {
5900            cpuAbiOverride = settings.cpuAbiOverrideString;
5901        }
5902
5903        return cpuAbiOverride;
5904    }
5905
5906    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5907            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5908        boolean success = false;
5909        try {
5910            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5911                    currentTime, user);
5912            success = true;
5913            return res;
5914        } finally {
5915            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5916                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5917            }
5918        }
5919    }
5920
5921    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5922            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5923        final File scanFile = new File(pkg.codePath);
5924        if (pkg.applicationInfo.getCodePath() == null ||
5925                pkg.applicationInfo.getResourcePath() == null) {
5926            // Bail out. The resource and code paths haven't been set.
5927            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5928                    "Code and resource paths haven't been set correctly");
5929        }
5930
5931        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5932            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5933        } else {
5934            // Only allow system apps to be flagged as core apps.
5935            pkg.coreApp = false;
5936        }
5937
5938        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5939            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5940        }
5941
5942        if (mCustomResolverComponentName != null &&
5943                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5944            setUpCustomResolverActivity(pkg);
5945        }
5946
5947        if (pkg.packageName.equals("android")) {
5948            synchronized (mPackages) {
5949                if (mAndroidApplication != null) {
5950                    Slog.w(TAG, "*************************************************");
5951                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5952                    Slog.w(TAG, " file=" + scanFile);
5953                    Slog.w(TAG, "*************************************************");
5954                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5955                            "Core android package being redefined.  Skipping.");
5956                }
5957
5958                // Set up information for our fall-back user intent resolution activity.
5959                mPlatformPackage = pkg;
5960                pkg.mVersionCode = mSdkVersion;
5961                mAndroidApplication = pkg.applicationInfo;
5962
5963                if (!mResolverReplaced) {
5964                    mResolveActivity.applicationInfo = mAndroidApplication;
5965                    mResolveActivity.name = ResolverActivity.class.getName();
5966                    mResolveActivity.packageName = mAndroidApplication.packageName;
5967                    mResolveActivity.processName = "system:ui";
5968                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5969                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5970                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5971                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5972                    mResolveActivity.exported = true;
5973                    mResolveActivity.enabled = true;
5974                    mResolveInfo.activityInfo = mResolveActivity;
5975                    mResolveInfo.priority = 0;
5976                    mResolveInfo.preferredOrder = 0;
5977                    mResolveInfo.match = 0;
5978                    mResolveComponentName = new ComponentName(
5979                            mAndroidApplication.packageName, mResolveActivity.name);
5980                }
5981            }
5982        }
5983
5984        if (DEBUG_PACKAGE_SCANNING) {
5985            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5986                Log.d(TAG, "Scanning package " + pkg.packageName);
5987        }
5988
5989        if (mPackages.containsKey(pkg.packageName)
5990                || mSharedLibraries.containsKey(pkg.packageName)) {
5991            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5992                    "Application package " + pkg.packageName
5993                    + " already installed.  Skipping duplicate.");
5994        }
5995
5996        // If we're only installing presumed-existing packages, require that the
5997        // scanned APK is both already known and at the path previously established
5998        // for it.  Previously unknown packages we pick up normally, but if we have an
5999        // a priori expectation about this package's install presence, enforce it.
6000        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6001            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6002            if (known != null) {
6003                if (DEBUG_PACKAGE_SCANNING) {
6004                    Log.d(TAG, "Examining " + pkg.codePath
6005                            + " and requiring known paths " + known.codePathString
6006                            + " & " + known.resourcePathString);
6007                }
6008                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6009                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6010                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6011                            "Application package " + pkg.packageName
6012                            + " found at " + pkg.applicationInfo.getCodePath()
6013                            + " but expected at " + known.codePathString + "; ignoring.");
6014                }
6015            }
6016        }
6017
6018        // Initialize package source and resource directories
6019        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6020        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6021
6022        SharedUserSetting suid = null;
6023        PackageSetting pkgSetting = null;
6024
6025        if (!isSystemApp(pkg)) {
6026            // Only system apps can use these features.
6027            pkg.mOriginalPackages = null;
6028            pkg.mRealPackage = null;
6029            pkg.mAdoptPermissions = null;
6030        }
6031
6032        // writer
6033        synchronized (mPackages) {
6034            if (pkg.mSharedUserId != null) {
6035                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6036                if (suid == null) {
6037                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6038                            "Creating application package " + pkg.packageName
6039                            + " for shared user failed");
6040                }
6041                if (DEBUG_PACKAGE_SCANNING) {
6042                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6043                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6044                                + "): packages=" + suid.packages);
6045                }
6046            }
6047
6048            // Check if we are renaming from an original package name.
6049            PackageSetting origPackage = null;
6050            String realName = null;
6051            if (pkg.mOriginalPackages != null) {
6052                // This package may need to be renamed to a previously
6053                // installed name.  Let's check on that...
6054                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6055                if (pkg.mOriginalPackages.contains(renamed)) {
6056                    // This package had originally been installed as the
6057                    // original name, and we have already taken care of
6058                    // transitioning to the new one.  Just update the new
6059                    // one to continue using the old name.
6060                    realName = pkg.mRealPackage;
6061                    if (!pkg.packageName.equals(renamed)) {
6062                        // Callers into this function may have already taken
6063                        // care of renaming the package; only do it here if
6064                        // it is not already done.
6065                        pkg.setPackageName(renamed);
6066                    }
6067
6068                } else {
6069                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6070                        if ((origPackage = mSettings.peekPackageLPr(
6071                                pkg.mOriginalPackages.get(i))) != null) {
6072                            // We do have the package already installed under its
6073                            // original name...  should we use it?
6074                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6075                                // New package is not compatible with original.
6076                                origPackage = null;
6077                                continue;
6078                            } else if (origPackage.sharedUser != null) {
6079                                // Make sure uid is compatible between packages.
6080                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6081                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6082                                            + " to " + pkg.packageName + ": old uid "
6083                                            + origPackage.sharedUser.name
6084                                            + " differs from " + pkg.mSharedUserId);
6085                                    origPackage = null;
6086                                    continue;
6087                                }
6088                            } else {
6089                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6090                                        + pkg.packageName + " to old name " + origPackage.name);
6091                            }
6092                            break;
6093                        }
6094                    }
6095                }
6096            }
6097
6098            if (mTransferedPackages.contains(pkg.packageName)) {
6099                Slog.w(TAG, "Package " + pkg.packageName
6100                        + " was transferred to another, but its .apk remains");
6101            }
6102
6103            // Just create the setting, don't add it yet. For already existing packages
6104            // the PkgSetting exists already and doesn't have to be created.
6105            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6106                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6107                    pkg.applicationInfo.primaryCpuAbi,
6108                    pkg.applicationInfo.secondaryCpuAbi,
6109                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6110                    user, false);
6111            if (pkgSetting == null) {
6112                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6113                        "Creating application package " + pkg.packageName + " failed");
6114            }
6115
6116            if (pkgSetting.origPackage != null) {
6117                // If we are first transitioning from an original package,
6118                // fix up the new package's name now.  We need to do this after
6119                // looking up the package under its new name, so getPackageLP
6120                // can take care of fiddling things correctly.
6121                pkg.setPackageName(origPackage.name);
6122
6123                // File a report about this.
6124                String msg = "New package " + pkgSetting.realName
6125                        + " renamed to replace old package " + pkgSetting.name;
6126                reportSettingsProblem(Log.WARN, msg);
6127
6128                // Make a note of it.
6129                mTransferedPackages.add(origPackage.name);
6130
6131                // No longer need to retain this.
6132                pkgSetting.origPackage = null;
6133            }
6134
6135            if (realName != null) {
6136                // Make a note of it.
6137                mTransferedPackages.add(pkg.packageName);
6138            }
6139
6140            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6141                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6142            }
6143
6144            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6145                // Check all shared libraries and map to their actual file path.
6146                // We only do this here for apps not on a system dir, because those
6147                // are the only ones that can fail an install due to this.  We
6148                // will take care of the system apps by updating all of their
6149                // library paths after the scan is done.
6150                updateSharedLibrariesLPw(pkg, null);
6151            }
6152
6153            if (mFoundPolicyFile) {
6154                SELinuxMMAC.assignSeinfoValue(pkg);
6155            }
6156
6157            pkg.applicationInfo.uid = pkgSetting.appId;
6158            pkg.mExtras = pkgSetting;
6159            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
6160                try {
6161                    verifySignaturesLP(pkgSetting, pkg);
6162                    // We just determined the app is signed correctly, so bring
6163                    // over the latest parsed certs.
6164                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6165                } catch (PackageManagerException e) {
6166                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6167                        throw e;
6168                    }
6169                    // The signature has changed, but this package is in the system
6170                    // image...  let's recover!
6171                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6172                    // However...  if this package is part of a shared user, but it
6173                    // doesn't match the signature of the shared user, let's fail.
6174                    // What this means is that you can't change the signatures
6175                    // associated with an overall shared user, which doesn't seem all
6176                    // that unreasonable.
6177                    if (pkgSetting.sharedUser != null) {
6178                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6179                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6180                            throw new PackageManagerException(
6181                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6182                                            "Signature mismatch for shared user : "
6183                                            + pkgSetting.sharedUser);
6184                        }
6185                    }
6186                    // File a report about this.
6187                    String msg = "System package " + pkg.packageName
6188                        + " signature changed; retaining data.";
6189                    reportSettingsProblem(Log.WARN, msg);
6190                }
6191            } else {
6192                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
6193                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6194                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6195                                "Package " + pkg.packageName + " upgrade keys do not match the "
6196                                + "previously installed version");
6197                    } else {
6198                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6199                        String msg = "System package " + pkg.packageName
6200                            + " signature changed; retaining data.";
6201                        reportSettingsProblem(Log.WARN, msg);
6202                    }
6203                } else {
6204                    // We just determined the app is signed correctly, so bring
6205                    // over the latest parsed certs.
6206                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6207                }
6208            }
6209            // Verify that this new package doesn't have any content providers
6210            // that conflict with existing packages.  Only do this if the
6211            // package isn't already installed, since we don't want to break
6212            // things that are installed.
6213            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6214                final int N = pkg.providers.size();
6215                int i;
6216                for (i=0; i<N; i++) {
6217                    PackageParser.Provider p = pkg.providers.get(i);
6218                    if (p.info.authority != null) {
6219                        String names[] = p.info.authority.split(";");
6220                        for (int j = 0; j < names.length; j++) {
6221                            if (mProvidersByAuthority.containsKey(names[j])) {
6222                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6223                                final String otherPackageName =
6224                                        ((other != null && other.getComponentName() != null) ?
6225                                                other.getComponentName().getPackageName() : "?");
6226                                throw new PackageManagerException(
6227                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6228                                                "Can't install because provider name " + names[j]
6229                                                + " (in package " + pkg.applicationInfo.packageName
6230                                                + ") is already used by " + otherPackageName);
6231                            }
6232                        }
6233                    }
6234                }
6235            }
6236
6237            if (pkg.mAdoptPermissions != null) {
6238                // This package wants to adopt ownership of permissions from
6239                // another package.
6240                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6241                    final String origName = pkg.mAdoptPermissions.get(i);
6242                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6243                    if (orig != null) {
6244                        if (verifyPackageUpdateLPr(orig, pkg)) {
6245                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6246                                    + pkg.packageName);
6247                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6248                        }
6249                    }
6250                }
6251            }
6252        }
6253
6254        final String pkgName = pkg.packageName;
6255
6256        final long scanFileTime = scanFile.lastModified();
6257        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6258        pkg.applicationInfo.processName = fixProcessName(
6259                pkg.applicationInfo.packageName,
6260                pkg.applicationInfo.processName,
6261                pkg.applicationInfo.uid);
6262
6263        File dataPath;
6264        if (mPlatformPackage == pkg) {
6265            // The system package is special.
6266            dataPath = new File(Environment.getDataDirectory(), "system");
6267
6268            pkg.applicationInfo.dataDir = dataPath.getPath();
6269
6270        } else {
6271            // This is a normal package, need to make its data directory.
6272            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6273                    UserHandle.USER_OWNER);
6274
6275            boolean uidError = false;
6276            if (dataPath.exists()) {
6277                int currentUid = 0;
6278                try {
6279                    StructStat stat = Os.stat(dataPath.getPath());
6280                    currentUid = stat.st_uid;
6281                } catch (ErrnoException e) {
6282                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6283                }
6284
6285                // If we have mismatched owners for the data path, we have a problem.
6286                if (currentUid != pkg.applicationInfo.uid) {
6287                    boolean recovered = false;
6288                    if (currentUid == 0) {
6289                        // The directory somehow became owned by root.  Wow.
6290                        // This is probably because the system was stopped while
6291                        // installd was in the middle of messing with its libs
6292                        // directory.  Ask installd to fix that.
6293                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6294                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6295                        if (ret >= 0) {
6296                            recovered = true;
6297                            String msg = "Package " + pkg.packageName
6298                                    + " unexpectedly changed to uid 0; recovered to " +
6299                                    + pkg.applicationInfo.uid;
6300                            reportSettingsProblem(Log.WARN, msg);
6301                        }
6302                    }
6303                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6304                            || (scanFlags&SCAN_BOOTING) != 0)) {
6305                        // If this is a system app, we can at least delete its
6306                        // current data so the application will still work.
6307                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6308                        if (ret >= 0) {
6309                            // TODO: Kill the processes first
6310                            // Old data gone!
6311                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6312                                    ? "System package " : "Third party package ";
6313                            String msg = prefix + pkg.packageName
6314                                    + " has changed from uid: "
6315                                    + currentUid + " to "
6316                                    + pkg.applicationInfo.uid + "; old data erased";
6317                            reportSettingsProblem(Log.WARN, msg);
6318                            recovered = true;
6319
6320                            // And now re-install the app.
6321                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6322                                    pkg.applicationInfo.seinfo);
6323                            if (ret == -1) {
6324                                // Ack should not happen!
6325                                msg = prefix + pkg.packageName
6326                                        + " could not have data directory re-created after delete.";
6327                                reportSettingsProblem(Log.WARN, msg);
6328                                throw new PackageManagerException(
6329                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6330                            }
6331                        }
6332                        if (!recovered) {
6333                            mHasSystemUidErrors = true;
6334                        }
6335                    } else if (!recovered) {
6336                        // If we allow this install to proceed, we will be broken.
6337                        // Abort, abort!
6338                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6339                                "scanPackageLI");
6340                    }
6341                    if (!recovered) {
6342                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6343                            + pkg.applicationInfo.uid + "/fs_"
6344                            + currentUid;
6345                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6346                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6347                        String msg = "Package " + pkg.packageName
6348                                + " has mismatched uid: "
6349                                + currentUid + " on disk, "
6350                                + pkg.applicationInfo.uid + " in settings";
6351                        // writer
6352                        synchronized (mPackages) {
6353                            mSettings.mReadMessages.append(msg);
6354                            mSettings.mReadMessages.append('\n');
6355                            uidError = true;
6356                            if (!pkgSetting.uidError) {
6357                                reportSettingsProblem(Log.ERROR, msg);
6358                            }
6359                        }
6360                    }
6361                }
6362                pkg.applicationInfo.dataDir = dataPath.getPath();
6363                if (mShouldRestoreconData) {
6364                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6365                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6366                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6367                }
6368            } else {
6369                if (DEBUG_PACKAGE_SCANNING) {
6370                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6371                        Log.v(TAG, "Want this data dir: " + dataPath);
6372                }
6373                //invoke installer to do the actual installation
6374                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6375                        pkg.applicationInfo.seinfo);
6376                if (ret < 0) {
6377                    // Error from installer
6378                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6379                            "Unable to create data dirs [errorCode=" + ret + "]");
6380                }
6381
6382                if (dataPath.exists()) {
6383                    pkg.applicationInfo.dataDir = dataPath.getPath();
6384                } else {
6385                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6386                    pkg.applicationInfo.dataDir = null;
6387                }
6388            }
6389
6390            pkgSetting.uidError = uidError;
6391        }
6392
6393        final String path = scanFile.getPath();
6394        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6395
6396        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6397            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6398
6399            // Some system apps still use directory structure for native libraries
6400            // in which case we might end up not detecting abi solely based on apk
6401            // structure. Try to detect abi based on directory structure.
6402            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6403                    pkg.applicationInfo.primaryCpuAbi == null) {
6404                setBundledAppAbisAndRoots(pkg, pkgSetting);
6405                setNativeLibraryPaths(pkg);
6406            }
6407
6408        } else {
6409            if ((scanFlags & SCAN_MOVE) != 0) {
6410                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6411                // but we already have this packages package info in the PackageSetting. We just
6412                // use that and derive the native library path based on the new codepath.
6413                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6414                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6415            }
6416
6417            // Set native library paths again. For moves, the path will be updated based on the
6418            // ABIs we've determined above. For non-moves, the path will be updated based on the
6419            // ABIs we determined during compilation, but the path will depend on the final
6420            // package path (after the rename away from the stage path).
6421            setNativeLibraryPaths(pkg);
6422        }
6423
6424        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6425        final int[] userIds = sUserManager.getUserIds();
6426        synchronized (mInstallLock) {
6427            // Create a native library symlink only if we have native libraries
6428            // and if the native libraries are 32 bit libraries. We do not provide
6429            // this symlink for 64 bit libraries.
6430            if (pkg.applicationInfo.primaryCpuAbi != null &&
6431                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6432                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6433                for (int userId : userIds) {
6434                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6435                            nativeLibPath, userId) < 0) {
6436                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6437                                "Failed linking native library dir (user=" + userId + ")");
6438                    }
6439                }
6440            }
6441        }
6442
6443        // This is a special case for the "system" package, where the ABI is
6444        // dictated by the zygote configuration (and init.rc). We should keep track
6445        // of this ABI so that we can deal with "normal" applications that run under
6446        // the same UID correctly.
6447        if (mPlatformPackage == pkg) {
6448            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6449                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6450        }
6451
6452        // If there's a mismatch between the abi-override in the package setting
6453        // and the abiOverride specified for the install. Warn about this because we
6454        // would've already compiled the app without taking the package setting into
6455        // account.
6456        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6457            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6458                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6459                        " for package: " + pkg.packageName);
6460            }
6461        }
6462
6463        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6464        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6465        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6466
6467        // Copy the derived override back to the parsed package, so that we can
6468        // update the package settings accordingly.
6469        pkg.cpuAbiOverride = cpuAbiOverride;
6470
6471        if (DEBUG_ABI_SELECTION) {
6472            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6473                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6474                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6475        }
6476
6477        // Push the derived path down into PackageSettings so we know what to
6478        // clean up at uninstall time.
6479        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6480
6481        if (DEBUG_ABI_SELECTION) {
6482            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6483                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6484                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6485        }
6486
6487        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6488            // We don't do this here during boot because we can do it all
6489            // at once after scanning all existing packages.
6490            //
6491            // We also do this *before* we perform dexopt on this package, so that
6492            // we can avoid redundant dexopts, and also to make sure we've got the
6493            // code and package path correct.
6494            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6495                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6496        }
6497
6498        if ((scanFlags & SCAN_NO_DEX) == 0) {
6499            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6500                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6501            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6502                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6503            }
6504        }
6505        if (mFactoryTest && pkg.requestedPermissions.contains(
6506                android.Manifest.permission.FACTORY_TEST)) {
6507            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6508        }
6509
6510        ArrayList<PackageParser.Package> clientLibPkgs = null;
6511
6512        // writer
6513        synchronized (mPackages) {
6514            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6515                // Only system apps can add new shared libraries.
6516                if (pkg.libraryNames != null) {
6517                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6518                        String name = pkg.libraryNames.get(i);
6519                        boolean allowed = false;
6520                        if (pkg.isUpdatedSystemApp()) {
6521                            // New library entries can only be added through the
6522                            // system image.  This is important to get rid of a lot
6523                            // of nasty edge cases: for example if we allowed a non-
6524                            // system update of the app to add a library, then uninstalling
6525                            // the update would make the library go away, and assumptions
6526                            // we made such as through app install filtering would now
6527                            // have allowed apps on the device which aren't compatible
6528                            // with it.  Better to just have the restriction here, be
6529                            // conservative, and create many fewer cases that can negatively
6530                            // impact the user experience.
6531                            final PackageSetting sysPs = mSettings
6532                                    .getDisabledSystemPkgLPr(pkg.packageName);
6533                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6534                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6535                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6536                                        allowed = true;
6537                                        allowed = true;
6538                                        break;
6539                                    }
6540                                }
6541                            }
6542                        } else {
6543                            allowed = true;
6544                        }
6545                        if (allowed) {
6546                            if (!mSharedLibraries.containsKey(name)) {
6547                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6548                            } else if (!name.equals(pkg.packageName)) {
6549                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6550                                        + name + " already exists; skipping");
6551                            }
6552                        } else {
6553                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6554                                    + name + " that is not declared on system image; skipping");
6555                        }
6556                    }
6557                    if ((scanFlags&SCAN_BOOTING) == 0) {
6558                        // If we are not booting, we need to update any applications
6559                        // that are clients of our shared library.  If we are booting,
6560                        // this will all be done once the scan is complete.
6561                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6562                    }
6563                }
6564            }
6565        }
6566
6567        // We also need to dexopt any apps that are dependent on this library.  Note that
6568        // if these fail, we should abort the install since installing the library will
6569        // result in some apps being broken.
6570        if (clientLibPkgs != null) {
6571            if ((scanFlags & SCAN_NO_DEX) == 0) {
6572                for (int i = 0; i < clientLibPkgs.size(); i++) {
6573                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6574                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6575                            null /* instruction sets */, forceDex,
6576                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6577                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6578                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6579                                "scanPackageLI failed to dexopt clientLibPkgs");
6580                    }
6581                }
6582            }
6583        }
6584
6585        // Also need to kill any apps that are dependent on the library.
6586        if (clientLibPkgs != null) {
6587            for (int i=0; i<clientLibPkgs.size(); i++) {
6588                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6589                killApplication(clientPkg.applicationInfo.packageName,
6590                        clientPkg.applicationInfo.uid, "update lib");
6591            }
6592        }
6593
6594        // writer
6595        synchronized (mPackages) {
6596            // We don't expect installation to fail beyond this point
6597
6598            // Add the new setting to mSettings
6599            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6600            // Add the new setting to mPackages
6601            mPackages.put(pkg.applicationInfo.packageName, pkg);
6602            // Make sure we don't accidentally delete its data.
6603            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6604            while (iter.hasNext()) {
6605                PackageCleanItem item = iter.next();
6606                if (pkgName.equals(item.packageName)) {
6607                    iter.remove();
6608                }
6609            }
6610
6611            // Take care of first install / last update times.
6612            if (currentTime != 0) {
6613                if (pkgSetting.firstInstallTime == 0) {
6614                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6615                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6616                    pkgSetting.lastUpdateTime = currentTime;
6617                }
6618            } else if (pkgSetting.firstInstallTime == 0) {
6619                // We need *something*.  Take time time stamp of the file.
6620                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6621            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6622                if (scanFileTime != pkgSetting.timeStamp) {
6623                    // A package on the system image has changed; consider this
6624                    // to be an update.
6625                    pkgSetting.lastUpdateTime = scanFileTime;
6626                }
6627            }
6628
6629            // Add the package's KeySets to the global KeySetManagerService
6630            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6631            try {
6632                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6633                if (pkg.mKeySetMapping != null) {
6634                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6635                    if (pkg.mUpgradeKeySets != null) {
6636                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6637                    }
6638                }
6639            } catch (NullPointerException e) {
6640                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6641            } catch (IllegalArgumentException e) {
6642                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6643            }
6644
6645            int N = pkg.providers.size();
6646            StringBuilder r = null;
6647            int i;
6648            for (i=0; i<N; i++) {
6649                PackageParser.Provider p = pkg.providers.get(i);
6650                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6651                        p.info.processName, pkg.applicationInfo.uid);
6652                mProviders.addProvider(p);
6653                p.syncable = p.info.isSyncable;
6654                if (p.info.authority != null) {
6655                    String names[] = p.info.authority.split(";");
6656                    p.info.authority = null;
6657                    for (int j = 0; j < names.length; j++) {
6658                        if (j == 1 && p.syncable) {
6659                            // We only want the first authority for a provider to possibly be
6660                            // syncable, so if we already added this provider using a different
6661                            // authority clear the syncable flag. We copy the provider before
6662                            // changing it because the mProviders object contains a reference
6663                            // to a provider that we don't want to change.
6664                            // Only do this for the second authority since the resulting provider
6665                            // object can be the same for all future authorities for this provider.
6666                            p = new PackageParser.Provider(p);
6667                            p.syncable = false;
6668                        }
6669                        if (!mProvidersByAuthority.containsKey(names[j])) {
6670                            mProvidersByAuthority.put(names[j], p);
6671                            if (p.info.authority == null) {
6672                                p.info.authority = names[j];
6673                            } else {
6674                                p.info.authority = p.info.authority + ";" + names[j];
6675                            }
6676                            if (DEBUG_PACKAGE_SCANNING) {
6677                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6678                                    Log.d(TAG, "Registered content provider: " + names[j]
6679                                            + ", className = " + p.info.name + ", isSyncable = "
6680                                            + p.info.isSyncable);
6681                            }
6682                        } else {
6683                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6684                            Slog.w(TAG, "Skipping provider name " + names[j] +
6685                                    " (in package " + pkg.applicationInfo.packageName +
6686                                    "): name already used by "
6687                                    + ((other != null && other.getComponentName() != null)
6688                                            ? other.getComponentName().getPackageName() : "?"));
6689                        }
6690                    }
6691                }
6692                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6693                    if (r == null) {
6694                        r = new StringBuilder(256);
6695                    } else {
6696                        r.append(' ');
6697                    }
6698                    r.append(p.info.name);
6699                }
6700            }
6701            if (r != null) {
6702                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6703            }
6704
6705            N = pkg.services.size();
6706            r = null;
6707            for (i=0; i<N; i++) {
6708                PackageParser.Service s = pkg.services.get(i);
6709                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6710                        s.info.processName, pkg.applicationInfo.uid);
6711                mServices.addService(s);
6712                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6713                    if (r == null) {
6714                        r = new StringBuilder(256);
6715                    } else {
6716                        r.append(' ');
6717                    }
6718                    r.append(s.info.name);
6719                }
6720            }
6721            if (r != null) {
6722                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6723            }
6724
6725            N = pkg.receivers.size();
6726            r = null;
6727            for (i=0; i<N; i++) {
6728                PackageParser.Activity a = pkg.receivers.get(i);
6729                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6730                        a.info.processName, pkg.applicationInfo.uid);
6731                mReceivers.addActivity(a, "receiver");
6732                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6733                    if (r == null) {
6734                        r = new StringBuilder(256);
6735                    } else {
6736                        r.append(' ');
6737                    }
6738                    r.append(a.info.name);
6739                }
6740            }
6741            if (r != null) {
6742                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6743            }
6744
6745            N = pkg.activities.size();
6746            r = null;
6747            for (i=0; i<N; i++) {
6748                PackageParser.Activity a = pkg.activities.get(i);
6749                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6750                        a.info.processName, pkg.applicationInfo.uid);
6751                mActivities.addActivity(a, "activity");
6752                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6753                    if (r == null) {
6754                        r = new StringBuilder(256);
6755                    } else {
6756                        r.append(' ');
6757                    }
6758                    r.append(a.info.name);
6759                }
6760            }
6761            if (r != null) {
6762                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6763            }
6764
6765            N = pkg.permissionGroups.size();
6766            r = null;
6767            for (i=0; i<N; i++) {
6768                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6769                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6770                if (cur == null) {
6771                    mPermissionGroups.put(pg.info.name, pg);
6772                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6773                        if (r == null) {
6774                            r = new StringBuilder(256);
6775                        } else {
6776                            r.append(' ');
6777                        }
6778                        r.append(pg.info.name);
6779                    }
6780                } else {
6781                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6782                            + pg.info.packageName + " ignored: original from "
6783                            + cur.info.packageName);
6784                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6785                        if (r == null) {
6786                            r = new StringBuilder(256);
6787                        } else {
6788                            r.append(' ');
6789                        }
6790                        r.append("DUP:");
6791                        r.append(pg.info.name);
6792                    }
6793                }
6794            }
6795            if (r != null) {
6796                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6797            }
6798
6799            N = pkg.permissions.size();
6800            r = null;
6801            for (i=0; i<N; i++) {
6802                PackageParser.Permission p = pkg.permissions.get(i);
6803
6804                // Now that permission groups have a special meaning, we ignore permission
6805                // groups for legacy apps to prevent unexpected behavior. In particular,
6806                // permissions for one app being granted to someone just becuase they happen
6807                // to be in a group defined by another app (before this had no implications).
6808                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6809                    p.group = mPermissionGroups.get(p.info.group);
6810                    // Warn for a permission in an unknown group.
6811                    if (p.info.group != null && p.group == null) {
6812                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6813                                + p.info.packageName + " in an unknown group " + p.info.group);
6814                    }
6815                }
6816
6817                ArrayMap<String, BasePermission> permissionMap =
6818                        p.tree ? mSettings.mPermissionTrees
6819                                : mSettings.mPermissions;
6820                BasePermission bp = permissionMap.get(p.info.name);
6821
6822                // Allow system apps to redefine non-system permissions
6823                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6824                    final boolean currentOwnerIsSystem = (bp.perm != null
6825                            && isSystemApp(bp.perm.owner));
6826                    if (isSystemApp(p.owner)) {
6827                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6828                            // It's a built-in permission and no owner, take ownership now
6829                            bp.packageSetting = pkgSetting;
6830                            bp.perm = p;
6831                            bp.uid = pkg.applicationInfo.uid;
6832                            bp.sourcePackage = p.info.packageName;
6833                        } else if (!currentOwnerIsSystem) {
6834                            String msg = "New decl " + p.owner + " of permission  "
6835                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6836                            reportSettingsProblem(Log.WARN, msg);
6837                            bp = null;
6838                        }
6839                    }
6840                }
6841
6842                if (bp == null) {
6843                    bp = new BasePermission(p.info.name, p.info.packageName,
6844                            BasePermission.TYPE_NORMAL);
6845                    permissionMap.put(p.info.name, bp);
6846                }
6847
6848                if (bp.perm == null) {
6849                    if (bp.sourcePackage == null
6850                            || bp.sourcePackage.equals(p.info.packageName)) {
6851                        BasePermission tree = findPermissionTreeLP(p.info.name);
6852                        if (tree == null
6853                                || tree.sourcePackage.equals(p.info.packageName)) {
6854                            bp.packageSetting = pkgSetting;
6855                            bp.perm = p;
6856                            bp.uid = pkg.applicationInfo.uid;
6857                            bp.sourcePackage = p.info.packageName;
6858                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6859                                if (r == null) {
6860                                    r = new StringBuilder(256);
6861                                } else {
6862                                    r.append(' ');
6863                                }
6864                                r.append(p.info.name);
6865                            }
6866                        } else {
6867                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6868                                    + p.info.packageName + " ignored: base tree "
6869                                    + tree.name + " is from package "
6870                                    + tree.sourcePackage);
6871                        }
6872                    } else {
6873                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6874                                + p.info.packageName + " ignored: original from "
6875                                + bp.sourcePackage);
6876                    }
6877                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6878                    if (r == null) {
6879                        r = new StringBuilder(256);
6880                    } else {
6881                        r.append(' ');
6882                    }
6883                    r.append("DUP:");
6884                    r.append(p.info.name);
6885                }
6886                if (bp.perm == p) {
6887                    bp.protectionLevel = p.info.protectionLevel;
6888                }
6889            }
6890
6891            if (r != null) {
6892                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6893            }
6894
6895            N = pkg.instrumentation.size();
6896            r = null;
6897            for (i=0; i<N; i++) {
6898                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6899                a.info.packageName = pkg.applicationInfo.packageName;
6900                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6901                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6902                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6903                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6904                a.info.dataDir = pkg.applicationInfo.dataDir;
6905
6906                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6907                // need other information about the application, like the ABI and what not ?
6908                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6909                mInstrumentation.put(a.getComponentName(), a);
6910                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6911                    if (r == null) {
6912                        r = new StringBuilder(256);
6913                    } else {
6914                        r.append(' ');
6915                    }
6916                    r.append(a.info.name);
6917                }
6918            }
6919            if (r != null) {
6920                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6921            }
6922
6923            if (pkg.protectedBroadcasts != null) {
6924                N = pkg.protectedBroadcasts.size();
6925                for (i=0; i<N; i++) {
6926                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6927                }
6928            }
6929
6930            pkgSetting.setTimeStamp(scanFileTime);
6931
6932            // Create idmap files for pairs of (packages, overlay packages).
6933            // Note: "android", ie framework-res.apk, is handled by native layers.
6934            if (pkg.mOverlayTarget != null) {
6935                // This is an overlay package.
6936                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6937                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6938                        mOverlays.put(pkg.mOverlayTarget,
6939                                new ArrayMap<String, PackageParser.Package>());
6940                    }
6941                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6942                    map.put(pkg.packageName, pkg);
6943                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6944                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6945                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6946                                "scanPackageLI failed to createIdmap");
6947                    }
6948                }
6949            } else if (mOverlays.containsKey(pkg.packageName) &&
6950                    !pkg.packageName.equals("android")) {
6951                // This is a regular package, with one or more known overlay packages.
6952                createIdmapsForPackageLI(pkg);
6953            }
6954        }
6955
6956        return pkg;
6957    }
6958
6959    /**
6960     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6961     * is derived purely on the basis of the contents of {@code scanFile} and
6962     * {@code cpuAbiOverride}.
6963     *
6964     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6965     */
6966    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
6967                                 String cpuAbiOverride, boolean extractLibs)
6968            throws PackageManagerException {
6969        // TODO: We can probably be smarter about this stuff. For installed apps,
6970        // we can calculate this information at install time once and for all. For
6971        // system apps, we can probably assume that this information doesn't change
6972        // after the first boot scan. As things stand, we do lots of unnecessary work.
6973
6974        // Give ourselves some initial paths; we'll come back for another
6975        // pass once we've determined ABI below.
6976        setNativeLibraryPaths(pkg);
6977
6978        // We would never need to extract libs for forward-locked and external packages,
6979        // since the container service will do it for us. We shouldn't attempt to
6980        // extract libs from system app when it was not updated.
6981        if (pkg.isForwardLocked() || isExternal(pkg) ||
6982            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
6983            extractLibs = false;
6984        }
6985
6986        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6987        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6988
6989        NativeLibraryHelper.Handle handle = null;
6990        try {
6991            handle = NativeLibraryHelper.Handle.create(scanFile);
6992            // TODO(multiArch): This can be null for apps that didn't go through the
6993            // usual installation process. We can calculate it again, like we
6994            // do during install time.
6995            //
6996            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6997            // unnecessary.
6998            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6999
7000            // Null out the abis so that they can be recalculated.
7001            pkg.applicationInfo.primaryCpuAbi = null;
7002            pkg.applicationInfo.secondaryCpuAbi = null;
7003            if (isMultiArch(pkg.applicationInfo)) {
7004                // Warn if we've set an abiOverride for multi-lib packages..
7005                // By definition, we need to copy both 32 and 64 bit libraries for
7006                // such packages.
7007                if (pkg.cpuAbiOverride != null
7008                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7009                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7010                }
7011
7012                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7013                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7014                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7015                    if (extractLibs) {
7016                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7017                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7018                                useIsaSpecificSubdirs);
7019                    } else {
7020                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7021                    }
7022                }
7023
7024                maybeThrowExceptionForMultiArchCopy(
7025                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7026
7027                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7028                    if (extractLibs) {
7029                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7030                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7031                                useIsaSpecificSubdirs);
7032                    } else {
7033                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7034                    }
7035                }
7036
7037                maybeThrowExceptionForMultiArchCopy(
7038                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7039
7040                if (abi64 >= 0) {
7041                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7042                }
7043
7044                if (abi32 >= 0) {
7045                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7046                    if (abi64 >= 0) {
7047                        pkg.applicationInfo.secondaryCpuAbi = abi;
7048                    } else {
7049                        pkg.applicationInfo.primaryCpuAbi = abi;
7050                    }
7051                }
7052            } else {
7053                String[] abiList = (cpuAbiOverride != null) ?
7054                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7055
7056                // Enable gross and lame hacks for apps that are built with old
7057                // SDK tools. We must scan their APKs for renderscript bitcode and
7058                // not launch them if it's present. Don't bother checking on devices
7059                // that don't have 64 bit support.
7060                boolean needsRenderScriptOverride = false;
7061                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7062                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7063                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7064                    needsRenderScriptOverride = true;
7065                }
7066
7067                final int copyRet;
7068                if (extractLibs) {
7069                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7070                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7071                } else {
7072                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7073                }
7074
7075                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7076                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7077                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7078                }
7079
7080                if (copyRet >= 0) {
7081                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7082                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7083                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7084                } else if (needsRenderScriptOverride) {
7085                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7086                }
7087            }
7088        } catch (IOException ioe) {
7089            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7090        } finally {
7091            IoUtils.closeQuietly(handle);
7092        }
7093
7094        // Now that we've calculated the ABIs and determined if it's an internal app,
7095        // we will go ahead and populate the nativeLibraryPath.
7096        setNativeLibraryPaths(pkg);
7097    }
7098
7099    /**
7100     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7101     * i.e, so that all packages can be run inside a single process if required.
7102     *
7103     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7104     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7105     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7106     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7107     * updating a package that belongs to a shared user.
7108     *
7109     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7110     * adds unnecessary complexity.
7111     */
7112    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7113            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7114        String requiredInstructionSet = null;
7115        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7116            requiredInstructionSet = VMRuntime.getInstructionSet(
7117                     scannedPackage.applicationInfo.primaryCpuAbi);
7118        }
7119
7120        PackageSetting requirer = null;
7121        for (PackageSetting ps : packagesForUser) {
7122            // If packagesForUser contains scannedPackage, we skip it. This will happen
7123            // when scannedPackage is an update of an existing package. Without this check,
7124            // we will never be able to change the ABI of any package belonging to a shared
7125            // user, even if it's compatible with other packages.
7126            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7127                if (ps.primaryCpuAbiString == null) {
7128                    continue;
7129                }
7130
7131                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7132                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7133                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7134                    // this but there's not much we can do.
7135                    String errorMessage = "Instruction set mismatch, "
7136                            + ((requirer == null) ? "[caller]" : requirer)
7137                            + " requires " + requiredInstructionSet + " whereas " + ps
7138                            + " requires " + instructionSet;
7139                    Slog.w(TAG, errorMessage);
7140                }
7141
7142                if (requiredInstructionSet == null) {
7143                    requiredInstructionSet = instructionSet;
7144                    requirer = ps;
7145                }
7146            }
7147        }
7148
7149        if (requiredInstructionSet != null) {
7150            String adjustedAbi;
7151            if (requirer != null) {
7152                // requirer != null implies that either scannedPackage was null or that scannedPackage
7153                // did not require an ABI, in which case we have to adjust scannedPackage to match
7154                // the ABI of the set (which is the same as requirer's ABI)
7155                adjustedAbi = requirer.primaryCpuAbiString;
7156                if (scannedPackage != null) {
7157                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7158                }
7159            } else {
7160                // requirer == null implies that we're updating all ABIs in the set to
7161                // match scannedPackage.
7162                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7163            }
7164
7165            for (PackageSetting ps : packagesForUser) {
7166                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7167                    if (ps.primaryCpuAbiString != null) {
7168                        continue;
7169                    }
7170
7171                    ps.primaryCpuAbiString = adjustedAbi;
7172                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7173                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7174                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7175
7176                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7177                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7178                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7179                            ps.primaryCpuAbiString = null;
7180                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7181                            return;
7182                        } else {
7183                            mInstaller.rmdex(ps.codePathString,
7184                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7185                        }
7186                    }
7187                }
7188            }
7189        }
7190    }
7191
7192    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7193        synchronized (mPackages) {
7194            mResolverReplaced = true;
7195            // Set up information for custom user intent resolution activity.
7196            mResolveActivity.applicationInfo = pkg.applicationInfo;
7197            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7198            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7199            mResolveActivity.processName = pkg.applicationInfo.packageName;
7200            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7201            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7202                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7203            mResolveActivity.theme = 0;
7204            mResolveActivity.exported = true;
7205            mResolveActivity.enabled = true;
7206            mResolveInfo.activityInfo = mResolveActivity;
7207            mResolveInfo.priority = 0;
7208            mResolveInfo.preferredOrder = 0;
7209            mResolveInfo.match = 0;
7210            mResolveComponentName = mCustomResolverComponentName;
7211            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7212                    mResolveComponentName);
7213        }
7214    }
7215
7216    private static String calculateBundledApkRoot(final String codePathString) {
7217        final File codePath = new File(codePathString);
7218        final File codeRoot;
7219        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7220            codeRoot = Environment.getRootDirectory();
7221        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7222            codeRoot = Environment.getOemDirectory();
7223        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7224            codeRoot = Environment.getVendorDirectory();
7225        } else {
7226            // Unrecognized code path; take its top real segment as the apk root:
7227            // e.g. /something/app/blah.apk => /something
7228            try {
7229                File f = codePath.getCanonicalFile();
7230                File parent = f.getParentFile();    // non-null because codePath is a file
7231                File tmp;
7232                while ((tmp = parent.getParentFile()) != null) {
7233                    f = parent;
7234                    parent = tmp;
7235                }
7236                codeRoot = f;
7237                Slog.w(TAG, "Unrecognized code path "
7238                        + codePath + " - using " + codeRoot);
7239            } catch (IOException e) {
7240                // Can't canonicalize the code path -- shenanigans?
7241                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7242                return Environment.getRootDirectory().getPath();
7243            }
7244        }
7245        return codeRoot.getPath();
7246    }
7247
7248    /**
7249     * Derive and set the location of native libraries for the given package,
7250     * which varies depending on where and how the package was installed.
7251     */
7252    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7253        final ApplicationInfo info = pkg.applicationInfo;
7254        final String codePath = pkg.codePath;
7255        final File codeFile = new File(codePath);
7256        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7257        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7258
7259        info.nativeLibraryRootDir = null;
7260        info.nativeLibraryRootRequiresIsa = false;
7261        info.nativeLibraryDir = null;
7262        info.secondaryNativeLibraryDir = null;
7263
7264        if (isApkFile(codeFile)) {
7265            // Monolithic install
7266            if (bundledApp) {
7267                // If "/system/lib64/apkname" exists, assume that is the per-package
7268                // native library directory to use; otherwise use "/system/lib/apkname".
7269                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7270                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7271                        getPrimaryInstructionSet(info));
7272
7273                // This is a bundled system app so choose the path based on the ABI.
7274                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7275                // is just the default path.
7276                final String apkName = deriveCodePathName(codePath);
7277                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7278                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7279                        apkName).getAbsolutePath();
7280
7281                if (info.secondaryCpuAbi != null) {
7282                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7283                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7284                            secondaryLibDir, apkName).getAbsolutePath();
7285                }
7286            } else if (asecApp) {
7287                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7288                        .getAbsolutePath();
7289            } else {
7290                final String apkName = deriveCodePathName(codePath);
7291                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7292                        .getAbsolutePath();
7293            }
7294
7295            info.nativeLibraryRootRequiresIsa = false;
7296            info.nativeLibraryDir = info.nativeLibraryRootDir;
7297        } else {
7298            // Cluster install
7299            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7300            info.nativeLibraryRootRequiresIsa = true;
7301
7302            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7303                    getPrimaryInstructionSet(info)).getAbsolutePath();
7304
7305            if (info.secondaryCpuAbi != null) {
7306                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7307                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7308            }
7309        }
7310    }
7311
7312    /**
7313     * Calculate the abis and roots for a bundled app. These can uniquely
7314     * be determined from the contents of the system partition, i.e whether
7315     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7316     * of this information, and instead assume that the system was built
7317     * sensibly.
7318     */
7319    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7320                                           PackageSetting pkgSetting) {
7321        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7322
7323        // If "/system/lib64/apkname" exists, assume that is the per-package
7324        // native library directory to use; otherwise use "/system/lib/apkname".
7325        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7326        setBundledAppAbi(pkg, apkRoot, apkName);
7327        // pkgSetting might be null during rescan following uninstall of updates
7328        // to a bundled app, so accommodate that possibility.  The settings in
7329        // that case will be established later from the parsed package.
7330        //
7331        // If the settings aren't null, sync them up with what we've just derived.
7332        // note that apkRoot isn't stored in the package settings.
7333        if (pkgSetting != null) {
7334            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7335            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7336        }
7337    }
7338
7339    /**
7340     * Deduces the ABI of a bundled app and sets the relevant fields on the
7341     * parsed pkg object.
7342     *
7343     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7344     *        under which system libraries are installed.
7345     * @param apkName the name of the installed package.
7346     */
7347    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7348        final File codeFile = new File(pkg.codePath);
7349
7350        final boolean has64BitLibs;
7351        final boolean has32BitLibs;
7352        if (isApkFile(codeFile)) {
7353            // Monolithic install
7354            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7355            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7356        } else {
7357            // Cluster install
7358            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7359            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7360                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7361                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7362                has64BitLibs = (new File(rootDir, isa)).exists();
7363            } else {
7364                has64BitLibs = false;
7365            }
7366            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7367                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7368                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7369                has32BitLibs = (new File(rootDir, isa)).exists();
7370            } else {
7371                has32BitLibs = false;
7372            }
7373        }
7374
7375        if (has64BitLibs && !has32BitLibs) {
7376            // The package has 64 bit libs, but not 32 bit libs. Its primary
7377            // ABI should be 64 bit. We can safely assume here that the bundled
7378            // native libraries correspond to the most preferred ABI in the list.
7379
7380            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7381            pkg.applicationInfo.secondaryCpuAbi = null;
7382        } else if (has32BitLibs && !has64BitLibs) {
7383            // The package has 32 bit libs but not 64 bit libs. Its primary
7384            // ABI should be 32 bit.
7385
7386            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7387            pkg.applicationInfo.secondaryCpuAbi = null;
7388        } else if (has32BitLibs && has64BitLibs) {
7389            // The application has both 64 and 32 bit bundled libraries. We check
7390            // here that the app declares multiArch support, and warn if it doesn't.
7391            //
7392            // We will be lenient here and record both ABIs. The primary will be the
7393            // ABI that's higher on the list, i.e, a device that's configured to prefer
7394            // 64 bit apps will see a 64 bit primary ABI,
7395
7396            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7397                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7398            }
7399
7400            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7401                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7402                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7403            } else {
7404                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7405                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7406            }
7407        } else {
7408            pkg.applicationInfo.primaryCpuAbi = null;
7409            pkg.applicationInfo.secondaryCpuAbi = null;
7410        }
7411    }
7412
7413    private void killApplication(String pkgName, int appId, String reason) {
7414        // Request the ActivityManager to kill the process(only for existing packages)
7415        // so that we do not end up in a confused state while the user is still using the older
7416        // version of the application while the new one gets installed.
7417        IActivityManager am = ActivityManagerNative.getDefault();
7418        if (am != null) {
7419            try {
7420                am.killApplicationWithAppId(pkgName, appId, reason);
7421            } catch (RemoteException e) {
7422            }
7423        }
7424    }
7425
7426    void removePackageLI(PackageSetting ps, boolean chatty) {
7427        if (DEBUG_INSTALL) {
7428            if (chatty)
7429                Log.d(TAG, "Removing package " + ps.name);
7430        }
7431
7432        // writer
7433        synchronized (mPackages) {
7434            mPackages.remove(ps.name);
7435            final PackageParser.Package pkg = ps.pkg;
7436            if (pkg != null) {
7437                cleanPackageDataStructuresLILPw(pkg, chatty);
7438            }
7439        }
7440    }
7441
7442    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7443        if (DEBUG_INSTALL) {
7444            if (chatty)
7445                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7446        }
7447
7448        // writer
7449        synchronized (mPackages) {
7450            mPackages.remove(pkg.applicationInfo.packageName);
7451            cleanPackageDataStructuresLILPw(pkg, chatty);
7452        }
7453    }
7454
7455    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7456        int N = pkg.providers.size();
7457        StringBuilder r = null;
7458        int i;
7459        for (i=0; i<N; i++) {
7460            PackageParser.Provider p = pkg.providers.get(i);
7461            mProviders.removeProvider(p);
7462            if (p.info.authority == null) {
7463
7464                /* There was another ContentProvider with this authority when
7465                 * this app was installed so this authority is null,
7466                 * Ignore it as we don't have to unregister the provider.
7467                 */
7468                continue;
7469            }
7470            String names[] = p.info.authority.split(";");
7471            for (int j = 0; j < names.length; j++) {
7472                if (mProvidersByAuthority.get(names[j]) == p) {
7473                    mProvidersByAuthority.remove(names[j]);
7474                    if (DEBUG_REMOVE) {
7475                        if (chatty)
7476                            Log.d(TAG, "Unregistered content provider: " + names[j]
7477                                    + ", className = " + p.info.name + ", isSyncable = "
7478                                    + p.info.isSyncable);
7479                    }
7480                }
7481            }
7482            if (DEBUG_REMOVE && chatty) {
7483                if (r == null) {
7484                    r = new StringBuilder(256);
7485                } else {
7486                    r.append(' ');
7487                }
7488                r.append(p.info.name);
7489            }
7490        }
7491        if (r != null) {
7492            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7493        }
7494
7495        N = pkg.services.size();
7496        r = null;
7497        for (i=0; i<N; i++) {
7498            PackageParser.Service s = pkg.services.get(i);
7499            mServices.removeService(s);
7500            if (chatty) {
7501                if (r == null) {
7502                    r = new StringBuilder(256);
7503                } else {
7504                    r.append(' ');
7505                }
7506                r.append(s.info.name);
7507            }
7508        }
7509        if (r != null) {
7510            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7511        }
7512
7513        N = pkg.receivers.size();
7514        r = null;
7515        for (i=0; i<N; i++) {
7516            PackageParser.Activity a = pkg.receivers.get(i);
7517            mReceivers.removeActivity(a, "receiver");
7518            if (DEBUG_REMOVE && chatty) {
7519                if (r == null) {
7520                    r = new StringBuilder(256);
7521                } else {
7522                    r.append(' ');
7523                }
7524                r.append(a.info.name);
7525            }
7526        }
7527        if (r != null) {
7528            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7529        }
7530
7531        N = pkg.activities.size();
7532        r = null;
7533        for (i=0; i<N; i++) {
7534            PackageParser.Activity a = pkg.activities.get(i);
7535            mActivities.removeActivity(a, "activity");
7536            if (DEBUG_REMOVE && chatty) {
7537                if (r == null) {
7538                    r = new StringBuilder(256);
7539                } else {
7540                    r.append(' ');
7541                }
7542                r.append(a.info.name);
7543            }
7544        }
7545        if (r != null) {
7546            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7547        }
7548
7549        N = pkg.permissions.size();
7550        r = null;
7551        for (i=0; i<N; i++) {
7552            PackageParser.Permission p = pkg.permissions.get(i);
7553            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7554            if (bp == null) {
7555                bp = mSettings.mPermissionTrees.get(p.info.name);
7556            }
7557            if (bp != null && bp.perm == p) {
7558                bp.perm = null;
7559                if (DEBUG_REMOVE && chatty) {
7560                    if (r == null) {
7561                        r = new StringBuilder(256);
7562                    } else {
7563                        r.append(' ');
7564                    }
7565                    r.append(p.info.name);
7566                }
7567            }
7568            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7569                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7570                if (appOpPerms != null) {
7571                    appOpPerms.remove(pkg.packageName);
7572                }
7573            }
7574        }
7575        if (r != null) {
7576            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7577        }
7578
7579        N = pkg.requestedPermissions.size();
7580        r = null;
7581        for (i=0; i<N; i++) {
7582            String perm = pkg.requestedPermissions.get(i);
7583            BasePermission bp = mSettings.mPermissions.get(perm);
7584            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7585                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7586                if (appOpPerms != null) {
7587                    appOpPerms.remove(pkg.packageName);
7588                    if (appOpPerms.isEmpty()) {
7589                        mAppOpPermissionPackages.remove(perm);
7590                    }
7591                }
7592            }
7593        }
7594        if (r != null) {
7595            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7596        }
7597
7598        N = pkg.instrumentation.size();
7599        r = null;
7600        for (i=0; i<N; i++) {
7601            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7602            mInstrumentation.remove(a.getComponentName());
7603            if (DEBUG_REMOVE && chatty) {
7604                if (r == null) {
7605                    r = new StringBuilder(256);
7606                } else {
7607                    r.append(' ');
7608                }
7609                r.append(a.info.name);
7610            }
7611        }
7612        if (r != null) {
7613            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7614        }
7615
7616        r = null;
7617        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7618            // Only system apps can hold shared libraries.
7619            if (pkg.libraryNames != null) {
7620                for (i=0; i<pkg.libraryNames.size(); i++) {
7621                    String name = pkg.libraryNames.get(i);
7622                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7623                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7624                        mSharedLibraries.remove(name);
7625                        if (DEBUG_REMOVE && chatty) {
7626                            if (r == null) {
7627                                r = new StringBuilder(256);
7628                            } else {
7629                                r.append(' ');
7630                            }
7631                            r.append(name);
7632                        }
7633                    }
7634                }
7635            }
7636        }
7637        if (r != null) {
7638            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7639        }
7640    }
7641
7642    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7643        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7644            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7645                return true;
7646            }
7647        }
7648        return false;
7649    }
7650
7651    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7652    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7653    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7654
7655    private void updatePermissionsLPw(String changingPkg,
7656            PackageParser.Package pkgInfo, int flags) {
7657        // Make sure there are no dangling permission trees.
7658        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7659        while (it.hasNext()) {
7660            final BasePermission bp = it.next();
7661            if (bp.packageSetting == null) {
7662                // We may not yet have parsed the package, so just see if
7663                // we still know about its settings.
7664                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7665            }
7666            if (bp.packageSetting == null) {
7667                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7668                        + " from package " + bp.sourcePackage);
7669                it.remove();
7670            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7671                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7672                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7673                            + " from package " + bp.sourcePackage);
7674                    flags |= UPDATE_PERMISSIONS_ALL;
7675                    it.remove();
7676                }
7677            }
7678        }
7679
7680        // Make sure all dynamic permissions have been assigned to a package,
7681        // and make sure there are no dangling permissions.
7682        it = mSettings.mPermissions.values().iterator();
7683        while (it.hasNext()) {
7684            final BasePermission bp = it.next();
7685            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7686                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7687                        + bp.name + " pkg=" + bp.sourcePackage
7688                        + " info=" + bp.pendingInfo);
7689                if (bp.packageSetting == null && bp.pendingInfo != null) {
7690                    final BasePermission tree = findPermissionTreeLP(bp.name);
7691                    if (tree != null && tree.perm != null) {
7692                        bp.packageSetting = tree.packageSetting;
7693                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7694                                new PermissionInfo(bp.pendingInfo));
7695                        bp.perm.info.packageName = tree.perm.info.packageName;
7696                        bp.perm.info.name = bp.name;
7697                        bp.uid = tree.uid;
7698                    }
7699                }
7700            }
7701            if (bp.packageSetting == null) {
7702                // We may not yet have parsed the package, so just see if
7703                // we still know about its settings.
7704                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7705            }
7706            if (bp.packageSetting == null) {
7707                Slog.w(TAG, "Removing dangling permission: " + bp.name
7708                        + " from package " + bp.sourcePackage);
7709                it.remove();
7710            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7711                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7712                    Slog.i(TAG, "Removing old permission: " + bp.name
7713                            + " from package " + bp.sourcePackage);
7714                    flags |= UPDATE_PERMISSIONS_ALL;
7715                    it.remove();
7716                }
7717            }
7718        }
7719
7720        // Now update the permissions for all packages, in particular
7721        // replace the granted permissions of the system packages.
7722        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7723            for (PackageParser.Package pkg : mPackages.values()) {
7724                if (pkg != pkgInfo) {
7725                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7726                            changingPkg);
7727                }
7728            }
7729        }
7730
7731        if (pkgInfo != null) {
7732            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7733        }
7734    }
7735
7736    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7737            String packageOfInterest) {
7738        // IMPORTANT: There are two types of permissions: install and runtime.
7739        // Install time permissions are granted when the app is installed to
7740        // all device users and users added in the future. Runtime permissions
7741        // are granted at runtime explicitly to specific users. Normal and signature
7742        // protected permissions are install time permissions. Dangerous permissions
7743        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7744        // otherwise they are runtime permissions. This function does not manage
7745        // runtime permissions except for the case an app targeting Lollipop MR1
7746        // being upgraded to target a newer SDK, in which case dangerous permissions
7747        // are transformed from install time to runtime ones.
7748
7749        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7750        if (ps == null) {
7751            return;
7752        }
7753
7754        PermissionsState permissionsState = ps.getPermissionsState();
7755        PermissionsState origPermissions = permissionsState;
7756
7757        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7758
7759        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7760        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7761
7762        boolean changedInstallPermission = false;
7763
7764        if (replace) {
7765            ps.installPermissionsFixed = false;
7766            if (!ps.isSharedUser()) {
7767                origPermissions = new PermissionsState(permissionsState);
7768                permissionsState.reset();
7769            }
7770        }
7771
7772        permissionsState.setGlobalGids(mGlobalGids);
7773
7774        final int N = pkg.requestedPermissions.size();
7775        for (int i=0; i<N; i++) {
7776            final String name = pkg.requestedPermissions.get(i);
7777            final BasePermission bp = mSettings.mPermissions.get(name);
7778
7779            if (DEBUG_INSTALL) {
7780                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7781            }
7782
7783            if (bp == null || bp.packageSetting == null) {
7784                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7785                    Slog.w(TAG, "Unknown permission " + name
7786                            + " in package " + pkg.packageName);
7787                }
7788                continue;
7789            }
7790
7791            final String perm = bp.name;
7792            boolean allowedSig = false;
7793            int grant = GRANT_DENIED;
7794
7795            // Keep track of app op permissions.
7796            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7797                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7798                if (pkgs == null) {
7799                    pkgs = new ArraySet<>();
7800                    mAppOpPermissionPackages.put(bp.name, pkgs);
7801                }
7802                pkgs.add(pkg.packageName);
7803            }
7804
7805            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7806            switch (level) {
7807                case PermissionInfo.PROTECTION_NORMAL: {
7808                    // For all apps normal permissions are install time ones.
7809                    grant = GRANT_INSTALL;
7810                } break;
7811
7812                case PermissionInfo.PROTECTION_DANGEROUS: {
7813                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7814                        // For legacy apps dangerous permissions are install time ones.
7815                        grant = GRANT_INSTALL_LEGACY;
7816                    } else if (ps.isSystem()) {
7817                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7818                        if (origPermissions.hasInstallPermission(bp.name)) {
7819                            // If a system app had an install permission, then the app was
7820                            // upgraded and we grant the permissions as runtime to all users.
7821                            grant = GRANT_UPGRADE;
7822                            upgradeUserIds = currentUserIds;
7823                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7824                            // If users changed since the last permissions update for a
7825                            // system app, we grant the permission as runtime to the new users.
7826                            grant = GRANT_UPGRADE;
7827                            upgradeUserIds = currentUserIds;
7828                            for (int userId : updatedUserIds) {
7829                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7830                            }
7831                        } else {
7832                            // Otherwise, we grant the permission as runtime if the app
7833                            // already had it, i.e. we preserve runtime permissions.
7834                            grant = GRANT_RUNTIME;
7835                        }
7836                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7837                        // For legacy apps that became modern, install becomes runtime.
7838                        grant = GRANT_UPGRADE;
7839                        upgradeUserIds = currentUserIds;
7840                    } else if (replace) {
7841                        // For upgraded modern apps keep runtime permissions unchanged.
7842                        grant = GRANT_RUNTIME;
7843                    }
7844                } break;
7845
7846                case PermissionInfo.PROTECTION_SIGNATURE: {
7847                    // For all apps signature permissions are install time ones.
7848                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7849                    if (allowedSig) {
7850                        grant = GRANT_INSTALL;
7851                    }
7852                } break;
7853            }
7854
7855            if (DEBUG_INSTALL) {
7856                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7857            }
7858
7859            if (grant != GRANT_DENIED) {
7860                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7861                    // If this is an existing, non-system package, then
7862                    // we can't add any new permissions to it.
7863                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7864                        // Except...  if this is a permission that was added
7865                        // to the platform (note: need to only do this when
7866                        // updating the platform).
7867                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7868                            grant = GRANT_DENIED;
7869                        }
7870                    }
7871                }
7872
7873                switch (grant) {
7874                    case GRANT_INSTALL: {
7875                        // Revoke this as runtime permission to handle the case of
7876                        // a runtime permssion being downgraded to an install one.
7877                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7878                            if (origPermissions.getRuntimePermissionState(
7879                                    bp.name, userId) != null) {
7880                                // Revoke the runtime permission and clear the flags.
7881                                origPermissions.revokeRuntimePermission(bp, userId);
7882                                origPermissions.updatePermissionFlags(bp, userId,
7883                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
7884                                // If we revoked a permission permission, we have to write.
7885                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7886                                        changedRuntimePermissionUserIds, userId);
7887                            }
7888                        }
7889                        // Grant an install permission.
7890                        if (permissionsState.grantInstallPermission(bp) !=
7891                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7892                            changedInstallPermission = true;
7893                        }
7894                    } break;
7895
7896                    case GRANT_INSTALL_LEGACY: {
7897                        // Grant an install permission.
7898                        if (permissionsState.grantInstallPermission(bp) !=
7899                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7900                            changedInstallPermission = true;
7901                        }
7902                    } break;
7903
7904                    case GRANT_RUNTIME: {
7905                        // Grant previously granted runtime permissions.
7906                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7907                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7908                                PermissionState permissionState = origPermissions
7909                                        .getRuntimePermissionState(bp.name, userId);
7910                                final int flags = permissionState.getFlags();
7911                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7912                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7913                                    // If we cannot put the permission as it was, we have to write.
7914                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7915                                            changedRuntimePermissionUserIds, userId);
7916                                } else {
7917                                    // System components not only get the permissions but
7918                                    // they are also fixed, so nothing can change that.
7919                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7920                                            ? flags
7921                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7922                                    // Propagate the permission flags.
7923                                    permissionsState.updatePermissionFlags(bp, userId,
7924                                            newFlags, newFlags);
7925                                }
7926                            }
7927                        }
7928                    } break;
7929
7930                    case GRANT_UPGRADE: {
7931                        // Grant runtime permissions for a previously held install permission.
7932                        PermissionState permissionState = origPermissions
7933                                .getInstallPermissionState(bp.name);
7934                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7935
7936                        origPermissions.revokeInstallPermission(bp);
7937                        // We will be transferring the permission flags, so clear them.
7938                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7939                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7940
7941                        // If the permission is not to be promoted to runtime we ignore it and
7942                        // also its other flags as they are not applicable to install permissions.
7943                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7944                            for (int userId : upgradeUserIds) {
7945                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7946                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7947                                    // System components not only get the permissions but
7948                                    // they are also fixed so nothing can change that.
7949                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7950                                            ? flags
7951                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7952                                    // Transfer the permission flags.
7953                                    permissionsState.updatePermissionFlags(bp, userId,
7954                                            newFlags, newFlags);
7955                                    // If we granted the permission, we have to write.
7956                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7957                                            changedRuntimePermissionUserIds, userId);
7958                                }
7959                            }
7960                        }
7961                    } break;
7962
7963                    default: {
7964                        if (packageOfInterest == null
7965                                || packageOfInterest.equals(pkg.packageName)) {
7966                            Slog.w(TAG, "Not granting permission " + perm
7967                                    + " to package " + pkg.packageName
7968                                    + " because it was previously installed without");
7969                        }
7970                    } break;
7971                }
7972            } else {
7973                if (permissionsState.revokeInstallPermission(bp) !=
7974                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7975                    // Also drop the permission flags.
7976                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7977                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7978                    changedInstallPermission = true;
7979                    Slog.i(TAG, "Un-granting permission " + perm
7980                            + " from package " + pkg.packageName
7981                            + " (protectionLevel=" + bp.protectionLevel
7982                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7983                            + ")");
7984                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7985                    // Don't print warning for app op permissions, since it is fine for them
7986                    // not to be granted, there is a UI for the user to decide.
7987                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7988                        Slog.w(TAG, "Not granting permission " + perm
7989                                + " to package " + pkg.packageName
7990                                + " (protectionLevel=" + bp.protectionLevel
7991                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7992                                + ")");
7993                    }
7994                }
7995            }
7996        }
7997
7998        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7999                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8000            // This is the first that we have heard about this package, so the
8001            // permissions we have now selected are fixed until explicitly
8002            // changed.
8003            ps.installPermissionsFixed = true;
8004        }
8005
8006        ps.setPermissionsUpdatedForUserIds(currentUserIds);
8007
8008        // Persist the runtime permissions state for users with changes.
8009        for (int userId : changedRuntimePermissionUserIds) {
8010            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
8011        }
8012    }
8013
8014    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8015        boolean allowed = false;
8016        final int NP = PackageParser.NEW_PERMISSIONS.length;
8017        for (int ip=0; ip<NP; ip++) {
8018            final PackageParser.NewPermissionInfo npi
8019                    = PackageParser.NEW_PERMISSIONS[ip];
8020            if (npi.name.equals(perm)
8021                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8022                allowed = true;
8023                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8024                        + pkg.packageName);
8025                break;
8026            }
8027        }
8028        return allowed;
8029    }
8030
8031    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8032            BasePermission bp, PermissionsState origPermissions) {
8033        boolean allowed;
8034        allowed = (compareSignatures(
8035                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8036                        == PackageManager.SIGNATURE_MATCH)
8037                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8038                        == PackageManager.SIGNATURE_MATCH);
8039        if (!allowed && (bp.protectionLevel
8040                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8041            if (isSystemApp(pkg)) {
8042                // For updated system applications, a system permission
8043                // is granted only if it had been defined by the original application.
8044                if (pkg.isUpdatedSystemApp()) {
8045                    final PackageSetting sysPs = mSettings
8046                            .getDisabledSystemPkgLPr(pkg.packageName);
8047                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8048                        // If the original was granted this permission, we take
8049                        // that grant decision as read and propagate it to the
8050                        // update.
8051                        if (sysPs.isPrivileged()) {
8052                            allowed = true;
8053                        }
8054                    } else {
8055                        // The system apk may have been updated with an older
8056                        // version of the one on the data partition, but which
8057                        // granted a new system permission that it didn't have
8058                        // before.  In this case we do want to allow the app to
8059                        // now get the new permission if the ancestral apk is
8060                        // privileged to get it.
8061                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8062                            for (int j=0;
8063                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8064                                if (perm.equals(
8065                                        sysPs.pkg.requestedPermissions.get(j))) {
8066                                    allowed = true;
8067                                    break;
8068                                }
8069                            }
8070                        }
8071                    }
8072                } else {
8073                    allowed = isPrivilegedApp(pkg);
8074                }
8075            }
8076        }
8077        if (!allowed && (bp.protectionLevel
8078                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8079            // For development permissions, a development permission
8080            // is granted only if it was already granted.
8081            allowed = origPermissions.hasInstallPermission(perm);
8082        }
8083        return allowed;
8084    }
8085
8086    final class ActivityIntentResolver
8087            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8088        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8089                boolean defaultOnly, int userId) {
8090            if (!sUserManager.exists(userId)) return null;
8091            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8092            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8093        }
8094
8095        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8096                int userId) {
8097            if (!sUserManager.exists(userId)) return null;
8098            mFlags = flags;
8099            return super.queryIntent(intent, resolvedType,
8100                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8101        }
8102
8103        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8104                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8105            if (!sUserManager.exists(userId)) return null;
8106            if (packageActivities == null) {
8107                return null;
8108            }
8109            mFlags = flags;
8110            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8111            final int N = packageActivities.size();
8112            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8113                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8114
8115            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8116            for (int i = 0; i < N; ++i) {
8117                intentFilters = packageActivities.get(i).intents;
8118                if (intentFilters != null && intentFilters.size() > 0) {
8119                    PackageParser.ActivityIntentInfo[] array =
8120                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8121                    intentFilters.toArray(array);
8122                    listCut.add(array);
8123                }
8124            }
8125            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8126        }
8127
8128        public final void addActivity(PackageParser.Activity a, String type) {
8129            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8130            mActivities.put(a.getComponentName(), a);
8131            if (DEBUG_SHOW_INFO)
8132                Log.v(
8133                TAG, "  " + type + " " +
8134                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8135            if (DEBUG_SHOW_INFO)
8136                Log.v(TAG, "    Class=" + a.info.name);
8137            final int NI = a.intents.size();
8138            for (int j=0; j<NI; j++) {
8139                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8140                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8141                    intent.setPriority(0);
8142                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8143                            + a.className + " with priority > 0, forcing to 0");
8144                }
8145                if (DEBUG_SHOW_INFO) {
8146                    Log.v(TAG, "    IntentFilter:");
8147                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8148                }
8149                if (!intent.debugCheck()) {
8150                    Log.w(TAG, "==> For Activity " + a.info.name);
8151                }
8152                addFilter(intent);
8153            }
8154        }
8155
8156        public final void removeActivity(PackageParser.Activity a, String type) {
8157            mActivities.remove(a.getComponentName());
8158            if (DEBUG_SHOW_INFO) {
8159                Log.v(TAG, "  " + type + " "
8160                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8161                                : a.info.name) + ":");
8162                Log.v(TAG, "    Class=" + a.info.name);
8163            }
8164            final int NI = a.intents.size();
8165            for (int j=0; j<NI; j++) {
8166                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8167                if (DEBUG_SHOW_INFO) {
8168                    Log.v(TAG, "    IntentFilter:");
8169                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8170                }
8171                removeFilter(intent);
8172            }
8173        }
8174
8175        @Override
8176        protected boolean allowFilterResult(
8177                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8178            ActivityInfo filterAi = filter.activity.info;
8179            for (int i=dest.size()-1; i>=0; i--) {
8180                ActivityInfo destAi = dest.get(i).activityInfo;
8181                if (destAi.name == filterAi.name
8182                        && destAi.packageName == filterAi.packageName) {
8183                    return false;
8184                }
8185            }
8186            return true;
8187        }
8188
8189        @Override
8190        protected ActivityIntentInfo[] newArray(int size) {
8191            return new ActivityIntentInfo[size];
8192        }
8193
8194        @Override
8195        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8196            if (!sUserManager.exists(userId)) return true;
8197            PackageParser.Package p = filter.activity.owner;
8198            if (p != null) {
8199                PackageSetting ps = (PackageSetting)p.mExtras;
8200                if (ps != null) {
8201                    // System apps are never considered stopped for purposes of
8202                    // filtering, because there may be no way for the user to
8203                    // actually re-launch them.
8204                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8205                            && ps.getStopped(userId);
8206                }
8207            }
8208            return false;
8209        }
8210
8211        @Override
8212        protected boolean isPackageForFilter(String packageName,
8213                PackageParser.ActivityIntentInfo info) {
8214            return packageName.equals(info.activity.owner.packageName);
8215        }
8216
8217        @Override
8218        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8219                int match, int userId) {
8220            if (!sUserManager.exists(userId)) return null;
8221            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8222                return null;
8223            }
8224            final PackageParser.Activity activity = info.activity;
8225            if (mSafeMode && (activity.info.applicationInfo.flags
8226                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8227                return null;
8228            }
8229            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8230            if (ps == null) {
8231                return null;
8232            }
8233            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8234                    ps.readUserState(userId), userId);
8235            if (ai == null) {
8236                return null;
8237            }
8238            final ResolveInfo res = new ResolveInfo();
8239            res.activityInfo = ai;
8240            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8241                res.filter = info;
8242            }
8243            if (info != null) {
8244                res.handleAllWebDataURI = info.handleAllWebDataURI();
8245            }
8246            res.priority = info.getPriority();
8247            res.preferredOrder = activity.owner.mPreferredOrder;
8248            //System.out.println("Result: " + res.activityInfo.className +
8249            //                   " = " + res.priority);
8250            res.match = match;
8251            res.isDefault = info.hasDefault;
8252            res.labelRes = info.labelRes;
8253            res.nonLocalizedLabel = info.nonLocalizedLabel;
8254            if (userNeedsBadging(userId)) {
8255                res.noResourceId = true;
8256            } else {
8257                res.icon = info.icon;
8258            }
8259            res.system = res.activityInfo.applicationInfo.isSystemApp();
8260            return res;
8261        }
8262
8263        @Override
8264        protected void sortResults(List<ResolveInfo> results) {
8265            Collections.sort(results, mResolvePrioritySorter);
8266        }
8267
8268        @Override
8269        protected void dumpFilter(PrintWriter out, String prefix,
8270                PackageParser.ActivityIntentInfo filter) {
8271            out.print(prefix); out.print(
8272                    Integer.toHexString(System.identityHashCode(filter.activity)));
8273                    out.print(' ');
8274                    filter.activity.printComponentShortName(out);
8275                    out.print(" filter ");
8276                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8277        }
8278
8279        @Override
8280        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8281            return filter.activity;
8282        }
8283
8284        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8285            PackageParser.Activity activity = (PackageParser.Activity)label;
8286            out.print(prefix); out.print(
8287                    Integer.toHexString(System.identityHashCode(activity)));
8288                    out.print(' ');
8289                    activity.printComponentShortName(out);
8290            if (count > 1) {
8291                out.print(" ("); out.print(count); out.print(" filters)");
8292            }
8293            out.println();
8294        }
8295
8296//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8297//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8298//            final List<ResolveInfo> retList = Lists.newArrayList();
8299//            while (i.hasNext()) {
8300//                final ResolveInfo resolveInfo = i.next();
8301//                if (isEnabledLP(resolveInfo.activityInfo)) {
8302//                    retList.add(resolveInfo);
8303//                }
8304//            }
8305//            return retList;
8306//        }
8307
8308        // Keys are String (activity class name), values are Activity.
8309        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8310                = new ArrayMap<ComponentName, PackageParser.Activity>();
8311        private int mFlags;
8312    }
8313
8314    private final class ServiceIntentResolver
8315            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8316        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8317                boolean defaultOnly, int userId) {
8318            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8319            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8320        }
8321
8322        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8323                int userId) {
8324            if (!sUserManager.exists(userId)) return null;
8325            mFlags = flags;
8326            return super.queryIntent(intent, resolvedType,
8327                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8328        }
8329
8330        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8331                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8332            if (!sUserManager.exists(userId)) return null;
8333            if (packageServices == null) {
8334                return null;
8335            }
8336            mFlags = flags;
8337            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8338            final int N = packageServices.size();
8339            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8340                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8341
8342            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8343            for (int i = 0; i < N; ++i) {
8344                intentFilters = packageServices.get(i).intents;
8345                if (intentFilters != null && intentFilters.size() > 0) {
8346                    PackageParser.ServiceIntentInfo[] array =
8347                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8348                    intentFilters.toArray(array);
8349                    listCut.add(array);
8350                }
8351            }
8352            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8353        }
8354
8355        public final void addService(PackageParser.Service s) {
8356            mServices.put(s.getComponentName(), s);
8357            if (DEBUG_SHOW_INFO) {
8358                Log.v(TAG, "  "
8359                        + (s.info.nonLocalizedLabel != null
8360                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8361                Log.v(TAG, "    Class=" + s.info.name);
8362            }
8363            final int NI = s.intents.size();
8364            int j;
8365            for (j=0; j<NI; j++) {
8366                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8367                if (DEBUG_SHOW_INFO) {
8368                    Log.v(TAG, "    IntentFilter:");
8369                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8370                }
8371                if (!intent.debugCheck()) {
8372                    Log.w(TAG, "==> For Service " + s.info.name);
8373                }
8374                addFilter(intent);
8375            }
8376        }
8377
8378        public final void removeService(PackageParser.Service s) {
8379            mServices.remove(s.getComponentName());
8380            if (DEBUG_SHOW_INFO) {
8381                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8382                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8383                Log.v(TAG, "    Class=" + s.info.name);
8384            }
8385            final int NI = s.intents.size();
8386            int j;
8387            for (j=0; j<NI; j++) {
8388                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8389                if (DEBUG_SHOW_INFO) {
8390                    Log.v(TAG, "    IntentFilter:");
8391                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8392                }
8393                removeFilter(intent);
8394            }
8395        }
8396
8397        @Override
8398        protected boolean allowFilterResult(
8399                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8400            ServiceInfo filterSi = filter.service.info;
8401            for (int i=dest.size()-1; i>=0; i--) {
8402                ServiceInfo destAi = dest.get(i).serviceInfo;
8403                if (destAi.name == filterSi.name
8404                        && destAi.packageName == filterSi.packageName) {
8405                    return false;
8406                }
8407            }
8408            return true;
8409        }
8410
8411        @Override
8412        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8413            return new PackageParser.ServiceIntentInfo[size];
8414        }
8415
8416        @Override
8417        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8418            if (!sUserManager.exists(userId)) return true;
8419            PackageParser.Package p = filter.service.owner;
8420            if (p != null) {
8421                PackageSetting ps = (PackageSetting)p.mExtras;
8422                if (ps != null) {
8423                    // System apps are never considered stopped for purposes of
8424                    // filtering, because there may be no way for the user to
8425                    // actually re-launch them.
8426                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8427                            && ps.getStopped(userId);
8428                }
8429            }
8430            return false;
8431        }
8432
8433        @Override
8434        protected boolean isPackageForFilter(String packageName,
8435                PackageParser.ServiceIntentInfo info) {
8436            return packageName.equals(info.service.owner.packageName);
8437        }
8438
8439        @Override
8440        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8441                int match, int userId) {
8442            if (!sUserManager.exists(userId)) return null;
8443            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8444            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8445                return null;
8446            }
8447            final PackageParser.Service service = info.service;
8448            if (mSafeMode && (service.info.applicationInfo.flags
8449                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8450                return null;
8451            }
8452            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8453            if (ps == null) {
8454                return null;
8455            }
8456            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8457                    ps.readUserState(userId), userId);
8458            if (si == null) {
8459                return null;
8460            }
8461            final ResolveInfo res = new ResolveInfo();
8462            res.serviceInfo = si;
8463            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8464                res.filter = filter;
8465            }
8466            res.priority = info.getPriority();
8467            res.preferredOrder = service.owner.mPreferredOrder;
8468            res.match = match;
8469            res.isDefault = info.hasDefault;
8470            res.labelRes = info.labelRes;
8471            res.nonLocalizedLabel = info.nonLocalizedLabel;
8472            res.icon = info.icon;
8473            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8474            return res;
8475        }
8476
8477        @Override
8478        protected void sortResults(List<ResolveInfo> results) {
8479            Collections.sort(results, mResolvePrioritySorter);
8480        }
8481
8482        @Override
8483        protected void dumpFilter(PrintWriter out, String prefix,
8484                PackageParser.ServiceIntentInfo filter) {
8485            out.print(prefix); out.print(
8486                    Integer.toHexString(System.identityHashCode(filter.service)));
8487                    out.print(' ');
8488                    filter.service.printComponentShortName(out);
8489                    out.print(" filter ");
8490                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8491        }
8492
8493        @Override
8494        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8495            return filter.service;
8496        }
8497
8498        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8499            PackageParser.Service service = (PackageParser.Service)label;
8500            out.print(prefix); out.print(
8501                    Integer.toHexString(System.identityHashCode(service)));
8502                    out.print(' ');
8503                    service.printComponentShortName(out);
8504            if (count > 1) {
8505                out.print(" ("); out.print(count); out.print(" filters)");
8506            }
8507            out.println();
8508        }
8509
8510//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8511//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8512//            final List<ResolveInfo> retList = Lists.newArrayList();
8513//            while (i.hasNext()) {
8514//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8515//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8516//                    retList.add(resolveInfo);
8517//                }
8518//            }
8519//            return retList;
8520//        }
8521
8522        // Keys are String (activity class name), values are Activity.
8523        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8524                = new ArrayMap<ComponentName, PackageParser.Service>();
8525        private int mFlags;
8526    };
8527
8528    private final class ProviderIntentResolver
8529            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8530        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8531                boolean defaultOnly, int userId) {
8532            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8533            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8534        }
8535
8536        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8537                int userId) {
8538            if (!sUserManager.exists(userId))
8539                return null;
8540            mFlags = flags;
8541            return super.queryIntent(intent, resolvedType,
8542                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8543        }
8544
8545        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8546                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8547            if (!sUserManager.exists(userId))
8548                return null;
8549            if (packageProviders == null) {
8550                return null;
8551            }
8552            mFlags = flags;
8553            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8554            final int N = packageProviders.size();
8555            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8556                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8557
8558            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8559            for (int i = 0; i < N; ++i) {
8560                intentFilters = packageProviders.get(i).intents;
8561                if (intentFilters != null && intentFilters.size() > 0) {
8562                    PackageParser.ProviderIntentInfo[] array =
8563                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8564                    intentFilters.toArray(array);
8565                    listCut.add(array);
8566                }
8567            }
8568            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8569        }
8570
8571        public final void addProvider(PackageParser.Provider p) {
8572            if (mProviders.containsKey(p.getComponentName())) {
8573                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8574                return;
8575            }
8576
8577            mProviders.put(p.getComponentName(), p);
8578            if (DEBUG_SHOW_INFO) {
8579                Log.v(TAG, "  "
8580                        + (p.info.nonLocalizedLabel != null
8581                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8582                Log.v(TAG, "    Class=" + p.info.name);
8583            }
8584            final int NI = p.intents.size();
8585            int j;
8586            for (j = 0; j < NI; j++) {
8587                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8588                if (DEBUG_SHOW_INFO) {
8589                    Log.v(TAG, "    IntentFilter:");
8590                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8591                }
8592                if (!intent.debugCheck()) {
8593                    Log.w(TAG, "==> For Provider " + p.info.name);
8594                }
8595                addFilter(intent);
8596            }
8597        }
8598
8599        public final void removeProvider(PackageParser.Provider p) {
8600            mProviders.remove(p.getComponentName());
8601            if (DEBUG_SHOW_INFO) {
8602                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8603                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8604                Log.v(TAG, "    Class=" + p.info.name);
8605            }
8606            final int NI = p.intents.size();
8607            int j;
8608            for (j = 0; j < NI; j++) {
8609                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8610                if (DEBUG_SHOW_INFO) {
8611                    Log.v(TAG, "    IntentFilter:");
8612                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8613                }
8614                removeFilter(intent);
8615            }
8616        }
8617
8618        @Override
8619        protected boolean allowFilterResult(
8620                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8621            ProviderInfo filterPi = filter.provider.info;
8622            for (int i = dest.size() - 1; i >= 0; i--) {
8623                ProviderInfo destPi = dest.get(i).providerInfo;
8624                if (destPi.name == filterPi.name
8625                        && destPi.packageName == filterPi.packageName) {
8626                    return false;
8627                }
8628            }
8629            return true;
8630        }
8631
8632        @Override
8633        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8634            return new PackageParser.ProviderIntentInfo[size];
8635        }
8636
8637        @Override
8638        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8639            if (!sUserManager.exists(userId))
8640                return true;
8641            PackageParser.Package p = filter.provider.owner;
8642            if (p != null) {
8643                PackageSetting ps = (PackageSetting) p.mExtras;
8644                if (ps != null) {
8645                    // System apps are never considered stopped for purposes of
8646                    // filtering, because there may be no way for the user to
8647                    // actually re-launch them.
8648                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8649                            && ps.getStopped(userId);
8650                }
8651            }
8652            return false;
8653        }
8654
8655        @Override
8656        protected boolean isPackageForFilter(String packageName,
8657                PackageParser.ProviderIntentInfo info) {
8658            return packageName.equals(info.provider.owner.packageName);
8659        }
8660
8661        @Override
8662        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8663                int match, int userId) {
8664            if (!sUserManager.exists(userId))
8665                return null;
8666            final PackageParser.ProviderIntentInfo info = filter;
8667            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8668                return null;
8669            }
8670            final PackageParser.Provider provider = info.provider;
8671            if (mSafeMode && (provider.info.applicationInfo.flags
8672                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8673                return null;
8674            }
8675            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8676            if (ps == null) {
8677                return null;
8678            }
8679            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8680                    ps.readUserState(userId), userId);
8681            if (pi == null) {
8682                return null;
8683            }
8684            final ResolveInfo res = new ResolveInfo();
8685            res.providerInfo = pi;
8686            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8687                res.filter = filter;
8688            }
8689            res.priority = info.getPriority();
8690            res.preferredOrder = provider.owner.mPreferredOrder;
8691            res.match = match;
8692            res.isDefault = info.hasDefault;
8693            res.labelRes = info.labelRes;
8694            res.nonLocalizedLabel = info.nonLocalizedLabel;
8695            res.icon = info.icon;
8696            res.system = res.providerInfo.applicationInfo.isSystemApp();
8697            return res;
8698        }
8699
8700        @Override
8701        protected void sortResults(List<ResolveInfo> results) {
8702            Collections.sort(results, mResolvePrioritySorter);
8703        }
8704
8705        @Override
8706        protected void dumpFilter(PrintWriter out, String prefix,
8707                PackageParser.ProviderIntentInfo filter) {
8708            out.print(prefix);
8709            out.print(
8710                    Integer.toHexString(System.identityHashCode(filter.provider)));
8711            out.print(' ');
8712            filter.provider.printComponentShortName(out);
8713            out.print(" filter ");
8714            out.println(Integer.toHexString(System.identityHashCode(filter)));
8715        }
8716
8717        @Override
8718        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8719            return filter.provider;
8720        }
8721
8722        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8723            PackageParser.Provider provider = (PackageParser.Provider)label;
8724            out.print(prefix); out.print(
8725                    Integer.toHexString(System.identityHashCode(provider)));
8726                    out.print(' ');
8727                    provider.printComponentShortName(out);
8728            if (count > 1) {
8729                out.print(" ("); out.print(count); out.print(" filters)");
8730            }
8731            out.println();
8732        }
8733
8734        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8735                = new ArrayMap<ComponentName, PackageParser.Provider>();
8736        private int mFlags;
8737    };
8738
8739    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8740            new Comparator<ResolveInfo>() {
8741        public int compare(ResolveInfo r1, ResolveInfo r2) {
8742            int v1 = r1.priority;
8743            int v2 = r2.priority;
8744            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8745            if (v1 != v2) {
8746                return (v1 > v2) ? -1 : 1;
8747            }
8748            v1 = r1.preferredOrder;
8749            v2 = r2.preferredOrder;
8750            if (v1 != v2) {
8751                return (v1 > v2) ? -1 : 1;
8752            }
8753            if (r1.isDefault != r2.isDefault) {
8754                return r1.isDefault ? -1 : 1;
8755            }
8756            v1 = r1.match;
8757            v2 = r2.match;
8758            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8759            if (v1 != v2) {
8760                return (v1 > v2) ? -1 : 1;
8761            }
8762            if (r1.system != r2.system) {
8763                return r1.system ? -1 : 1;
8764            }
8765            return 0;
8766        }
8767    };
8768
8769    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8770            new Comparator<ProviderInfo>() {
8771        public int compare(ProviderInfo p1, ProviderInfo p2) {
8772            final int v1 = p1.initOrder;
8773            final int v2 = p2.initOrder;
8774            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8775        }
8776    };
8777
8778    final void sendPackageBroadcast(final String action, final String pkg,
8779            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8780            final int[] userIds) {
8781        mHandler.post(new Runnable() {
8782            @Override
8783            public void run() {
8784                try {
8785                    final IActivityManager am = ActivityManagerNative.getDefault();
8786                    if (am == null) return;
8787                    final int[] resolvedUserIds;
8788                    if (userIds == null) {
8789                        resolvedUserIds = am.getRunningUserIds();
8790                    } else {
8791                        resolvedUserIds = userIds;
8792                    }
8793                    for (int id : resolvedUserIds) {
8794                        final Intent intent = new Intent(action,
8795                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8796                        if (extras != null) {
8797                            intent.putExtras(extras);
8798                        }
8799                        if (targetPkg != null) {
8800                            intent.setPackage(targetPkg);
8801                        }
8802                        // Modify the UID when posting to other users
8803                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8804                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8805                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8806                            intent.putExtra(Intent.EXTRA_UID, uid);
8807                        }
8808                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8809                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8810                        if (DEBUG_BROADCASTS) {
8811                            RuntimeException here = new RuntimeException("here");
8812                            here.fillInStackTrace();
8813                            Slog.d(TAG, "Sending to user " + id + ": "
8814                                    + intent.toShortString(false, true, false, false)
8815                                    + " " + intent.getExtras(), here);
8816                        }
8817                        am.broadcastIntent(null, intent, null, finishedReceiver,
8818                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8819                                finishedReceiver != null, false, id);
8820                    }
8821                } catch (RemoteException ex) {
8822                }
8823            }
8824        });
8825    }
8826
8827    /**
8828     * Check if the external storage media is available. This is true if there
8829     * is a mounted external storage medium or if the external storage is
8830     * emulated.
8831     */
8832    private boolean isExternalMediaAvailable() {
8833        return mMediaMounted || Environment.isExternalStorageEmulated();
8834    }
8835
8836    @Override
8837    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8838        // writer
8839        synchronized (mPackages) {
8840            if (!isExternalMediaAvailable()) {
8841                // If the external storage is no longer mounted at this point,
8842                // the caller may not have been able to delete all of this
8843                // packages files and can not delete any more.  Bail.
8844                return null;
8845            }
8846            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8847            if (lastPackage != null) {
8848                pkgs.remove(lastPackage);
8849            }
8850            if (pkgs.size() > 0) {
8851                return pkgs.get(0);
8852            }
8853        }
8854        return null;
8855    }
8856
8857    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8858        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8859                userId, andCode ? 1 : 0, packageName);
8860        if (mSystemReady) {
8861            msg.sendToTarget();
8862        } else {
8863            if (mPostSystemReadyMessages == null) {
8864                mPostSystemReadyMessages = new ArrayList<>();
8865            }
8866            mPostSystemReadyMessages.add(msg);
8867        }
8868    }
8869
8870    void startCleaningPackages() {
8871        // reader
8872        synchronized (mPackages) {
8873            if (!isExternalMediaAvailable()) {
8874                return;
8875            }
8876            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8877                return;
8878            }
8879        }
8880        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8881        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8882        IActivityManager am = ActivityManagerNative.getDefault();
8883        if (am != null) {
8884            try {
8885                am.startService(null, intent, null, UserHandle.USER_OWNER);
8886            } catch (RemoteException e) {
8887            }
8888        }
8889    }
8890
8891    @Override
8892    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8893            int installFlags, String installerPackageName, VerificationParams verificationParams,
8894            String packageAbiOverride) {
8895        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8896                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8897    }
8898
8899    @Override
8900    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8901            int installFlags, String installerPackageName, VerificationParams verificationParams,
8902            String packageAbiOverride, int userId) {
8903        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8904
8905        final int callingUid = Binder.getCallingUid();
8906        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8907
8908        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8909            try {
8910                if (observer != null) {
8911                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8912                }
8913            } catch (RemoteException re) {
8914            }
8915            return;
8916        }
8917
8918        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8919            installFlags |= PackageManager.INSTALL_FROM_ADB;
8920
8921        } else {
8922            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8923            // about installerPackageName.
8924
8925            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8926            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8927        }
8928
8929        UserHandle user;
8930        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8931            user = UserHandle.ALL;
8932        } else {
8933            user = new UserHandle(userId);
8934        }
8935
8936        // Only system components can circumvent runtime permissions when installing.
8937        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8938                && mContext.checkCallingOrSelfPermission(Manifest.permission
8939                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8940            throw new SecurityException("You need the "
8941                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8942                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8943        }
8944
8945        verificationParams.setInstallerUid(callingUid);
8946
8947        final File originFile = new File(originPath);
8948        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8949
8950        final Message msg = mHandler.obtainMessage(INIT_COPY);
8951        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8952                null, verificationParams, user, packageAbiOverride);
8953        mHandler.sendMessage(msg);
8954    }
8955
8956    void installStage(String packageName, File stagedDir, String stagedCid,
8957            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8958            String installerPackageName, int installerUid, UserHandle user) {
8959        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8960                params.referrerUri, installerUid, null);
8961
8962        final OriginInfo origin;
8963        if (stagedDir != null) {
8964            origin = OriginInfo.fromStagedFile(stagedDir);
8965        } else {
8966            origin = OriginInfo.fromStagedContainer(stagedCid);
8967        }
8968
8969        final Message msg = mHandler.obtainMessage(INIT_COPY);
8970        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8971                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8972        mHandler.sendMessage(msg);
8973    }
8974
8975    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8976        Bundle extras = new Bundle(1);
8977        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8978
8979        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8980                packageName, extras, null, null, new int[] {userId});
8981        try {
8982            IActivityManager am = ActivityManagerNative.getDefault();
8983            final boolean isSystem =
8984                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8985            if (isSystem && am.isUserRunning(userId, false)) {
8986                // The just-installed/enabled app is bundled on the system, so presumed
8987                // to be able to run automatically without needing an explicit launch.
8988                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8989                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8990                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8991                        .setPackage(packageName);
8992                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8993                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8994            }
8995        } catch (RemoteException e) {
8996            // shouldn't happen
8997            Slog.w(TAG, "Unable to bootstrap installed package", e);
8998        }
8999    }
9000
9001    @Override
9002    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9003            int userId) {
9004        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9005        PackageSetting pkgSetting;
9006        final int uid = Binder.getCallingUid();
9007        enforceCrossUserPermission(uid, userId, true, true,
9008                "setApplicationHiddenSetting for user " + userId);
9009
9010        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9011            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9012            return false;
9013        }
9014
9015        long callingId = Binder.clearCallingIdentity();
9016        try {
9017            boolean sendAdded = false;
9018            boolean sendRemoved = false;
9019            // writer
9020            synchronized (mPackages) {
9021                pkgSetting = mSettings.mPackages.get(packageName);
9022                if (pkgSetting == null) {
9023                    return false;
9024                }
9025                if (pkgSetting.getHidden(userId) != hidden) {
9026                    pkgSetting.setHidden(hidden, userId);
9027                    mSettings.writePackageRestrictionsLPr(userId);
9028                    if (hidden) {
9029                        sendRemoved = true;
9030                    } else {
9031                        sendAdded = true;
9032                    }
9033                }
9034            }
9035            if (sendAdded) {
9036                sendPackageAddedForUser(packageName, pkgSetting, userId);
9037                return true;
9038            }
9039            if (sendRemoved) {
9040                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9041                        "hiding pkg");
9042                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9043            }
9044        } finally {
9045            Binder.restoreCallingIdentity(callingId);
9046        }
9047        return false;
9048    }
9049
9050    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9051            int userId) {
9052        final PackageRemovedInfo info = new PackageRemovedInfo();
9053        info.removedPackage = packageName;
9054        info.removedUsers = new int[] {userId};
9055        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9056        info.sendBroadcast(false, false, false);
9057    }
9058
9059    /**
9060     * Returns true if application is not found or there was an error. Otherwise it returns
9061     * the hidden state of the package for the given user.
9062     */
9063    @Override
9064    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9065        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9066        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9067                false, "getApplicationHidden for user " + userId);
9068        PackageSetting pkgSetting;
9069        long callingId = Binder.clearCallingIdentity();
9070        try {
9071            // writer
9072            synchronized (mPackages) {
9073                pkgSetting = mSettings.mPackages.get(packageName);
9074                if (pkgSetting == null) {
9075                    return true;
9076                }
9077                return pkgSetting.getHidden(userId);
9078            }
9079        } finally {
9080            Binder.restoreCallingIdentity(callingId);
9081        }
9082    }
9083
9084    /**
9085     * @hide
9086     */
9087    @Override
9088    public int installExistingPackageAsUser(String packageName, int userId) {
9089        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9090                null);
9091        PackageSetting pkgSetting;
9092        final int uid = Binder.getCallingUid();
9093        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9094                + userId);
9095        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9096            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9097        }
9098
9099        long callingId = Binder.clearCallingIdentity();
9100        try {
9101            boolean sendAdded = false;
9102
9103            // writer
9104            synchronized (mPackages) {
9105                pkgSetting = mSettings.mPackages.get(packageName);
9106                if (pkgSetting == null) {
9107                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9108                }
9109                if (!pkgSetting.getInstalled(userId)) {
9110                    pkgSetting.setInstalled(true, userId);
9111                    pkgSetting.setHidden(false, userId);
9112                    mSettings.writePackageRestrictionsLPr(userId);
9113                    sendAdded = true;
9114                }
9115            }
9116
9117            if (sendAdded) {
9118                sendPackageAddedForUser(packageName, pkgSetting, userId);
9119            }
9120        } finally {
9121            Binder.restoreCallingIdentity(callingId);
9122        }
9123
9124        return PackageManager.INSTALL_SUCCEEDED;
9125    }
9126
9127    boolean isUserRestricted(int userId, String restrictionKey) {
9128        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9129        if (restrictions.getBoolean(restrictionKey, false)) {
9130            Log.w(TAG, "User is restricted: " + restrictionKey);
9131            return true;
9132        }
9133        return false;
9134    }
9135
9136    @Override
9137    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9138        mContext.enforceCallingOrSelfPermission(
9139                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9140                "Only package verification agents can verify applications");
9141
9142        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9143        final PackageVerificationResponse response = new PackageVerificationResponse(
9144                verificationCode, Binder.getCallingUid());
9145        msg.arg1 = id;
9146        msg.obj = response;
9147        mHandler.sendMessage(msg);
9148    }
9149
9150    @Override
9151    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9152            long millisecondsToDelay) {
9153        mContext.enforceCallingOrSelfPermission(
9154                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9155                "Only package verification agents can extend verification timeouts");
9156
9157        final PackageVerificationState state = mPendingVerification.get(id);
9158        final PackageVerificationResponse response = new PackageVerificationResponse(
9159                verificationCodeAtTimeout, Binder.getCallingUid());
9160
9161        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9162            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9163        }
9164        if (millisecondsToDelay < 0) {
9165            millisecondsToDelay = 0;
9166        }
9167        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9168                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9169            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9170        }
9171
9172        if ((state != null) && !state.timeoutExtended()) {
9173            state.extendTimeout();
9174
9175            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9176            msg.arg1 = id;
9177            msg.obj = response;
9178            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9179        }
9180    }
9181
9182    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9183            int verificationCode, UserHandle user) {
9184        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9185        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9186        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9187        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9188        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9189
9190        mContext.sendBroadcastAsUser(intent, user,
9191                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9192    }
9193
9194    private ComponentName matchComponentForVerifier(String packageName,
9195            List<ResolveInfo> receivers) {
9196        ActivityInfo targetReceiver = null;
9197
9198        final int NR = receivers.size();
9199        for (int i = 0; i < NR; i++) {
9200            final ResolveInfo info = receivers.get(i);
9201            if (info.activityInfo == null) {
9202                continue;
9203            }
9204
9205            if (packageName.equals(info.activityInfo.packageName)) {
9206                targetReceiver = info.activityInfo;
9207                break;
9208            }
9209        }
9210
9211        if (targetReceiver == null) {
9212            return null;
9213        }
9214
9215        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9216    }
9217
9218    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9219            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9220        if (pkgInfo.verifiers.length == 0) {
9221            return null;
9222        }
9223
9224        final int N = pkgInfo.verifiers.length;
9225        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9226        for (int i = 0; i < N; i++) {
9227            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9228
9229            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9230                    receivers);
9231            if (comp == null) {
9232                continue;
9233            }
9234
9235            final int verifierUid = getUidForVerifier(verifierInfo);
9236            if (verifierUid == -1) {
9237                continue;
9238            }
9239
9240            if (DEBUG_VERIFY) {
9241                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9242                        + " with the correct signature");
9243            }
9244            sufficientVerifiers.add(comp);
9245            verificationState.addSufficientVerifier(verifierUid);
9246        }
9247
9248        return sufficientVerifiers;
9249    }
9250
9251    private int getUidForVerifier(VerifierInfo verifierInfo) {
9252        synchronized (mPackages) {
9253            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9254            if (pkg == null) {
9255                return -1;
9256            } else if (pkg.mSignatures.length != 1) {
9257                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9258                        + " has more than one signature; ignoring");
9259                return -1;
9260            }
9261
9262            /*
9263             * If the public key of the package's signature does not match
9264             * our expected public key, then this is a different package and
9265             * we should skip.
9266             */
9267
9268            final byte[] expectedPublicKey;
9269            try {
9270                final Signature verifierSig = pkg.mSignatures[0];
9271                final PublicKey publicKey = verifierSig.getPublicKey();
9272                expectedPublicKey = publicKey.getEncoded();
9273            } catch (CertificateException e) {
9274                return -1;
9275            }
9276
9277            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9278
9279            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9280                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9281                        + " does not have the expected public key; ignoring");
9282                return -1;
9283            }
9284
9285            return pkg.applicationInfo.uid;
9286        }
9287    }
9288
9289    @Override
9290    public void finishPackageInstall(int token) {
9291        enforceSystemOrRoot("Only the system is allowed to finish installs");
9292
9293        if (DEBUG_INSTALL) {
9294            Slog.v(TAG, "BM finishing package install for " + token);
9295        }
9296
9297        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9298        mHandler.sendMessage(msg);
9299    }
9300
9301    /**
9302     * Get the verification agent timeout.
9303     *
9304     * @return verification timeout in milliseconds
9305     */
9306    private long getVerificationTimeout() {
9307        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9308                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9309                DEFAULT_VERIFICATION_TIMEOUT);
9310    }
9311
9312    /**
9313     * Get the default verification agent response code.
9314     *
9315     * @return default verification response code
9316     */
9317    private int getDefaultVerificationResponse() {
9318        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9319                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9320                DEFAULT_VERIFICATION_RESPONSE);
9321    }
9322
9323    /**
9324     * Check whether or not package verification has been enabled.
9325     *
9326     * @return true if verification should be performed
9327     */
9328    private boolean isVerificationEnabled(int userId, int installFlags) {
9329        if (!DEFAULT_VERIFY_ENABLE) {
9330            return false;
9331        }
9332
9333        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9334
9335        // Check if installing from ADB
9336        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9337            // Do not run verification in a test harness environment
9338            if (ActivityManager.isRunningInTestHarness()) {
9339                return false;
9340            }
9341            if (ensureVerifyAppsEnabled) {
9342                return true;
9343            }
9344            // Check if the developer does not want package verification for ADB installs
9345            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9346                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9347                return false;
9348            }
9349        }
9350
9351        if (ensureVerifyAppsEnabled) {
9352            return true;
9353        }
9354
9355        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9356                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9357    }
9358
9359    @Override
9360    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9361            throws RemoteException {
9362        mContext.enforceCallingOrSelfPermission(
9363                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9364                "Only intentfilter verification agents can verify applications");
9365
9366        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9367        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9368                Binder.getCallingUid(), verificationCode, failedDomains);
9369        msg.arg1 = id;
9370        msg.obj = response;
9371        mHandler.sendMessage(msg);
9372    }
9373
9374    @Override
9375    public int getIntentVerificationStatus(String packageName, int userId) {
9376        synchronized (mPackages) {
9377            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9378        }
9379    }
9380
9381    @Override
9382    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9383        boolean result = false;
9384        synchronized (mPackages) {
9385            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9386        }
9387        if (result) {
9388            scheduleWritePackageRestrictionsLocked(userId);
9389        }
9390        return result;
9391    }
9392
9393    @Override
9394    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9395        synchronized (mPackages) {
9396            return mSettings.getIntentFilterVerificationsLPr(packageName);
9397        }
9398    }
9399
9400    @Override
9401    public List<IntentFilter> getAllIntentFilters(String packageName) {
9402        if (TextUtils.isEmpty(packageName)) {
9403            return Collections.<IntentFilter>emptyList();
9404        }
9405        synchronized (mPackages) {
9406            PackageParser.Package pkg = mPackages.get(packageName);
9407            if (pkg == null || pkg.activities == null) {
9408                return Collections.<IntentFilter>emptyList();
9409            }
9410            final int count = pkg.activities.size();
9411            ArrayList<IntentFilter> result = new ArrayList<>();
9412            for (int n=0; n<count; n++) {
9413                PackageParser.Activity activity = pkg.activities.get(n);
9414                if (activity.intents != null || activity.intents.size() > 0) {
9415                    result.addAll(activity.intents);
9416                }
9417            }
9418            return result;
9419        }
9420    }
9421
9422    @Override
9423    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9424        synchronized (mPackages) {
9425            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9426            if (packageName != null) {
9427                result |= updateIntentVerificationStatus(packageName,
9428                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9429                        UserHandle.myUserId());
9430            }
9431            return result;
9432        }
9433    }
9434
9435    @Override
9436    public String getDefaultBrowserPackageName(int userId) {
9437        synchronized (mPackages) {
9438            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9439        }
9440    }
9441
9442    /**
9443     * Get the "allow unknown sources" setting.
9444     *
9445     * @return the current "allow unknown sources" setting
9446     */
9447    private int getUnknownSourcesSettings() {
9448        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9449                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9450                -1);
9451    }
9452
9453    @Override
9454    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9455        final int uid = Binder.getCallingUid();
9456        // writer
9457        synchronized (mPackages) {
9458            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9459            if (targetPackageSetting == null) {
9460                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9461            }
9462
9463            PackageSetting installerPackageSetting;
9464            if (installerPackageName != null) {
9465                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9466                if (installerPackageSetting == null) {
9467                    throw new IllegalArgumentException("Unknown installer package: "
9468                            + installerPackageName);
9469                }
9470            } else {
9471                installerPackageSetting = null;
9472            }
9473
9474            Signature[] callerSignature;
9475            Object obj = mSettings.getUserIdLPr(uid);
9476            if (obj != null) {
9477                if (obj instanceof SharedUserSetting) {
9478                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9479                } else if (obj instanceof PackageSetting) {
9480                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9481                } else {
9482                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9483                }
9484            } else {
9485                throw new SecurityException("Unknown calling uid " + uid);
9486            }
9487
9488            // Verify: can't set installerPackageName to a package that is
9489            // not signed with the same cert as the caller.
9490            if (installerPackageSetting != null) {
9491                if (compareSignatures(callerSignature,
9492                        installerPackageSetting.signatures.mSignatures)
9493                        != PackageManager.SIGNATURE_MATCH) {
9494                    throw new SecurityException(
9495                            "Caller does not have same cert as new installer package "
9496                            + installerPackageName);
9497                }
9498            }
9499
9500            // Verify: if target already has an installer package, it must
9501            // be signed with the same cert as the caller.
9502            if (targetPackageSetting.installerPackageName != null) {
9503                PackageSetting setting = mSettings.mPackages.get(
9504                        targetPackageSetting.installerPackageName);
9505                // If the currently set package isn't valid, then it's always
9506                // okay to change it.
9507                if (setting != null) {
9508                    if (compareSignatures(callerSignature,
9509                            setting.signatures.mSignatures)
9510                            != PackageManager.SIGNATURE_MATCH) {
9511                        throw new SecurityException(
9512                                "Caller does not have same cert as old installer package "
9513                                + targetPackageSetting.installerPackageName);
9514                    }
9515                }
9516            }
9517
9518            // Okay!
9519            targetPackageSetting.installerPackageName = installerPackageName;
9520            scheduleWriteSettingsLocked();
9521        }
9522    }
9523
9524    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9525        // Queue up an async operation since the package installation may take a little while.
9526        mHandler.post(new Runnable() {
9527            public void run() {
9528                mHandler.removeCallbacks(this);
9529                 // Result object to be returned
9530                PackageInstalledInfo res = new PackageInstalledInfo();
9531                res.returnCode = currentStatus;
9532                res.uid = -1;
9533                res.pkg = null;
9534                res.removedInfo = new PackageRemovedInfo();
9535                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9536                    args.doPreInstall(res.returnCode);
9537                    synchronized (mInstallLock) {
9538                        installPackageLI(args, res);
9539                    }
9540                    args.doPostInstall(res.returnCode, res.uid);
9541                }
9542
9543                // A restore should be performed at this point if (a) the install
9544                // succeeded, (b) the operation is not an update, and (c) the new
9545                // package has not opted out of backup participation.
9546                final boolean update = res.removedInfo.removedPackage != null;
9547                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9548                boolean doRestore = !update
9549                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9550
9551                // Set up the post-install work request bookkeeping.  This will be used
9552                // and cleaned up by the post-install event handling regardless of whether
9553                // there's a restore pass performed.  Token values are >= 1.
9554                int token;
9555                if (mNextInstallToken < 0) mNextInstallToken = 1;
9556                token = mNextInstallToken++;
9557
9558                PostInstallData data = new PostInstallData(args, res);
9559                mRunningInstalls.put(token, data);
9560                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9561
9562                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9563                    // Pass responsibility to the Backup Manager.  It will perform a
9564                    // restore if appropriate, then pass responsibility back to the
9565                    // Package Manager to run the post-install observer callbacks
9566                    // and broadcasts.
9567                    IBackupManager bm = IBackupManager.Stub.asInterface(
9568                            ServiceManager.getService(Context.BACKUP_SERVICE));
9569                    if (bm != null) {
9570                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9571                                + " to BM for possible restore");
9572                        try {
9573                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9574                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9575                            } else {
9576                                doRestore = false;
9577                            }
9578                        } catch (RemoteException e) {
9579                            // can't happen; the backup manager is local
9580                        } catch (Exception e) {
9581                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9582                            doRestore = false;
9583                        }
9584                    } else {
9585                        Slog.e(TAG, "Backup Manager not found!");
9586                        doRestore = false;
9587                    }
9588                }
9589
9590                if (!doRestore) {
9591                    // No restore possible, or the Backup Manager was mysteriously not
9592                    // available -- just fire the post-install work request directly.
9593                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9594                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9595                    mHandler.sendMessage(msg);
9596                }
9597            }
9598        });
9599    }
9600
9601    private abstract class HandlerParams {
9602        private static final int MAX_RETRIES = 4;
9603
9604        /**
9605         * Number of times startCopy() has been attempted and had a non-fatal
9606         * error.
9607         */
9608        private int mRetries = 0;
9609
9610        /** User handle for the user requesting the information or installation. */
9611        private final UserHandle mUser;
9612
9613        HandlerParams(UserHandle user) {
9614            mUser = user;
9615        }
9616
9617        UserHandle getUser() {
9618            return mUser;
9619        }
9620
9621        final boolean startCopy() {
9622            boolean res;
9623            try {
9624                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9625
9626                if (++mRetries > MAX_RETRIES) {
9627                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9628                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9629                    handleServiceError();
9630                    return false;
9631                } else {
9632                    handleStartCopy();
9633                    res = true;
9634                }
9635            } catch (RemoteException e) {
9636                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9637                mHandler.sendEmptyMessage(MCS_RECONNECT);
9638                res = false;
9639            }
9640            handleReturnCode();
9641            return res;
9642        }
9643
9644        final void serviceError() {
9645            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9646            handleServiceError();
9647            handleReturnCode();
9648        }
9649
9650        abstract void handleStartCopy() throws RemoteException;
9651        abstract void handleServiceError();
9652        abstract void handleReturnCode();
9653    }
9654
9655    class MeasureParams extends HandlerParams {
9656        private final PackageStats mStats;
9657        private boolean mSuccess;
9658
9659        private final IPackageStatsObserver mObserver;
9660
9661        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9662            super(new UserHandle(stats.userHandle));
9663            mObserver = observer;
9664            mStats = stats;
9665        }
9666
9667        @Override
9668        public String toString() {
9669            return "MeasureParams{"
9670                + Integer.toHexString(System.identityHashCode(this))
9671                + " " + mStats.packageName + "}";
9672        }
9673
9674        @Override
9675        void handleStartCopy() throws RemoteException {
9676            synchronized (mInstallLock) {
9677                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9678            }
9679
9680            if (mSuccess) {
9681                final boolean mounted;
9682                if (Environment.isExternalStorageEmulated()) {
9683                    mounted = true;
9684                } else {
9685                    final String status = Environment.getExternalStorageState();
9686                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9687                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9688                }
9689
9690                if (mounted) {
9691                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9692
9693                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9694                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9695
9696                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9697                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9698
9699                    // Always subtract cache size, since it's a subdirectory
9700                    mStats.externalDataSize -= mStats.externalCacheSize;
9701
9702                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9703                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9704
9705                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9706                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9707                }
9708            }
9709        }
9710
9711        @Override
9712        void handleReturnCode() {
9713            if (mObserver != null) {
9714                try {
9715                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9716                } catch (RemoteException e) {
9717                    Slog.i(TAG, "Observer no longer exists.");
9718                }
9719            }
9720        }
9721
9722        @Override
9723        void handleServiceError() {
9724            Slog.e(TAG, "Could not measure application " + mStats.packageName
9725                            + " external storage");
9726        }
9727    }
9728
9729    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9730            throws RemoteException {
9731        long result = 0;
9732        for (File path : paths) {
9733            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9734        }
9735        return result;
9736    }
9737
9738    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9739        for (File path : paths) {
9740            try {
9741                mcs.clearDirectory(path.getAbsolutePath());
9742            } catch (RemoteException e) {
9743            }
9744        }
9745    }
9746
9747    static class OriginInfo {
9748        /**
9749         * Location where install is coming from, before it has been
9750         * copied/renamed into place. This could be a single monolithic APK
9751         * file, or a cluster directory. This location may be untrusted.
9752         */
9753        final File file;
9754        final String cid;
9755
9756        /**
9757         * Flag indicating that {@link #file} or {@link #cid} has already been
9758         * staged, meaning downstream users don't need to defensively copy the
9759         * contents.
9760         */
9761        final boolean staged;
9762
9763        /**
9764         * Flag indicating that {@link #file} or {@link #cid} is an already
9765         * installed app that is being moved.
9766         */
9767        final boolean existing;
9768
9769        final String resolvedPath;
9770        final File resolvedFile;
9771
9772        static OriginInfo fromNothing() {
9773            return new OriginInfo(null, null, false, false);
9774        }
9775
9776        static OriginInfo fromUntrustedFile(File file) {
9777            return new OriginInfo(file, null, false, false);
9778        }
9779
9780        static OriginInfo fromExistingFile(File file) {
9781            return new OriginInfo(file, null, false, true);
9782        }
9783
9784        static OriginInfo fromStagedFile(File file) {
9785            return new OriginInfo(file, null, true, false);
9786        }
9787
9788        static OriginInfo fromStagedContainer(String cid) {
9789            return new OriginInfo(null, cid, true, false);
9790        }
9791
9792        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9793            this.file = file;
9794            this.cid = cid;
9795            this.staged = staged;
9796            this.existing = existing;
9797
9798            if (cid != null) {
9799                resolvedPath = PackageHelper.getSdDir(cid);
9800                resolvedFile = new File(resolvedPath);
9801            } else if (file != null) {
9802                resolvedPath = file.getAbsolutePath();
9803                resolvedFile = file;
9804            } else {
9805                resolvedPath = null;
9806                resolvedFile = null;
9807            }
9808        }
9809    }
9810
9811    class MoveInfo {
9812        final int moveId;
9813        final String fromUuid;
9814        final String toUuid;
9815        final String packageName;
9816        final String dataAppName;
9817        final int appId;
9818        final String seinfo;
9819
9820        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9821                String dataAppName, int appId, String seinfo) {
9822            this.moveId = moveId;
9823            this.fromUuid = fromUuid;
9824            this.toUuid = toUuid;
9825            this.packageName = packageName;
9826            this.dataAppName = dataAppName;
9827            this.appId = appId;
9828            this.seinfo = seinfo;
9829        }
9830    }
9831
9832    class InstallParams extends HandlerParams {
9833        final OriginInfo origin;
9834        final MoveInfo move;
9835        final IPackageInstallObserver2 observer;
9836        int installFlags;
9837        final String installerPackageName;
9838        final String volumeUuid;
9839        final VerificationParams verificationParams;
9840        private InstallArgs mArgs;
9841        private int mRet;
9842        final String packageAbiOverride;
9843
9844        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9845                int installFlags, String installerPackageName, String volumeUuid,
9846                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9847            super(user);
9848            this.origin = origin;
9849            this.move = move;
9850            this.observer = observer;
9851            this.installFlags = installFlags;
9852            this.installerPackageName = installerPackageName;
9853            this.volumeUuid = volumeUuid;
9854            this.verificationParams = verificationParams;
9855            this.packageAbiOverride = packageAbiOverride;
9856        }
9857
9858        @Override
9859        public String toString() {
9860            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9861                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9862        }
9863
9864        public ManifestDigest getManifestDigest() {
9865            if (verificationParams == null) {
9866                return null;
9867            }
9868            return verificationParams.getManifestDigest();
9869        }
9870
9871        private int installLocationPolicy(PackageInfoLite pkgLite) {
9872            String packageName = pkgLite.packageName;
9873            int installLocation = pkgLite.installLocation;
9874            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9875            // reader
9876            synchronized (mPackages) {
9877                PackageParser.Package pkg = mPackages.get(packageName);
9878                if (pkg != null) {
9879                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9880                        // Check for downgrading.
9881                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9882                            try {
9883                                checkDowngrade(pkg, pkgLite);
9884                            } catch (PackageManagerException e) {
9885                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9886                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9887                            }
9888                        }
9889                        // Check for updated system application.
9890                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9891                            if (onSd) {
9892                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9893                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9894                            }
9895                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9896                        } else {
9897                            if (onSd) {
9898                                // Install flag overrides everything.
9899                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9900                            }
9901                            // If current upgrade specifies particular preference
9902                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9903                                // Application explicitly specified internal.
9904                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9905                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9906                                // App explictly prefers external. Let policy decide
9907                            } else {
9908                                // Prefer previous location
9909                                if (isExternal(pkg)) {
9910                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9911                                }
9912                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9913                            }
9914                        }
9915                    } else {
9916                        // Invalid install. Return error code
9917                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9918                    }
9919                }
9920            }
9921            // All the special cases have been taken care of.
9922            // Return result based on recommended install location.
9923            if (onSd) {
9924                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9925            }
9926            return pkgLite.recommendedInstallLocation;
9927        }
9928
9929        /*
9930         * Invoke remote method to get package information and install
9931         * location values. Override install location based on default
9932         * policy if needed and then create install arguments based
9933         * on the install location.
9934         */
9935        public void handleStartCopy() throws RemoteException {
9936            int ret = PackageManager.INSTALL_SUCCEEDED;
9937
9938            // If we're already staged, we've firmly committed to an install location
9939            if (origin.staged) {
9940                if (origin.file != null) {
9941                    installFlags |= PackageManager.INSTALL_INTERNAL;
9942                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9943                } else if (origin.cid != null) {
9944                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9945                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9946                } else {
9947                    throw new IllegalStateException("Invalid stage location");
9948                }
9949            }
9950
9951            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9952            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9953
9954            PackageInfoLite pkgLite = null;
9955
9956            if (onInt && onSd) {
9957                // Check if both bits are set.
9958                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9959                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9960            } else {
9961                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9962                        packageAbiOverride);
9963
9964                /*
9965                 * If we have too little free space, try to free cache
9966                 * before giving up.
9967                 */
9968                if (!origin.staged && pkgLite.recommendedInstallLocation
9969                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9970                    // TODO: focus freeing disk space on the target device
9971                    final StorageManager storage = StorageManager.from(mContext);
9972                    final long lowThreshold = storage.getStorageLowBytes(
9973                            Environment.getDataDirectory());
9974
9975                    final long sizeBytes = mContainerService.calculateInstalledSize(
9976                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9977
9978                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9979                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9980                                installFlags, packageAbiOverride);
9981                    }
9982
9983                    /*
9984                     * The cache free must have deleted the file we
9985                     * downloaded to install.
9986                     *
9987                     * TODO: fix the "freeCache" call to not delete
9988                     *       the file we care about.
9989                     */
9990                    if (pkgLite.recommendedInstallLocation
9991                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9992                        pkgLite.recommendedInstallLocation
9993                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9994                    }
9995                }
9996            }
9997
9998            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9999                int loc = pkgLite.recommendedInstallLocation;
10000                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10001                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10002                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10003                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10004                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10005                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10006                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10007                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10008                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10009                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10010                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10011                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10012                } else {
10013                    // Override with defaults if needed.
10014                    loc = installLocationPolicy(pkgLite);
10015                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10016                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10017                    } else if (!onSd && !onInt) {
10018                        // Override install location with flags
10019                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10020                            // Set the flag to install on external media.
10021                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10022                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10023                        } else {
10024                            // Make sure the flag for installing on external
10025                            // media is unset
10026                            installFlags |= PackageManager.INSTALL_INTERNAL;
10027                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10028                        }
10029                    }
10030                }
10031            }
10032
10033            final InstallArgs args = createInstallArgs(this);
10034            mArgs = args;
10035
10036            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10037                 /*
10038                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10039                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10040                 */
10041                int userIdentifier = getUser().getIdentifier();
10042                if (userIdentifier == UserHandle.USER_ALL
10043                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10044                    userIdentifier = UserHandle.USER_OWNER;
10045                }
10046
10047                /*
10048                 * Determine if we have any installed package verifiers. If we
10049                 * do, then we'll defer to them to verify the packages.
10050                 */
10051                final int requiredUid = mRequiredVerifierPackage == null ? -1
10052                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10053                if (!origin.existing && requiredUid != -1
10054                        && isVerificationEnabled(userIdentifier, installFlags)) {
10055                    final Intent verification = new Intent(
10056                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10057                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10058                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10059                            PACKAGE_MIME_TYPE);
10060                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10061
10062                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10063                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10064                            0 /* TODO: Which userId? */);
10065
10066                    if (DEBUG_VERIFY) {
10067                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10068                                + verification.toString() + " with " + pkgLite.verifiers.length
10069                                + " optional verifiers");
10070                    }
10071
10072                    final int verificationId = mPendingVerificationToken++;
10073
10074                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10075
10076                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10077                            installerPackageName);
10078
10079                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10080                            installFlags);
10081
10082                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10083                            pkgLite.packageName);
10084
10085                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10086                            pkgLite.versionCode);
10087
10088                    if (verificationParams != null) {
10089                        if (verificationParams.getVerificationURI() != null) {
10090                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10091                                 verificationParams.getVerificationURI());
10092                        }
10093                        if (verificationParams.getOriginatingURI() != null) {
10094                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10095                                  verificationParams.getOriginatingURI());
10096                        }
10097                        if (verificationParams.getReferrer() != null) {
10098                            verification.putExtra(Intent.EXTRA_REFERRER,
10099                                  verificationParams.getReferrer());
10100                        }
10101                        if (verificationParams.getOriginatingUid() >= 0) {
10102                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10103                                  verificationParams.getOriginatingUid());
10104                        }
10105                        if (verificationParams.getInstallerUid() >= 0) {
10106                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10107                                  verificationParams.getInstallerUid());
10108                        }
10109                    }
10110
10111                    final PackageVerificationState verificationState = new PackageVerificationState(
10112                            requiredUid, args);
10113
10114                    mPendingVerification.append(verificationId, verificationState);
10115
10116                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10117                            receivers, verificationState);
10118
10119                    /*
10120                     * If any sufficient verifiers were listed in the package
10121                     * manifest, attempt to ask them.
10122                     */
10123                    if (sufficientVerifiers != null) {
10124                        final int N = sufficientVerifiers.size();
10125                        if (N == 0) {
10126                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10127                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10128                        } else {
10129                            for (int i = 0; i < N; i++) {
10130                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10131
10132                                final Intent sufficientIntent = new Intent(verification);
10133                                sufficientIntent.setComponent(verifierComponent);
10134
10135                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10136                            }
10137                        }
10138                    }
10139
10140                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10141                            mRequiredVerifierPackage, receivers);
10142                    if (ret == PackageManager.INSTALL_SUCCEEDED
10143                            && mRequiredVerifierPackage != null) {
10144                        /*
10145                         * Send the intent to the required verification agent,
10146                         * but only start the verification timeout after the
10147                         * target BroadcastReceivers have run.
10148                         */
10149                        verification.setComponent(requiredVerifierComponent);
10150                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10151                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10152                                new BroadcastReceiver() {
10153                                    @Override
10154                                    public void onReceive(Context context, Intent intent) {
10155                                        final Message msg = mHandler
10156                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10157                                        msg.arg1 = verificationId;
10158                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10159                                    }
10160                                }, null, 0, null, null);
10161
10162                        /*
10163                         * We don't want the copy to proceed until verification
10164                         * succeeds, so null out this field.
10165                         */
10166                        mArgs = null;
10167                    }
10168                } else {
10169                    /*
10170                     * No package verification is enabled, so immediately start
10171                     * the remote call to initiate copy using temporary file.
10172                     */
10173                    ret = args.copyApk(mContainerService, true);
10174                }
10175            }
10176
10177            mRet = ret;
10178        }
10179
10180        @Override
10181        void handleReturnCode() {
10182            // If mArgs is null, then MCS couldn't be reached. When it
10183            // reconnects, it will try again to install. At that point, this
10184            // will succeed.
10185            if (mArgs != null) {
10186                processPendingInstall(mArgs, mRet);
10187            }
10188        }
10189
10190        @Override
10191        void handleServiceError() {
10192            mArgs = createInstallArgs(this);
10193            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10194        }
10195
10196        public boolean isForwardLocked() {
10197            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10198        }
10199    }
10200
10201    /**
10202     * Used during creation of InstallArgs
10203     *
10204     * @param installFlags package installation flags
10205     * @return true if should be installed on external storage
10206     */
10207    private static boolean installOnExternalAsec(int installFlags) {
10208        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10209            return false;
10210        }
10211        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10212            return true;
10213        }
10214        return false;
10215    }
10216
10217    /**
10218     * Used during creation of InstallArgs
10219     *
10220     * @param installFlags package installation flags
10221     * @return true if should be installed as forward locked
10222     */
10223    private static boolean installForwardLocked(int installFlags) {
10224        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10225    }
10226
10227    private InstallArgs createInstallArgs(InstallParams params) {
10228        if (params.move != null) {
10229            return new MoveInstallArgs(params);
10230        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10231            return new AsecInstallArgs(params);
10232        } else {
10233            return new FileInstallArgs(params);
10234        }
10235    }
10236
10237    /**
10238     * Create args that describe an existing installed package. Typically used
10239     * when cleaning up old installs, or used as a move source.
10240     */
10241    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10242            String resourcePath, String[] instructionSets) {
10243        final boolean isInAsec;
10244        if (installOnExternalAsec(installFlags)) {
10245            /* Apps on SD card are always in ASEC containers. */
10246            isInAsec = true;
10247        } else if (installForwardLocked(installFlags)
10248                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10249            /*
10250             * Forward-locked apps are only in ASEC containers if they're the
10251             * new style
10252             */
10253            isInAsec = true;
10254        } else {
10255            isInAsec = false;
10256        }
10257
10258        if (isInAsec) {
10259            return new AsecInstallArgs(codePath, instructionSets,
10260                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10261        } else {
10262            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10263        }
10264    }
10265
10266    static abstract class InstallArgs {
10267        /** @see InstallParams#origin */
10268        final OriginInfo origin;
10269        /** @see InstallParams#move */
10270        final MoveInfo move;
10271
10272        final IPackageInstallObserver2 observer;
10273        // Always refers to PackageManager flags only
10274        final int installFlags;
10275        final String installerPackageName;
10276        final String volumeUuid;
10277        final ManifestDigest manifestDigest;
10278        final UserHandle user;
10279        final String abiOverride;
10280
10281        // The list of instruction sets supported by this app. This is currently
10282        // only used during the rmdex() phase to clean up resources. We can get rid of this
10283        // if we move dex files under the common app path.
10284        /* nullable */ String[] instructionSets;
10285
10286        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10287                int installFlags, String installerPackageName, String volumeUuid,
10288                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10289                String abiOverride) {
10290            this.origin = origin;
10291            this.move = move;
10292            this.installFlags = installFlags;
10293            this.observer = observer;
10294            this.installerPackageName = installerPackageName;
10295            this.volumeUuid = volumeUuid;
10296            this.manifestDigest = manifestDigest;
10297            this.user = user;
10298            this.instructionSets = instructionSets;
10299            this.abiOverride = abiOverride;
10300        }
10301
10302        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10303        abstract int doPreInstall(int status);
10304
10305        /**
10306         * Rename package into final resting place. All paths on the given
10307         * scanned package should be updated to reflect the rename.
10308         */
10309        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10310        abstract int doPostInstall(int status, int uid);
10311
10312        /** @see PackageSettingBase#codePathString */
10313        abstract String getCodePath();
10314        /** @see PackageSettingBase#resourcePathString */
10315        abstract String getResourcePath();
10316
10317        // Need installer lock especially for dex file removal.
10318        abstract void cleanUpResourcesLI();
10319        abstract boolean doPostDeleteLI(boolean delete);
10320
10321        /**
10322         * Called before the source arguments are copied. This is used mostly
10323         * for MoveParams when it needs to read the source file to put it in the
10324         * destination.
10325         */
10326        int doPreCopy() {
10327            return PackageManager.INSTALL_SUCCEEDED;
10328        }
10329
10330        /**
10331         * Called after the source arguments are copied. This is used mostly for
10332         * MoveParams when it needs to read the source file to put it in the
10333         * destination.
10334         *
10335         * @return
10336         */
10337        int doPostCopy(int uid) {
10338            return PackageManager.INSTALL_SUCCEEDED;
10339        }
10340
10341        protected boolean isFwdLocked() {
10342            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10343        }
10344
10345        protected boolean isExternalAsec() {
10346            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10347        }
10348
10349        UserHandle getUser() {
10350            return user;
10351        }
10352    }
10353
10354    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10355        if (!allCodePaths.isEmpty()) {
10356            if (instructionSets == null) {
10357                throw new IllegalStateException("instructionSet == null");
10358            }
10359            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10360            for (String codePath : allCodePaths) {
10361                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10362                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10363                    if (retCode < 0) {
10364                        Slog.w(TAG, "Couldn't remove dex file for package: "
10365                                + " at location " + codePath + ", retcode=" + retCode);
10366                        // we don't consider this to be a failure of the core package deletion
10367                    }
10368                }
10369            }
10370        }
10371    }
10372
10373    /**
10374     * Logic to handle installation of non-ASEC applications, including copying
10375     * and renaming logic.
10376     */
10377    class FileInstallArgs extends InstallArgs {
10378        private File codeFile;
10379        private File resourceFile;
10380
10381        // Example topology:
10382        // /data/app/com.example/base.apk
10383        // /data/app/com.example/split_foo.apk
10384        // /data/app/com.example/lib/arm/libfoo.so
10385        // /data/app/com.example/lib/arm64/libfoo.so
10386        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10387
10388        /** New install */
10389        FileInstallArgs(InstallParams params) {
10390            super(params.origin, params.move, params.observer, params.installFlags,
10391                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10392                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10393            if (isFwdLocked()) {
10394                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10395            }
10396        }
10397
10398        /** Existing install */
10399        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10400            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10401                    null);
10402            this.codeFile = (codePath != null) ? new File(codePath) : null;
10403            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10404        }
10405
10406        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10407            if (origin.staged) {
10408                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10409                codeFile = origin.file;
10410                resourceFile = origin.file;
10411                return PackageManager.INSTALL_SUCCEEDED;
10412            }
10413
10414            try {
10415                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10416                codeFile = tempDir;
10417                resourceFile = tempDir;
10418            } catch (IOException e) {
10419                Slog.w(TAG, "Failed to create copy file: " + e);
10420                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10421            }
10422
10423            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10424                @Override
10425                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10426                    if (!FileUtils.isValidExtFilename(name)) {
10427                        throw new IllegalArgumentException("Invalid filename: " + name);
10428                    }
10429                    try {
10430                        final File file = new File(codeFile, name);
10431                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10432                                O_RDWR | O_CREAT, 0644);
10433                        Os.chmod(file.getAbsolutePath(), 0644);
10434                        return new ParcelFileDescriptor(fd);
10435                    } catch (ErrnoException e) {
10436                        throw new RemoteException("Failed to open: " + e.getMessage());
10437                    }
10438                }
10439            };
10440
10441            int ret = PackageManager.INSTALL_SUCCEEDED;
10442            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10443            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10444                Slog.e(TAG, "Failed to copy package");
10445                return ret;
10446            }
10447
10448            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10449            NativeLibraryHelper.Handle handle = null;
10450            try {
10451                handle = NativeLibraryHelper.Handle.create(codeFile);
10452                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10453                        abiOverride);
10454            } catch (IOException e) {
10455                Slog.e(TAG, "Copying native libraries failed", e);
10456                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10457            } finally {
10458                IoUtils.closeQuietly(handle);
10459            }
10460
10461            return ret;
10462        }
10463
10464        int doPreInstall(int status) {
10465            if (status != PackageManager.INSTALL_SUCCEEDED) {
10466                cleanUp();
10467            }
10468            return status;
10469        }
10470
10471        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10472            if (status != PackageManager.INSTALL_SUCCEEDED) {
10473                cleanUp();
10474                return false;
10475            }
10476
10477            final File targetDir = codeFile.getParentFile();
10478            final File beforeCodeFile = codeFile;
10479            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10480
10481            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10482            try {
10483                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10484            } catch (ErrnoException e) {
10485                Slog.w(TAG, "Failed to rename", e);
10486                return false;
10487            }
10488
10489            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10490                Slog.w(TAG, "Failed to restorecon");
10491                return false;
10492            }
10493
10494            // Reflect the rename internally
10495            codeFile = afterCodeFile;
10496            resourceFile = afterCodeFile;
10497
10498            // Reflect the rename in scanned details
10499            pkg.codePath = afterCodeFile.getAbsolutePath();
10500            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10501                    pkg.baseCodePath);
10502            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10503                    pkg.splitCodePaths);
10504
10505            // Reflect the rename in app info
10506            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10507            pkg.applicationInfo.setCodePath(pkg.codePath);
10508            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10509            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10510            pkg.applicationInfo.setResourcePath(pkg.codePath);
10511            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10512            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10513
10514            return true;
10515        }
10516
10517        int doPostInstall(int status, int uid) {
10518            if (status != PackageManager.INSTALL_SUCCEEDED) {
10519                cleanUp();
10520            }
10521            return status;
10522        }
10523
10524        @Override
10525        String getCodePath() {
10526            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10527        }
10528
10529        @Override
10530        String getResourcePath() {
10531            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10532        }
10533
10534        private boolean cleanUp() {
10535            if (codeFile == null || !codeFile.exists()) {
10536                return false;
10537            }
10538
10539            if (codeFile.isDirectory()) {
10540                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10541            } else {
10542                codeFile.delete();
10543            }
10544
10545            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10546                resourceFile.delete();
10547            }
10548
10549            return true;
10550        }
10551
10552        void cleanUpResourcesLI() {
10553            // Try enumerating all code paths before deleting
10554            List<String> allCodePaths = Collections.EMPTY_LIST;
10555            if (codeFile != null && codeFile.exists()) {
10556                try {
10557                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10558                    allCodePaths = pkg.getAllCodePaths();
10559                } catch (PackageParserException e) {
10560                    // Ignored; we tried our best
10561                }
10562            }
10563
10564            cleanUp();
10565            removeDexFiles(allCodePaths, instructionSets);
10566        }
10567
10568        boolean doPostDeleteLI(boolean delete) {
10569            // XXX err, shouldn't we respect the delete flag?
10570            cleanUpResourcesLI();
10571            return true;
10572        }
10573    }
10574
10575    private boolean isAsecExternal(String cid) {
10576        final String asecPath = PackageHelper.getSdFilesystem(cid);
10577        return !asecPath.startsWith(mAsecInternalPath);
10578    }
10579
10580    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10581            PackageManagerException {
10582        if (copyRet < 0) {
10583            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10584                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10585                throw new PackageManagerException(copyRet, message);
10586            }
10587        }
10588    }
10589
10590    /**
10591     * Extract the MountService "container ID" from the full code path of an
10592     * .apk.
10593     */
10594    static String cidFromCodePath(String fullCodePath) {
10595        int eidx = fullCodePath.lastIndexOf("/");
10596        String subStr1 = fullCodePath.substring(0, eidx);
10597        int sidx = subStr1.lastIndexOf("/");
10598        return subStr1.substring(sidx+1, eidx);
10599    }
10600
10601    /**
10602     * Logic to handle installation of ASEC applications, including copying and
10603     * renaming logic.
10604     */
10605    class AsecInstallArgs extends InstallArgs {
10606        static final String RES_FILE_NAME = "pkg.apk";
10607        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10608
10609        String cid;
10610        String packagePath;
10611        String resourcePath;
10612
10613        /** New install */
10614        AsecInstallArgs(InstallParams params) {
10615            super(params.origin, params.move, params.observer, params.installFlags,
10616                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10617                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10618        }
10619
10620        /** Existing install */
10621        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10622                        boolean isExternal, boolean isForwardLocked) {
10623            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10624                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10625                    instructionSets, null);
10626            // Hackily pretend we're still looking at a full code path
10627            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10628                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10629            }
10630
10631            // Extract cid from fullCodePath
10632            int eidx = fullCodePath.lastIndexOf("/");
10633            String subStr1 = fullCodePath.substring(0, eidx);
10634            int sidx = subStr1.lastIndexOf("/");
10635            cid = subStr1.substring(sidx+1, eidx);
10636            setMountPath(subStr1);
10637        }
10638
10639        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10640            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10641                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10642                    instructionSets, null);
10643            this.cid = cid;
10644            setMountPath(PackageHelper.getSdDir(cid));
10645        }
10646
10647        void createCopyFile() {
10648            cid = mInstallerService.allocateExternalStageCidLegacy();
10649        }
10650
10651        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10652            if (origin.staged) {
10653                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10654                cid = origin.cid;
10655                setMountPath(PackageHelper.getSdDir(cid));
10656                return PackageManager.INSTALL_SUCCEEDED;
10657            }
10658
10659            if (temp) {
10660                createCopyFile();
10661            } else {
10662                /*
10663                 * Pre-emptively destroy the container since it's destroyed if
10664                 * copying fails due to it existing anyway.
10665                 */
10666                PackageHelper.destroySdDir(cid);
10667            }
10668
10669            final String newMountPath = imcs.copyPackageToContainer(
10670                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10671                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10672
10673            if (newMountPath != null) {
10674                setMountPath(newMountPath);
10675                return PackageManager.INSTALL_SUCCEEDED;
10676            } else {
10677                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10678            }
10679        }
10680
10681        @Override
10682        String getCodePath() {
10683            return packagePath;
10684        }
10685
10686        @Override
10687        String getResourcePath() {
10688            return resourcePath;
10689        }
10690
10691        int doPreInstall(int status) {
10692            if (status != PackageManager.INSTALL_SUCCEEDED) {
10693                // Destroy container
10694                PackageHelper.destroySdDir(cid);
10695            } else {
10696                boolean mounted = PackageHelper.isContainerMounted(cid);
10697                if (!mounted) {
10698                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10699                            Process.SYSTEM_UID);
10700                    if (newMountPath != null) {
10701                        setMountPath(newMountPath);
10702                    } else {
10703                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10704                    }
10705                }
10706            }
10707            return status;
10708        }
10709
10710        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10711            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10712            String newMountPath = null;
10713            if (PackageHelper.isContainerMounted(cid)) {
10714                // Unmount the container
10715                if (!PackageHelper.unMountSdDir(cid)) {
10716                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10717                    return false;
10718                }
10719            }
10720            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10721                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10722                        " which might be stale. Will try to clean up.");
10723                // Clean up the stale container and proceed to recreate.
10724                if (!PackageHelper.destroySdDir(newCacheId)) {
10725                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10726                    return false;
10727                }
10728                // Successfully cleaned up stale container. Try to rename again.
10729                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10730                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10731                            + " inspite of cleaning it up.");
10732                    return false;
10733                }
10734            }
10735            if (!PackageHelper.isContainerMounted(newCacheId)) {
10736                Slog.w(TAG, "Mounting container " + newCacheId);
10737                newMountPath = PackageHelper.mountSdDir(newCacheId,
10738                        getEncryptKey(), Process.SYSTEM_UID);
10739            } else {
10740                newMountPath = PackageHelper.getSdDir(newCacheId);
10741            }
10742            if (newMountPath == null) {
10743                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10744                return false;
10745            }
10746            Log.i(TAG, "Succesfully renamed " + cid +
10747                    " to " + newCacheId +
10748                    " at new path: " + newMountPath);
10749            cid = newCacheId;
10750
10751            final File beforeCodeFile = new File(packagePath);
10752            setMountPath(newMountPath);
10753            final File afterCodeFile = new File(packagePath);
10754
10755            // Reflect the rename in scanned details
10756            pkg.codePath = afterCodeFile.getAbsolutePath();
10757            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10758                    pkg.baseCodePath);
10759            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10760                    pkg.splitCodePaths);
10761
10762            // Reflect the rename in app info
10763            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10764            pkg.applicationInfo.setCodePath(pkg.codePath);
10765            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10766            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10767            pkg.applicationInfo.setResourcePath(pkg.codePath);
10768            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10769            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10770
10771            return true;
10772        }
10773
10774        private void setMountPath(String mountPath) {
10775            final File mountFile = new File(mountPath);
10776
10777            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10778            if (monolithicFile.exists()) {
10779                packagePath = monolithicFile.getAbsolutePath();
10780                if (isFwdLocked()) {
10781                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10782                } else {
10783                    resourcePath = packagePath;
10784                }
10785            } else {
10786                packagePath = mountFile.getAbsolutePath();
10787                resourcePath = packagePath;
10788            }
10789        }
10790
10791        int doPostInstall(int status, int uid) {
10792            if (status != PackageManager.INSTALL_SUCCEEDED) {
10793                cleanUp();
10794            } else {
10795                final int groupOwner;
10796                final String protectedFile;
10797                if (isFwdLocked()) {
10798                    groupOwner = UserHandle.getSharedAppGid(uid);
10799                    protectedFile = RES_FILE_NAME;
10800                } else {
10801                    groupOwner = -1;
10802                    protectedFile = null;
10803                }
10804
10805                if (uid < Process.FIRST_APPLICATION_UID
10806                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10807                    Slog.e(TAG, "Failed to finalize " + cid);
10808                    PackageHelper.destroySdDir(cid);
10809                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10810                }
10811
10812                boolean mounted = PackageHelper.isContainerMounted(cid);
10813                if (!mounted) {
10814                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10815                }
10816            }
10817            return status;
10818        }
10819
10820        private void cleanUp() {
10821            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10822
10823            // Destroy secure container
10824            PackageHelper.destroySdDir(cid);
10825        }
10826
10827        private List<String> getAllCodePaths() {
10828            final File codeFile = new File(getCodePath());
10829            if (codeFile != null && codeFile.exists()) {
10830                try {
10831                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10832                    return pkg.getAllCodePaths();
10833                } catch (PackageParserException e) {
10834                    // Ignored; we tried our best
10835                }
10836            }
10837            return Collections.EMPTY_LIST;
10838        }
10839
10840        void cleanUpResourcesLI() {
10841            // Enumerate all code paths before deleting
10842            cleanUpResourcesLI(getAllCodePaths());
10843        }
10844
10845        private void cleanUpResourcesLI(List<String> allCodePaths) {
10846            cleanUp();
10847            removeDexFiles(allCodePaths, instructionSets);
10848        }
10849
10850        String getPackageName() {
10851            return getAsecPackageName(cid);
10852        }
10853
10854        boolean doPostDeleteLI(boolean delete) {
10855            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10856            final List<String> allCodePaths = getAllCodePaths();
10857            boolean mounted = PackageHelper.isContainerMounted(cid);
10858            if (mounted) {
10859                // Unmount first
10860                if (PackageHelper.unMountSdDir(cid)) {
10861                    mounted = false;
10862                }
10863            }
10864            if (!mounted && delete) {
10865                cleanUpResourcesLI(allCodePaths);
10866            }
10867            return !mounted;
10868        }
10869
10870        @Override
10871        int doPreCopy() {
10872            if (isFwdLocked()) {
10873                if (!PackageHelper.fixSdPermissions(cid,
10874                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10875                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10876                }
10877            }
10878
10879            return PackageManager.INSTALL_SUCCEEDED;
10880        }
10881
10882        @Override
10883        int doPostCopy(int uid) {
10884            if (isFwdLocked()) {
10885                if (uid < Process.FIRST_APPLICATION_UID
10886                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10887                                RES_FILE_NAME)) {
10888                    Slog.e(TAG, "Failed to finalize " + cid);
10889                    PackageHelper.destroySdDir(cid);
10890                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10891                }
10892            }
10893
10894            return PackageManager.INSTALL_SUCCEEDED;
10895        }
10896    }
10897
10898    /**
10899     * Logic to handle movement of existing installed applications.
10900     */
10901    class MoveInstallArgs extends InstallArgs {
10902        private File codeFile;
10903        private File resourceFile;
10904
10905        /** New install */
10906        MoveInstallArgs(InstallParams params) {
10907            super(params.origin, params.move, params.observer, params.installFlags,
10908                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10909                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10910        }
10911
10912        int copyApk(IMediaContainerService imcs, boolean temp) {
10913            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
10914                    + move.fromUuid + " to " + move.toUuid);
10915            synchronized (mInstaller) {
10916                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10917                        move.dataAppName, move.appId, move.seinfo) != 0) {
10918                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10919                }
10920            }
10921
10922            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10923            resourceFile = codeFile;
10924            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
10925
10926            return PackageManager.INSTALL_SUCCEEDED;
10927        }
10928
10929        int doPreInstall(int status) {
10930            if (status != PackageManager.INSTALL_SUCCEEDED) {
10931                cleanUp();
10932            }
10933            return status;
10934        }
10935
10936        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10937            if (status != PackageManager.INSTALL_SUCCEEDED) {
10938                cleanUp();
10939                return false;
10940            }
10941
10942            // Reflect the move in app info
10943            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10944            pkg.applicationInfo.setCodePath(pkg.codePath);
10945            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10946            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10947            pkg.applicationInfo.setResourcePath(pkg.codePath);
10948            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10949            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10950
10951            return true;
10952        }
10953
10954        int doPostInstall(int status, int uid) {
10955            if (status != PackageManager.INSTALL_SUCCEEDED) {
10956                cleanUp();
10957            }
10958            return status;
10959        }
10960
10961        @Override
10962        String getCodePath() {
10963            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10964        }
10965
10966        @Override
10967        String getResourcePath() {
10968            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10969        }
10970
10971        private boolean cleanUp() {
10972            if (codeFile == null || !codeFile.exists()) {
10973                return false;
10974            }
10975
10976            if (codeFile.isDirectory()) {
10977                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10978            } else {
10979                codeFile.delete();
10980            }
10981
10982            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10983                resourceFile.delete();
10984            }
10985
10986            return true;
10987        }
10988
10989        void cleanUpResourcesLI() {
10990            cleanUp();
10991        }
10992
10993        boolean doPostDeleteLI(boolean delete) {
10994            // XXX err, shouldn't we respect the delete flag?
10995            cleanUpResourcesLI();
10996            return true;
10997        }
10998    }
10999
11000    static String getAsecPackageName(String packageCid) {
11001        int idx = packageCid.lastIndexOf("-");
11002        if (idx == -1) {
11003            return packageCid;
11004        }
11005        return packageCid.substring(0, idx);
11006    }
11007
11008    // Utility method used to create code paths based on package name and available index.
11009    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11010        String idxStr = "";
11011        int idx = 1;
11012        // Fall back to default value of idx=1 if prefix is not
11013        // part of oldCodePath
11014        if (oldCodePath != null) {
11015            String subStr = oldCodePath;
11016            // Drop the suffix right away
11017            if (suffix != null && subStr.endsWith(suffix)) {
11018                subStr = subStr.substring(0, subStr.length() - suffix.length());
11019            }
11020            // If oldCodePath already contains prefix find out the
11021            // ending index to either increment or decrement.
11022            int sidx = subStr.lastIndexOf(prefix);
11023            if (sidx != -1) {
11024                subStr = subStr.substring(sidx + prefix.length());
11025                if (subStr != null) {
11026                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11027                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11028                    }
11029                    try {
11030                        idx = Integer.parseInt(subStr);
11031                        if (idx <= 1) {
11032                            idx++;
11033                        } else {
11034                            idx--;
11035                        }
11036                    } catch(NumberFormatException e) {
11037                    }
11038                }
11039            }
11040        }
11041        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11042        return prefix + idxStr;
11043    }
11044
11045    private File getNextCodePath(File targetDir, String packageName) {
11046        int suffix = 1;
11047        File result;
11048        do {
11049            result = new File(targetDir, packageName + "-" + suffix);
11050            suffix++;
11051        } while (result.exists());
11052        return result;
11053    }
11054
11055    // Utility method that returns the relative package path with respect
11056    // to the installation directory. Like say for /data/data/com.test-1.apk
11057    // string com.test-1 is returned.
11058    static String deriveCodePathName(String codePath) {
11059        if (codePath == null) {
11060            return null;
11061        }
11062        final File codeFile = new File(codePath);
11063        final String name = codeFile.getName();
11064        if (codeFile.isDirectory()) {
11065            return name;
11066        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11067            final int lastDot = name.lastIndexOf('.');
11068            return name.substring(0, lastDot);
11069        } else {
11070            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11071            return null;
11072        }
11073    }
11074
11075    class PackageInstalledInfo {
11076        String name;
11077        int uid;
11078        // The set of users that originally had this package installed.
11079        int[] origUsers;
11080        // The set of users that now have this package installed.
11081        int[] newUsers;
11082        PackageParser.Package pkg;
11083        int returnCode;
11084        String returnMsg;
11085        PackageRemovedInfo removedInfo;
11086
11087        public void setError(int code, String msg) {
11088            returnCode = code;
11089            returnMsg = msg;
11090            Slog.w(TAG, msg);
11091        }
11092
11093        public void setError(String msg, PackageParserException e) {
11094            returnCode = e.error;
11095            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11096            Slog.w(TAG, msg, e);
11097        }
11098
11099        public void setError(String msg, PackageManagerException e) {
11100            returnCode = e.error;
11101            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11102            Slog.w(TAG, msg, e);
11103        }
11104
11105        // In some error cases we want to convey more info back to the observer
11106        String origPackage;
11107        String origPermission;
11108    }
11109
11110    /*
11111     * Install a non-existing package.
11112     */
11113    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11114            UserHandle user, String installerPackageName, String volumeUuid,
11115            PackageInstalledInfo res) {
11116        // Remember this for later, in case we need to rollback this install
11117        String pkgName = pkg.packageName;
11118
11119        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11120        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11121                UserHandle.USER_OWNER).exists();
11122        synchronized(mPackages) {
11123            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11124                // A package with the same name is already installed, though
11125                // it has been renamed to an older name.  The package we
11126                // are trying to install should be installed as an update to
11127                // the existing one, but that has not been requested, so bail.
11128                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11129                        + " without first uninstalling package running as "
11130                        + mSettings.mRenamedPackages.get(pkgName));
11131                return;
11132            }
11133            if (mPackages.containsKey(pkgName)) {
11134                // Don't allow installation over an existing package with the same name.
11135                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11136                        + " without first uninstalling.");
11137                return;
11138            }
11139        }
11140
11141        try {
11142            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11143                    System.currentTimeMillis(), user);
11144
11145            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11146            // delete the partially installed application. the data directory will have to be
11147            // restored if it was already existing
11148            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11149                // remove package from internal structures.  Note that we want deletePackageX to
11150                // delete the package data and cache directories that it created in
11151                // scanPackageLocked, unless those directories existed before we even tried to
11152                // install.
11153                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11154                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11155                                res.removedInfo, true);
11156            }
11157
11158        } catch (PackageManagerException e) {
11159            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11160        }
11161    }
11162
11163    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11164        // Upgrade keysets are being used.  Determine if new package has a superset of the
11165        // required keys.
11166        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11167        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11168        for (int i = 0; i < upgradeKeySets.length; i++) {
11169            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11170            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
11171                return true;
11172            }
11173        }
11174        return false;
11175    }
11176
11177    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11178            UserHandle user, String installerPackageName, String volumeUuid,
11179            PackageInstalledInfo res) {
11180        final PackageParser.Package oldPackage;
11181        final String pkgName = pkg.packageName;
11182        final int[] allUsers;
11183        final boolean[] perUserInstalled;
11184        final boolean weFroze;
11185
11186        // First find the old package info and check signatures
11187        synchronized(mPackages) {
11188            oldPackage = mPackages.get(pkgName);
11189            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11190            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11191            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11192                // default to original signature matching
11193                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11194                    != PackageManager.SIGNATURE_MATCH) {
11195                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11196                            "New package has a different signature: " + pkgName);
11197                    return;
11198                }
11199            } else {
11200                if(!checkUpgradeKeySetLP(ps, pkg)) {
11201                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11202                            "New package not signed by keys specified by upgrade-keysets: "
11203                            + pkgName);
11204                    return;
11205                }
11206            }
11207
11208            // In case of rollback, remember per-user/profile install state
11209            allUsers = sUserManager.getUserIds();
11210            perUserInstalled = new boolean[allUsers.length];
11211            for (int i = 0; i < allUsers.length; i++) {
11212                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11213            }
11214
11215            // Mark the app as frozen to prevent launching during the upgrade
11216            // process, and then kill all running instances
11217            if (!ps.frozen) {
11218                ps.frozen = true;
11219                weFroze = true;
11220            } else {
11221                weFroze = false;
11222            }
11223        }
11224
11225        // Now that we're guarded by frozen state, kill app during upgrade
11226        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11227
11228        try {
11229            boolean sysPkg = (isSystemApp(oldPackage));
11230            if (sysPkg) {
11231                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11232                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11233            } else {
11234                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11235                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11236            }
11237        } finally {
11238            // Regardless of success or failure of upgrade steps above, always
11239            // unfreeze the package if we froze it
11240            if (weFroze) {
11241                unfreezePackage(pkgName);
11242            }
11243        }
11244    }
11245
11246    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11247            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11248            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11249            String volumeUuid, PackageInstalledInfo res) {
11250        String pkgName = deletedPackage.packageName;
11251        boolean deletedPkg = true;
11252        boolean updatedSettings = false;
11253
11254        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11255                + deletedPackage);
11256        long origUpdateTime;
11257        if (pkg.mExtras != null) {
11258            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11259        } else {
11260            origUpdateTime = 0;
11261        }
11262
11263        // First delete the existing package while retaining the data directory
11264        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11265                res.removedInfo, true)) {
11266            // If the existing package wasn't successfully deleted
11267            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11268            deletedPkg = false;
11269        } else {
11270            // Successfully deleted the old package; proceed with replace.
11271
11272            // If deleted package lived in a container, give users a chance to
11273            // relinquish resources before killing.
11274            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11275                if (DEBUG_INSTALL) {
11276                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11277                }
11278                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11279                final ArrayList<String> pkgList = new ArrayList<String>(1);
11280                pkgList.add(deletedPackage.applicationInfo.packageName);
11281                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11282            }
11283
11284            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11285            try {
11286                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11287                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11288                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11289                        perUserInstalled, res, user);
11290                updatedSettings = true;
11291            } catch (PackageManagerException e) {
11292                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11293            }
11294        }
11295
11296        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11297            // remove package from internal structures.  Note that we want deletePackageX to
11298            // delete the package data and cache directories that it created in
11299            // scanPackageLocked, unless those directories existed before we even tried to
11300            // install.
11301            if(updatedSettings) {
11302                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11303                deletePackageLI(
11304                        pkgName, null, true, allUsers, perUserInstalled,
11305                        PackageManager.DELETE_KEEP_DATA,
11306                                res.removedInfo, true);
11307            }
11308            // Since we failed to install the new package we need to restore the old
11309            // package that we deleted.
11310            if (deletedPkg) {
11311                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11312                File restoreFile = new File(deletedPackage.codePath);
11313                // Parse old package
11314                boolean oldExternal = isExternal(deletedPackage);
11315                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11316                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11317                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11318                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11319                try {
11320                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11321                } catch (PackageManagerException e) {
11322                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11323                            + e.getMessage());
11324                    return;
11325                }
11326                // Restore of old package succeeded. Update permissions.
11327                // writer
11328                synchronized (mPackages) {
11329                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11330                            UPDATE_PERMISSIONS_ALL);
11331                    // can downgrade to reader
11332                    mSettings.writeLPr();
11333                }
11334                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11335            }
11336        }
11337    }
11338
11339    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11340            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11341            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11342            String volumeUuid, PackageInstalledInfo res) {
11343        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11344                + ", old=" + deletedPackage);
11345        boolean disabledSystem = false;
11346        boolean updatedSettings = false;
11347        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11348        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11349                != 0) {
11350            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11351        }
11352        String packageName = deletedPackage.packageName;
11353        if (packageName == null) {
11354            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11355                    "Attempt to delete null packageName.");
11356            return;
11357        }
11358        PackageParser.Package oldPkg;
11359        PackageSetting oldPkgSetting;
11360        // reader
11361        synchronized (mPackages) {
11362            oldPkg = mPackages.get(packageName);
11363            oldPkgSetting = mSettings.mPackages.get(packageName);
11364            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11365                    (oldPkgSetting == null)) {
11366                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11367                        "Couldn't find package:" + packageName + " information");
11368                return;
11369            }
11370        }
11371
11372        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11373        res.removedInfo.removedPackage = packageName;
11374        // Remove existing system package
11375        removePackageLI(oldPkgSetting, true);
11376        // writer
11377        synchronized (mPackages) {
11378            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11379            if (!disabledSystem && deletedPackage != null) {
11380                // We didn't need to disable the .apk as a current system package,
11381                // which means we are replacing another update that is already
11382                // installed.  We need to make sure to delete the older one's .apk.
11383                res.removedInfo.args = createInstallArgsForExisting(0,
11384                        deletedPackage.applicationInfo.getCodePath(),
11385                        deletedPackage.applicationInfo.getResourcePath(),
11386                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11387            } else {
11388                res.removedInfo.args = null;
11389            }
11390        }
11391
11392        // Successfully disabled the old package. Now proceed with re-installation
11393        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11394
11395        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11396        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11397
11398        PackageParser.Package newPackage = null;
11399        try {
11400            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11401            if (newPackage.mExtras != null) {
11402                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11403                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11404                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11405
11406                // is the update attempting to change shared user? that isn't going to work...
11407                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11408                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11409                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11410                            + " to " + newPkgSetting.sharedUser);
11411                    updatedSettings = true;
11412                }
11413            }
11414
11415            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11416                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11417                        perUserInstalled, res, user);
11418                updatedSettings = true;
11419            }
11420
11421        } catch (PackageManagerException e) {
11422            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11423        }
11424
11425        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11426            // Re installation failed. Restore old information
11427            // Remove new pkg information
11428            if (newPackage != null) {
11429                removeInstalledPackageLI(newPackage, true);
11430            }
11431            // Add back the old system package
11432            try {
11433                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11434            } catch (PackageManagerException e) {
11435                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11436            }
11437            // Restore the old system information in Settings
11438            synchronized (mPackages) {
11439                if (disabledSystem) {
11440                    mSettings.enableSystemPackageLPw(packageName);
11441                }
11442                if (updatedSettings) {
11443                    mSettings.setInstallerPackageName(packageName,
11444                            oldPkgSetting.installerPackageName);
11445                }
11446                mSettings.writeLPr();
11447            }
11448        }
11449    }
11450
11451    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11452            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11453            UserHandle user) {
11454        String pkgName = newPackage.packageName;
11455        synchronized (mPackages) {
11456            //write settings. the installStatus will be incomplete at this stage.
11457            //note that the new package setting would have already been
11458            //added to mPackages. It hasn't been persisted yet.
11459            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11460            mSettings.writeLPr();
11461        }
11462
11463        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11464
11465        synchronized (mPackages) {
11466            updatePermissionsLPw(newPackage.packageName, newPackage,
11467                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11468                            ? UPDATE_PERMISSIONS_ALL : 0));
11469            // For system-bundled packages, we assume that installing an upgraded version
11470            // of the package implies that the user actually wants to run that new code,
11471            // so we enable the package.
11472            PackageSetting ps = mSettings.mPackages.get(pkgName);
11473            if (ps != null) {
11474                if (isSystemApp(newPackage)) {
11475                    // NB: implicit assumption that system package upgrades apply to all users
11476                    if (DEBUG_INSTALL) {
11477                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11478                    }
11479                    if (res.origUsers != null) {
11480                        for (int userHandle : res.origUsers) {
11481                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11482                                    userHandle, installerPackageName);
11483                        }
11484                    }
11485                    // Also convey the prior install/uninstall state
11486                    if (allUsers != null && perUserInstalled != null) {
11487                        for (int i = 0; i < allUsers.length; i++) {
11488                            if (DEBUG_INSTALL) {
11489                                Slog.d(TAG, "    user " + allUsers[i]
11490                                        + " => " + perUserInstalled[i]);
11491                            }
11492                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11493                        }
11494                        // these install state changes will be persisted in the
11495                        // upcoming call to mSettings.writeLPr().
11496                    }
11497                }
11498                // It's implied that when a user requests installation, they want the app to be
11499                // installed and enabled.
11500                int userId = user.getIdentifier();
11501                if (userId != UserHandle.USER_ALL) {
11502                    ps.setInstalled(true, userId);
11503                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11504                }
11505            }
11506            res.name = pkgName;
11507            res.uid = newPackage.applicationInfo.uid;
11508            res.pkg = newPackage;
11509            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11510            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11511            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11512            //to update install status
11513            mSettings.writeLPr();
11514        }
11515    }
11516
11517    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11518        final int installFlags = args.installFlags;
11519        final String installerPackageName = args.installerPackageName;
11520        final String volumeUuid = args.volumeUuid;
11521        final File tmpPackageFile = new File(args.getCodePath());
11522        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11523        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11524                || (args.volumeUuid != null));
11525        boolean replace = false;
11526        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11527        // Result object to be returned
11528        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11529
11530        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11531        // Retrieve PackageSettings and parse package
11532        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11533                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11534                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11535        PackageParser pp = new PackageParser();
11536        pp.setSeparateProcesses(mSeparateProcesses);
11537        pp.setDisplayMetrics(mMetrics);
11538
11539        final PackageParser.Package pkg;
11540        try {
11541            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11542        } catch (PackageParserException e) {
11543            res.setError("Failed parse during installPackageLI", e);
11544            return;
11545        }
11546
11547        // Mark that we have an install time CPU ABI override.
11548        pkg.cpuAbiOverride = args.abiOverride;
11549
11550        String pkgName = res.name = pkg.packageName;
11551        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11552            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11553                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11554                return;
11555            }
11556        }
11557
11558        try {
11559            pp.collectCertificates(pkg, parseFlags);
11560            pp.collectManifestDigest(pkg);
11561        } catch (PackageParserException e) {
11562            res.setError("Failed collect during installPackageLI", e);
11563            return;
11564        }
11565
11566        /* If the installer passed in a manifest digest, compare it now. */
11567        if (args.manifestDigest != null) {
11568            if (DEBUG_INSTALL) {
11569                final String parsedManifest = pkg.manifestDigest == null ? "null"
11570                        : pkg.manifestDigest.toString();
11571                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11572                        + parsedManifest);
11573            }
11574
11575            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11576                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11577                return;
11578            }
11579        } else if (DEBUG_INSTALL) {
11580            final String parsedManifest = pkg.manifestDigest == null
11581                    ? "null" : pkg.manifestDigest.toString();
11582            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11583        }
11584
11585        // Get rid of all references to package scan path via parser.
11586        pp = null;
11587        String oldCodePath = null;
11588        boolean systemApp = false;
11589        synchronized (mPackages) {
11590            // Check if installing already existing package
11591            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11592                String oldName = mSettings.mRenamedPackages.get(pkgName);
11593                if (pkg.mOriginalPackages != null
11594                        && pkg.mOriginalPackages.contains(oldName)
11595                        && mPackages.containsKey(oldName)) {
11596                    // This package is derived from an original package,
11597                    // and this device has been updating from that original
11598                    // name.  We must continue using the original name, so
11599                    // rename the new package here.
11600                    pkg.setPackageName(oldName);
11601                    pkgName = pkg.packageName;
11602                    replace = true;
11603                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11604                            + oldName + " pkgName=" + pkgName);
11605                } else if (mPackages.containsKey(pkgName)) {
11606                    // This package, under its official name, already exists
11607                    // on the device; we should replace it.
11608                    replace = true;
11609                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11610                }
11611
11612                // Prevent apps opting out from runtime permissions
11613                if (replace) {
11614                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11615                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11616                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11617                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11618                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11619                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11620                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11621                                        + " doesn't support runtime permissions but the old"
11622                                        + " target SDK " + oldTargetSdk + " does.");
11623                        return;
11624                    }
11625                }
11626            }
11627
11628            PackageSetting ps = mSettings.mPackages.get(pkgName);
11629            if (ps != null) {
11630                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11631
11632                // Quick sanity check that we're signed correctly if updating;
11633                // we'll check this again later when scanning, but we want to
11634                // bail early here before tripping over redefined permissions.
11635                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11636                    try {
11637                        verifySignaturesLP(ps, pkg);
11638                    } catch (PackageManagerException e) {
11639                        res.setError(e.error, e.getMessage());
11640                        return;
11641                    }
11642                } else {
11643                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11644                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11645                                + pkg.packageName + " upgrade keys do not match the "
11646                                + "previously installed version");
11647                        return;
11648                    }
11649                }
11650
11651                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11652                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11653                    systemApp = (ps.pkg.applicationInfo.flags &
11654                            ApplicationInfo.FLAG_SYSTEM) != 0;
11655                }
11656                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11657            }
11658
11659            // Check whether the newly-scanned package wants to define an already-defined perm
11660            int N = pkg.permissions.size();
11661            for (int i = N-1; i >= 0; i--) {
11662                PackageParser.Permission perm = pkg.permissions.get(i);
11663                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11664                if (bp != null) {
11665                    // If the defining package is signed with our cert, it's okay.  This
11666                    // also includes the "updating the same package" case, of course.
11667                    // "updating same package" could also involve key-rotation.
11668                    final boolean sigsOk;
11669                    if (!bp.sourcePackage.equals(pkg.packageName)
11670                            || !(bp.packageSetting instanceof PackageSetting)
11671                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11672                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11673                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11674                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11675                    } else {
11676                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11677                    }
11678                    if (!sigsOk) {
11679                        // If the owning package is the system itself, we log but allow
11680                        // install to proceed; we fail the install on all other permission
11681                        // redefinitions.
11682                        if (!bp.sourcePackage.equals("android")) {
11683                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11684                                    + pkg.packageName + " attempting to redeclare permission "
11685                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11686                            res.origPermission = perm.info.name;
11687                            res.origPackage = bp.sourcePackage;
11688                            return;
11689                        } else {
11690                            Slog.w(TAG, "Package " + pkg.packageName
11691                                    + " attempting to redeclare system permission "
11692                                    + perm.info.name + "; ignoring new declaration");
11693                            pkg.permissions.remove(i);
11694                        }
11695                    }
11696                }
11697            }
11698
11699        }
11700
11701        if (systemApp && onExternal) {
11702            // Disable updates to system apps on sdcard
11703            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11704                    "Cannot install updates to system apps on sdcard");
11705            return;
11706        }
11707
11708        if (args.move != null) {
11709            // We did an in-place move, so dex is ready to roll
11710            scanFlags |= SCAN_NO_DEX;
11711            scanFlags |= SCAN_MOVE;
11712        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11713            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11714            scanFlags |= SCAN_NO_DEX;
11715
11716            try {
11717                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11718                        true /* extract libs */);
11719            } catch (PackageManagerException pme) {
11720                Slog.e(TAG, "Error deriving application ABI", pme);
11721                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11722                return;
11723            }
11724
11725            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11726            int result = mPackageDexOptimizer
11727                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11728                            false /* defer */, false /* inclDependencies */);
11729            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11730                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11731                return;
11732            }
11733        }
11734
11735        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11736            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11737            return;
11738        }
11739
11740        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11741
11742        if (replace) {
11743            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11744                    installerPackageName, volumeUuid, res);
11745        } else {
11746            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11747                    args.user, installerPackageName, volumeUuid, res);
11748        }
11749        synchronized (mPackages) {
11750            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11751            if (ps != null) {
11752                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11753            }
11754        }
11755    }
11756
11757    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11758        if (mIntentFilterVerifierComponent == null) {
11759            Slog.w(TAG, "No IntentFilter verification will not be done as "
11760                    + "there is no IntentFilterVerifier available!");
11761            return;
11762        }
11763
11764        final int verifierUid = getPackageUid(
11765                mIntentFilterVerifierComponent.getPackageName(),
11766                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11767
11768        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11769        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11770        msg.obj = pkg;
11771        msg.arg1 = userId;
11772        msg.arg2 = verifierUid;
11773
11774        mHandler.sendMessage(msg);
11775    }
11776
11777    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11778            PackageParser.Package pkg) {
11779        int size = pkg.activities.size();
11780        if (size == 0) {
11781            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11782                    "No activity, so no need to verify any IntentFilter!");
11783            return;
11784        }
11785
11786        final boolean hasDomainURLs = hasDomainURLs(pkg);
11787        if (!hasDomainURLs) {
11788            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11789                    "No domain URLs, so no need to verify any IntentFilter!");
11790            return;
11791        }
11792
11793        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11794                + " if any IntentFilter from the " + size
11795                + " Activities needs verification ...");
11796
11797        final int verificationId = mIntentFilterVerificationToken++;
11798        int count = 0;
11799        final String packageName = pkg.packageName;
11800        ArrayList<String> allHosts = new ArrayList<>();
11801
11802        synchronized (mPackages) {
11803            for (PackageParser.Activity a : pkg.activities) {
11804                for (ActivityIntentInfo filter : a.intents) {
11805                    boolean needsFilterVerification = filter.needsVerification();
11806                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11807                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11808                                "Verification needed for IntentFilter:" + filter.toString());
11809                        mIntentFilterVerifier.addOneIntentFilterVerification(
11810                                verifierUid, userId, verificationId, filter, packageName);
11811                        count++;
11812                    } else if (!needsFilterVerification) {
11813                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11814                                "No verification needed for IntentFilter:" + filter.toString());
11815                        if (hasValidDomains(filter)) {
11816                            ArrayList<String> hosts = filter.getHostsList();
11817                            if (hosts.size() > 0) {
11818                                allHosts.addAll(hosts);
11819                            } else {
11820                                if (allHosts.isEmpty()) {
11821                                    allHosts.add("*");
11822                                }
11823                            }
11824                        }
11825                    } else {
11826                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11827                                "Verification already done for IntentFilter:" + filter.toString());
11828                    }
11829                }
11830            }
11831        }
11832
11833        if (count > 0) {
11834            mIntentFilterVerifier.startVerifications(userId);
11835            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Started " + count
11836                    + " IntentFilter verification" + (count > 1 ? "s" : "")
11837                    +  " for userId:" + userId + "!");
11838        } else {
11839            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11840                    "No need to start any IntentFilter verification!");
11841            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11842                    packageName, allHosts) != null) {
11843                scheduleWriteSettingsLocked();
11844            }
11845        }
11846    }
11847
11848    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11849        final ComponentName cn  = filter.activity.getComponentName();
11850        final String packageName = cn.getPackageName();
11851
11852        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11853                packageName);
11854        if (ivi == null) {
11855            return true;
11856        }
11857        int status = ivi.getStatus();
11858        switch (status) {
11859            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11860            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11861                return true;
11862
11863            default:
11864                // Nothing to do
11865                return false;
11866        }
11867    }
11868
11869    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11870        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11871                || ((pkg.applicationInfo.privateFlags
11872                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11873                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11874    }
11875
11876    private static boolean isMultiArch(PackageSetting ps) {
11877        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11878    }
11879
11880    private static boolean isMultiArch(ApplicationInfo info) {
11881        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11882    }
11883
11884    private static boolean isExternal(PackageParser.Package pkg) {
11885        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11886    }
11887
11888    private static boolean isExternal(PackageSetting ps) {
11889        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11890    }
11891
11892    private static boolean isExternal(ApplicationInfo info) {
11893        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11894    }
11895
11896    private static boolean isSystemApp(PackageParser.Package pkg) {
11897        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11898    }
11899
11900    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11901        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11902    }
11903
11904    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11905        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11906    }
11907
11908    private static boolean isSystemApp(PackageSetting ps) {
11909        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11910    }
11911
11912    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11913        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11914    }
11915
11916    private int packageFlagsToInstallFlags(PackageSetting ps) {
11917        int installFlags = 0;
11918        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11919            // This existing package was an external ASEC install when we have
11920            // the external flag without a UUID
11921            installFlags |= PackageManager.INSTALL_EXTERNAL;
11922        }
11923        if (ps.isForwardLocked()) {
11924            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11925        }
11926        return installFlags;
11927    }
11928
11929    private void deleteTempPackageFiles() {
11930        final FilenameFilter filter = new FilenameFilter() {
11931            public boolean accept(File dir, String name) {
11932                return name.startsWith("vmdl") && name.endsWith(".tmp");
11933            }
11934        };
11935        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11936            file.delete();
11937        }
11938    }
11939
11940    @Override
11941    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11942            int flags) {
11943        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11944                flags);
11945    }
11946
11947    @Override
11948    public void deletePackage(final String packageName,
11949            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11950        mContext.enforceCallingOrSelfPermission(
11951                android.Manifest.permission.DELETE_PACKAGES, null);
11952        final int uid = Binder.getCallingUid();
11953        if (UserHandle.getUserId(uid) != userId) {
11954            mContext.enforceCallingPermission(
11955                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11956                    "deletePackage for user " + userId);
11957        }
11958        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11959            try {
11960                observer.onPackageDeleted(packageName,
11961                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11962            } catch (RemoteException re) {
11963            }
11964            return;
11965        }
11966
11967        boolean uninstallBlocked = false;
11968        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11969            int[] users = sUserManager.getUserIds();
11970            for (int i = 0; i < users.length; ++i) {
11971                if (getBlockUninstallForUser(packageName, users[i])) {
11972                    uninstallBlocked = true;
11973                    break;
11974                }
11975            }
11976        } else {
11977            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11978        }
11979        if (uninstallBlocked) {
11980            try {
11981                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11982                        null);
11983            } catch (RemoteException re) {
11984            }
11985            return;
11986        }
11987
11988        if (DEBUG_REMOVE) {
11989            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11990        }
11991        // Queue up an async operation since the package deletion may take a little while.
11992        mHandler.post(new Runnable() {
11993            public void run() {
11994                mHandler.removeCallbacks(this);
11995                final int returnCode = deletePackageX(packageName, userId, flags);
11996                if (observer != null) {
11997                    try {
11998                        observer.onPackageDeleted(packageName, returnCode, null);
11999                    } catch (RemoteException e) {
12000                        Log.i(TAG, "Observer no longer exists.");
12001                    } //end catch
12002                } //end if
12003            } //end run
12004        });
12005    }
12006
12007    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12008        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12009                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12010        try {
12011            if (dpm != null) {
12012                if (dpm.isDeviceOwner(packageName)) {
12013                    return true;
12014                }
12015                int[] users;
12016                if (userId == UserHandle.USER_ALL) {
12017                    users = sUserManager.getUserIds();
12018                } else {
12019                    users = new int[]{userId};
12020                }
12021                for (int i = 0; i < users.length; ++i) {
12022                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12023                        return true;
12024                    }
12025                }
12026            }
12027        } catch (RemoteException e) {
12028        }
12029        return false;
12030    }
12031
12032    /**
12033     *  This method is an internal method that could be get invoked either
12034     *  to delete an installed package or to clean up a failed installation.
12035     *  After deleting an installed package, a broadcast is sent to notify any
12036     *  listeners that the package has been installed. For cleaning up a failed
12037     *  installation, the broadcast is not necessary since the package's
12038     *  installation wouldn't have sent the initial broadcast either
12039     *  The key steps in deleting a package are
12040     *  deleting the package information in internal structures like mPackages,
12041     *  deleting the packages base directories through installd
12042     *  updating mSettings to reflect current status
12043     *  persisting settings for later use
12044     *  sending a broadcast if necessary
12045     */
12046    private int deletePackageX(String packageName, int userId, int flags) {
12047        final PackageRemovedInfo info = new PackageRemovedInfo();
12048        final boolean res;
12049
12050        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12051                ? UserHandle.ALL : new UserHandle(userId);
12052
12053        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12054            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12055            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12056        }
12057
12058        boolean removedForAllUsers = false;
12059        boolean systemUpdate = false;
12060
12061        // for the uninstall-updates case and restricted profiles, remember the per-
12062        // userhandle installed state
12063        int[] allUsers;
12064        boolean[] perUserInstalled;
12065        synchronized (mPackages) {
12066            PackageSetting ps = mSettings.mPackages.get(packageName);
12067            allUsers = sUserManager.getUserIds();
12068            perUserInstalled = new boolean[allUsers.length];
12069            for (int i = 0; i < allUsers.length; i++) {
12070                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12071            }
12072        }
12073
12074        synchronized (mInstallLock) {
12075            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12076            res = deletePackageLI(packageName, removeForUser,
12077                    true, allUsers, perUserInstalled,
12078                    flags | REMOVE_CHATTY, info, true);
12079            systemUpdate = info.isRemovedPackageSystemUpdate;
12080            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12081                removedForAllUsers = true;
12082            }
12083            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12084                    + " removedForAllUsers=" + removedForAllUsers);
12085        }
12086
12087        if (res) {
12088            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12089
12090            // If the removed package was a system update, the old system package
12091            // was re-enabled; we need to broadcast this information
12092            if (systemUpdate) {
12093                Bundle extras = new Bundle(1);
12094                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12095                        ? info.removedAppId : info.uid);
12096                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12097
12098                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12099                        extras, null, null, null);
12100                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12101                        extras, null, null, null);
12102                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12103                        null, packageName, null, null);
12104            }
12105        }
12106        // Force a gc here.
12107        Runtime.getRuntime().gc();
12108        // Delete the resources here after sending the broadcast to let
12109        // other processes clean up before deleting resources.
12110        if (info.args != null) {
12111            synchronized (mInstallLock) {
12112                info.args.doPostDeleteLI(true);
12113            }
12114        }
12115
12116        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12117    }
12118
12119    class PackageRemovedInfo {
12120        String removedPackage;
12121        int uid = -1;
12122        int removedAppId = -1;
12123        int[] removedUsers = null;
12124        boolean isRemovedPackageSystemUpdate = false;
12125        // Clean up resources deleted packages.
12126        InstallArgs args = null;
12127
12128        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12129            Bundle extras = new Bundle(1);
12130            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12131            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12132            if (replacing) {
12133                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12134            }
12135            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12136            if (removedPackage != null) {
12137                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12138                        extras, null, null, removedUsers);
12139                if (fullRemove && !replacing) {
12140                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12141                            extras, null, null, removedUsers);
12142                }
12143            }
12144            if (removedAppId >= 0) {
12145                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12146                        removedUsers);
12147            }
12148        }
12149    }
12150
12151    /*
12152     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12153     * flag is not set, the data directory is removed as well.
12154     * make sure this flag is set for partially installed apps. If not its meaningless to
12155     * delete a partially installed application.
12156     */
12157    private void removePackageDataLI(PackageSetting ps,
12158            int[] allUserHandles, boolean[] perUserInstalled,
12159            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12160        String packageName = ps.name;
12161        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12162        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12163        // Retrieve object to delete permissions for shared user later on
12164        final PackageSetting deletedPs;
12165        // reader
12166        synchronized (mPackages) {
12167            deletedPs = mSettings.mPackages.get(packageName);
12168            if (outInfo != null) {
12169                outInfo.removedPackage = packageName;
12170                outInfo.removedUsers = deletedPs != null
12171                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12172                        : null;
12173            }
12174        }
12175        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12176            removeDataDirsLI(ps.volumeUuid, packageName);
12177            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12178        }
12179        // writer
12180        synchronized (mPackages) {
12181            if (deletedPs != null) {
12182                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12183                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12184                    clearDefaultBrowserIfNeeded(packageName);
12185                    if (outInfo != null) {
12186                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12187                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12188                    }
12189                    updatePermissionsLPw(deletedPs.name, null, 0);
12190                    if (deletedPs.sharedUser != null) {
12191                        // Remove permissions associated with package. Since runtime
12192                        // permissions are per user we have to kill the removed package
12193                        // or packages running under the shared user of the removed
12194                        // package if revoking the permissions requested only by the removed
12195                        // package is successful and this causes a change in gids.
12196                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12197                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12198                                    userId);
12199                            if (userIdToKill == UserHandle.USER_ALL
12200                                    || userIdToKill >= UserHandle.USER_OWNER) {
12201                                // If gids changed for this user, kill all affected packages.
12202                                mHandler.post(new Runnable() {
12203                                    @Override
12204                                    public void run() {
12205                                        // This has to happen with no lock held.
12206                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12207                                                KILL_APP_REASON_GIDS_CHANGED);
12208                                    }
12209                                });
12210                            break;
12211                            }
12212                        }
12213                    }
12214                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12215                }
12216                // make sure to preserve per-user disabled state if this removal was just
12217                // a downgrade of a system app to the factory package
12218                if (allUserHandles != null && perUserInstalled != null) {
12219                    if (DEBUG_REMOVE) {
12220                        Slog.d(TAG, "Propagating install state across downgrade");
12221                    }
12222                    for (int i = 0; i < allUserHandles.length; i++) {
12223                        if (DEBUG_REMOVE) {
12224                            Slog.d(TAG, "    user " + allUserHandles[i]
12225                                    + " => " + perUserInstalled[i]);
12226                        }
12227                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12228                    }
12229                }
12230            }
12231            // can downgrade to reader
12232            if (writeSettings) {
12233                // Save settings now
12234                mSettings.writeLPr();
12235            }
12236        }
12237        if (outInfo != null) {
12238            // A user ID was deleted here. Go through all users and remove it
12239            // from KeyStore.
12240            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12241        }
12242    }
12243
12244    static boolean locationIsPrivileged(File path) {
12245        try {
12246            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12247                    .getCanonicalPath();
12248            return path.getCanonicalPath().startsWith(privilegedAppDir);
12249        } catch (IOException e) {
12250            Slog.e(TAG, "Unable to access code path " + path);
12251        }
12252        return false;
12253    }
12254
12255    /*
12256     * Tries to delete system package.
12257     */
12258    private boolean deleteSystemPackageLI(PackageSetting newPs,
12259            int[] allUserHandles, boolean[] perUserInstalled,
12260            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12261        final boolean applyUserRestrictions
12262                = (allUserHandles != null) && (perUserInstalled != null);
12263        PackageSetting disabledPs = null;
12264        // Confirm if the system package has been updated
12265        // An updated system app can be deleted. This will also have to restore
12266        // the system pkg from system partition
12267        // reader
12268        synchronized (mPackages) {
12269            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12270        }
12271        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12272                + " disabledPs=" + disabledPs);
12273        if (disabledPs == null) {
12274            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12275            return false;
12276        } else if (DEBUG_REMOVE) {
12277            Slog.d(TAG, "Deleting system pkg from data partition");
12278        }
12279        if (DEBUG_REMOVE) {
12280            if (applyUserRestrictions) {
12281                Slog.d(TAG, "Remembering install states:");
12282                for (int i = 0; i < allUserHandles.length; i++) {
12283                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12284                }
12285            }
12286        }
12287        // Delete the updated package
12288        outInfo.isRemovedPackageSystemUpdate = true;
12289        if (disabledPs.versionCode < newPs.versionCode) {
12290            // Delete data for downgrades
12291            flags &= ~PackageManager.DELETE_KEEP_DATA;
12292        } else {
12293            // Preserve data by setting flag
12294            flags |= PackageManager.DELETE_KEEP_DATA;
12295        }
12296        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12297                allUserHandles, perUserInstalled, outInfo, writeSettings);
12298        if (!ret) {
12299            return false;
12300        }
12301        // writer
12302        synchronized (mPackages) {
12303            // Reinstate the old system package
12304            mSettings.enableSystemPackageLPw(newPs.name);
12305            // Remove any native libraries from the upgraded package.
12306            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12307        }
12308        // Install the system package
12309        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12310        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12311        if (locationIsPrivileged(disabledPs.codePath)) {
12312            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12313        }
12314
12315        final PackageParser.Package newPkg;
12316        try {
12317            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12318        } catch (PackageManagerException e) {
12319            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12320            return false;
12321        }
12322
12323        // writer
12324        synchronized (mPackages) {
12325            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12326            updatePermissionsLPw(newPkg.packageName, newPkg,
12327                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12328            if (applyUserRestrictions) {
12329                if (DEBUG_REMOVE) {
12330                    Slog.d(TAG, "Propagating install state across reinstall");
12331                }
12332                for (int i = 0; i < allUserHandles.length; i++) {
12333                    if (DEBUG_REMOVE) {
12334                        Slog.d(TAG, "    user " + allUserHandles[i]
12335                                + " => " + perUserInstalled[i]);
12336                    }
12337                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12338                }
12339                // Regardless of writeSettings we need to ensure that this restriction
12340                // state propagation is persisted
12341                mSettings.writeAllUsersPackageRestrictionsLPr();
12342            }
12343            // can downgrade to reader here
12344            if (writeSettings) {
12345                mSettings.writeLPr();
12346            }
12347        }
12348        return true;
12349    }
12350
12351    private boolean deleteInstalledPackageLI(PackageSetting ps,
12352            boolean deleteCodeAndResources, int flags,
12353            int[] allUserHandles, boolean[] perUserInstalled,
12354            PackageRemovedInfo outInfo, boolean writeSettings) {
12355        if (outInfo != null) {
12356            outInfo.uid = ps.appId;
12357        }
12358
12359        // Delete package data from internal structures and also remove data if flag is set
12360        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12361
12362        // Delete application code and resources
12363        if (deleteCodeAndResources && (outInfo != null)) {
12364            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12365                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12366            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12367        }
12368        return true;
12369    }
12370
12371    @Override
12372    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12373            int userId) {
12374        mContext.enforceCallingOrSelfPermission(
12375                android.Manifest.permission.DELETE_PACKAGES, null);
12376        synchronized (mPackages) {
12377            PackageSetting ps = mSettings.mPackages.get(packageName);
12378            if (ps == null) {
12379                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12380                return false;
12381            }
12382            if (!ps.getInstalled(userId)) {
12383                // Can't block uninstall for an app that is not installed or enabled.
12384                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12385                return false;
12386            }
12387            ps.setBlockUninstall(blockUninstall, userId);
12388            mSettings.writePackageRestrictionsLPr(userId);
12389        }
12390        return true;
12391    }
12392
12393    @Override
12394    public boolean getBlockUninstallForUser(String packageName, int userId) {
12395        synchronized (mPackages) {
12396            PackageSetting ps = mSettings.mPackages.get(packageName);
12397            if (ps == null) {
12398                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12399                return false;
12400            }
12401            return ps.getBlockUninstall(userId);
12402        }
12403    }
12404
12405    /*
12406     * This method handles package deletion in general
12407     */
12408    private boolean deletePackageLI(String packageName, UserHandle user,
12409            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12410            int flags, PackageRemovedInfo outInfo,
12411            boolean writeSettings) {
12412        if (packageName == null) {
12413            Slog.w(TAG, "Attempt to delete null packageName.");
12414            return false;
12415        }
12416        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12417        PackageSetting ps;
12418        boolean dataOnly = false;
12419        int removeUser = -1;
12420        int appId = -1;
12421        synchronized (mPackages) {
12422            ps = mSettings.mPackages.get(packageName);
12423            if (ps == null) {
12424                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12425                return false;
12426            }
12427            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12428                    && user.getIdentifier() != UserHandle.USER_ALL) {
12429                // The caller is asking that the package only be deleted for a single
12430                // user.  To do this, we just mark its uninstalled state and delete
12431                // its data.  If this is a system app, we only allow this to happen if
12432                // they have set the special DELETE_SYSTEM_APP which requests different
12433                // semantics than normal for uninstalling system apps.
12434                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12435                ps.setUserState(user.getIdentifier(),
12436                        COMPONENT_ENABLED_STATE_DEFAULT,
12437                        false, //installed
12438                        true,  //stopped
12439                        true,  //notLaunched
12440                        false, //hidden
12441                        null, null, null,
12442                        false, // blockUninstall
12443                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12444                if (!isSystemApp(ps)) {
12445                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12446                        // Other user still have this package installed, so all
12447                        // we need to do is clear this user's data and save that
12448                        // it is uninstalled.
12449                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12450                        removeUser = user.getIdentifier();
12451                        appId = ps.appId;
12452                        scheduleWritePackageRestrictionsLocked(removeUser);
12453                    } else {
12454                        // We need to set it back to 'installed' so the uninstall
12455                        // broadcasts will be sent correctly.
12456                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12457                        ps.setInstalled(true, user.getIdentifier());
12458                    }
12459                } else {
12460                    // This is a system app, so we assume that the
12461                    // other users still have this package installed, so all
12462                    // we need to do is clear this user's data and save that
12463                    // it is uninstalled.
12464                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12465                    removeUser = user.getIdentifier();
12466                    appId = ps.appId;
12467                    scheduleWritePackageRestrictionsLocked(removeUser);
12468                }
12469            }
12470        }
12471
12472        if (removeUser >= 0) {
12473            // From above, we determined that we are deleting this only
12474            // for a single user.  Continue the work here.
12475            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12476            if (outInfo != null) {
12477                outInfo.removedPackage = packageName;
12478                outInfo.removedAppId = appId;
12479                outInfo.removedUsers = new int[] {removeUser};
12480            }
12481            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12482            removeKeystoreDataIfNeeded(removeUser, appId);
12483            schedulePackageCleaning(packageName, removeUser, false);
12484            synchronized (mPackages) {
12485                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12486                    scheduleWritePackageRestrictionsLocked(removeUser);
12487                }
12488            }
12489            return true;
12490        }
12491
12492        if (dataOnly) {
12493            // Delete application data first
12494            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12495            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12496            return true;
12497        }
12498
12499        boolean ret = false;
12500        if (isSystemApp(ps)) {
12501            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12502            // When an updated system application is deleted we delete the existing resources as well and
12503            // fall back to existing code in system partition
12504            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12505                    flags, outInfo, writeSettings);
12506        } else {
12507            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12508            // Kill application pre-emptively especially for apps on sd.
12509            killApplication(packageName, ps.appId, "uninstall pkg");
12510            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12511                    allUserHandles, perUserInstalled,
12512                    outInfo, writeSettings);
12513        }
12514
12515        return ret;
12516    }
12517
12518    private final class ClearStorageConnection implements ServiceConnection {
12519        IMediaContainerService mContainerService;
12520
12521        @Override
12522        public void onServiceConnected(ComponentName name, IBinder service) {
12523            synchronized (this) {
12524                mContainerService = IMediaContainerService.Stub.asInterface(service);
12525                notifyAll();
12526            }
12527        }
12528
12529        @Override
12530        public void onServiceDisconnected(ComponentName name) {
12531        }
12532    }
12533
12534    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12535        final boolean mounted;
12536        if (Environment.isExternalStorageEmulated()) {
12537            mounted = true;
12538        } else {
12539            final String status = Environment.getExternalStorageState();
12540
12541            mounted = status.equals(Environment.MEDIA_MOUNTED)
12542                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12543        }
12544
12545        if (!mounted) {
12546            return;
12547        }
12548
12549        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12550        int[] users;
12551        if (userId == UserHandle.USER_ALL) {
12552            users = sUserManager.getUserIds();
12553        } else {
12554            users = new int[] { userId };
12555        }
12556        final ClearStorageConnection conn = new ClearStorageConnection();
12557        if (mContext.bindServiceAsUser(
12558                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12559            try {
12560                for (int curUser : users) {
12561                    long timeout = SystemClock.uptimeMillis() + 5000;
12562                    synchronized (conn) {
12563                        long now = SystemClock.uptimeMillis();
12564                        while (conn.mContainerService == null && now < timeout) {
12565                            try {
12566                                conn.wait(timeout - now);
12567                            } catch (InterruptedException e) {
12568                            }
12569                        }
12570                    }
12571                    if (conn.mContainerService == null) {
12572                        return;
12573                    }
12574
12575                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12576                    clearDirectory(conn.mContainerService,
12577                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12578                    if (allData) {
12579                        clearDirectory(conn.mContainerService,
12580                                userEnv.buildExternalStorageAppDataDirs(packageName));
12581                        clearDirectory(conn.mContainerService,
12582                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12583                    }
12584                }
12585            } finally {
12586                mContext.unbindService(conn);
12587            }
12588        }
12589    }
12590
12591    @Override
12592    public void clearApplicationUserData(final String packageName,
12593            final IPackageDataObserver observer, final int userId) {
12594        mContext.enforceCallingOrSelfPermission(
12595                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12596        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12597        // Queue up an async operation since the package deletion may take a little while.
12598        mHandler.post(new Runnable() {
12599            public void run() {
12600                mHandler.removeCallbacks(this);
12601                final boolean succeeded;
12602                synchronized (mInstallLock) {
12603                    succeeded = clearApplicationUserDataLI(packageName, userId);
12604                }
12605                clearExternalStorageDataSync(packageName, userId, true);
12606                if (succeeded) {
12607                    // invoke DeviceStorageMonitor's update method to clear any notifications
12608                    DeviceStorageMonitorInternal
12609                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12610                    if (dsm != null) {
12611                        dsm.checkMemory();
12612                    }
12613                }
12614                if(observer != null) {
12615                    try {
12616                        observer.onRemoveCompleted(packageName, succeeded);
12617                    } catch (RemoteException e) {
12618                        Log.i(TAG, "Observer no longer exists.");
12619                    }
12620                } //end if observer
12621            } //end run
12622        });
12623    }
12624
12625    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12626        if (packageName == null) {
12627            Slog.w(TAG, "Attempt to delete null packageName.");
12628            return false;
12629        }
12630
12631        // Try finding details about the requested package
12632        PackageParser.Package pkg;
12633        synchronized (mPackages) {
12634            pkg = mPackages.get(packageName);
12635            if (pkg == null) {
12636                final PackageSetting ps = mSettings.mPackages.get(packageName);
12637                if (ps != null) {
12638                    pkg = ps.pkg;
12639                }
12640            }
12641
12642            if (pkg == null) {
12643                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12644                return false;
12645            }
12646
12647            PackageSetting ps = (PackageSetting) pkg.mExtras;
12648            PermissionsState permissionsState = ps.getPermissionsState();
12649            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12650        }
12651
12652        // Always delete data directories for package, even if we found no other
12653        // record of app. This helps users recover from UID mismatches without
12654        // resorting to a full data wipe.
12655        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12656        if (retCode < 0) {
12657            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12658            return false;
12659        }
12660
12661        final int appId = pkg.applicationInfo.uid;
12662        removeKeystoreDataIfNeeded(userId, appId);
12663
12664        // Create a native library symlink only if we have native libraries
12665        // and if the native libraries are 32 bit libraries. We do not provide
12666        // this symlink for 64 bit libraries.
12667        if (pkg.applicationInfo.primaryCpuAbi != null &&
12668                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12669            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12670            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12671                    nativeLibPath, userId) < 0) {
12672                Slog.w(TAG, "Failed linking native library dir");
12673                return false;
12674            }
12675        }
12676
12677        return true;
12678    }
12679
12680
12681    /**
12682     * Revokes granted runtime permissions and clears resettable flags
12683     * which are flags that can be set by a user interaction.
12684     *
12685     * @param permissionsState The permission state to reset.
12686     * @param userId The device user for which to do a reset.
12687     */
12688    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12689            PermissionsState permissionsState, int userId) {
12690        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12691                | PackageManager.FLAG_PERMISSION_USER_FIXED
12692                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12693
12694        boolean needsWrite = false;
12695
12696        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12697            BasePermission bp = mSettings.mPermissions.get(state.getName());
12698            if (bp != null) {
12699                permissionsState.revokeRuntimePermission(bp, userId);
12700                permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0);
12701                needsWrite = true;
12702            }
12703        }
12704
12705        if (needsWrite) {
12706            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12707        }
12708    }
12709
12710    /**
12711     * Remove entries from the keystore daemon. Will only remove it if the
12712     * {@code appId} is valid.
12713     */
12714    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12715        if (appId < 0) {
12716            return;
12717        }
12718
12719        final KeyStore keyStore = KeyStore.getInstance();
12720        if (keyStore != null) {
12721            if (userId == UserHandle.USER_ALL) {
12722                for (final int individual : sUserManager.getUserIds()) {
12723                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12724                }
12725            } else {
12726                keyStore.clearUid(UserHandle.getUid(userId, appId));
12727            }
12728        } else {
12729            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12730        }
12731    }
12732
12733    @Override
12734    public void deleteApplicationCacheFiles(final String packageName,
12735            final IPackageDataObserver observer) {
12736        mContext.enforceCallingOrSelfPermission(
12737                android.Manifest.permission.DELETE_CACHE_FILES, null);
12738        // Queue up an async operation since the package deletion may take a little while.
12739        final int userId = UserHandle.getCallingUserId();
12740        mHandler.post(new Runnable() {
12741            public void run() {
12742                mHandler.removeCallbacks(this);
12743                final boolean succeded;
12744                synchronized (mInstallLock) {
12745                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12746                }
12747                clearExternalStorageDataSync(packageName, userId, false);
12748                if (observer != null) {
12749                    try {
12750                        observer.onRemoveCompleted(packageName, succeded);
12751                    } catch (RemoteException e) {
12752                        Log.i(TAG, "Observer no longer exists.");
12753                    }
12754                } //end if observer
12755            } //end run
12756        });
12757    }
12758
12759    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12760        if (packageName == null) {
12761            Slog.w(TAG, "Attempt to delete null packageName.");
12762            return false;
12763        }
12764        PackageParser.Package p;
12765        synchronized (mPackages) {
12766            p = mPackages.get(packageName);
12767        }
12768        if (p == null) {
12769            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12770            return false;
12771        }
12772        final ApplicationInfo applicationInfo = p.applicationInfo;
12773        if (applicationInfo == null) {
12774            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12775            return false;
12776        }
12777        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12778        if (retCode < 0) {
12779            Slog.w(TAG, "Couldn't remove cache files for package: "
12780                       + packageName + " u" + userId);
12781            return false;
12782        }
12783        return true;
12784    }
12785
12786    @Override
12787    public void getPackageSizeInfo(final String packageName, int userHandle,
12788            final IPackageStatsObserver observer) {
12789        mContext.enforceCallingOrSelfPermission(
12790                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12791        if (packageName == null) {
12792            throw new IllegalArgumentException("Attempt to get size of null packageName");
12793        }
12794
12795        PackageStats stats = new PackageStats(packageName, userHandle);
12796
12797        /*
12798         * Queue up an async operation since the package measurement may take a
12799         * little while.
12800         */
12801        Message msg = mHandler.obtainMessage(INIT_COPY);
12802        msg.obj = new MeasureParams(stats, observer);
12803        mHandler.sendMessage(msg);
12804    }
12805
12806    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12807            PackageStats pStats) {
12808        if (packageName == null) {
12809            Slog.w(TAG, "Attempt to get size of null packageName.");
12810            return false;
12811        }
12812        PackageParser.Package p;
12813        boolean dataOnly = false;
12814        String libDirRoot = null;
12815        String asecPath = null;
12816        PackageSetting ps = null;
12817        synchronized (mPackages) {
12818            p = mPackages.get(packageName);
12819            ps = mSettings.mPackages.get(packageName);
12820            if(p == null) {
12821                dataOnly = true;
12822                if((ps == null) || (ps.pkg == null)) {
12823                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12824                    return false;
12825                }
12826                p = ps.pkg;
12827            }
12828            if (ps != null) {
12829                libDirRoot = ps.legacyNativeLibraryPathString;
12830            }
12831            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12832                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12833                if (secureContainerId != null) {
12834                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12835                }
12836            }
12837        }
12838        String publicSrcDir = null;
12839        if(!dataOnly) {
12840            final ApplicationInfo applicationInfo = p.applicationInfo;
12841            if (applicationInfo == null) {
12842                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12843                return false;
12844            }
12845            if (p.isForwardLocked()) {
12846                publicSrcDir = applicationInfo.getBaseResourcePath();
12847            }
12848        }
12849        // TODO: extend to measure size of split APKs
12850        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12851        // not just the first level.
12852        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12853        // just the primary.
12854        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12855        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12856                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12857        if (res < 0) {
12858            return false;
12859        }
12860
12861        // Fix-up for forward-locked applications in ASEC containers.
12862        if (!isExternal(p)) {
12863            pStats.codeSize += pStats.externalCodeSize;
12864            pStats.externalCodeSize = 0L;
12865        }
12866
12867        return true;
12868    }
12869
12870
12871    @Override
12872    public void addPackageToPreferred(String packageName) {
12873        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12874    }
12875
12876    @Override
12877    public void removePackageFromPreferred(String packageName) {
12878        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12879    }
12880
12881    @Override
12882    public List<PackageInfo> getPreferredPackages(int flags) {
12883        return new ArrayList<PackageInfo>();
12884    }
12885
12886    private int getUidTargetSdkVersionLockedLPr(int uid) {
12887        Object obj = mSettings.getUserIdLPr(uid);
12888        if (obj instanceof SharedUserSetting) {
12889            final SharedUserSetting sus = (SharedUserSetting) obj;
12890            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12891            final Iterator<PackageSetting> it = sus.packages.iterator();
12892            while (it.hasNext()) {
12893                final PackageSetting ps = it.next();
12894                if (ps.pkg != null) {
12895                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12896                    if (v < vers) vers = v;
12897                }
12898            }
12899            return vers;
12900        } else if (obj instanceof PackageSetting) {
12901            final PackageSetting ps = (PackageSetting) obj;
12902            if (ps.pkg != null) {
12903                return ps.pkg.applicationInfo.targetSdkVersion;
12904            }
12905        }
12906        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12907    }
12908
12909    @Override
12910    public void addPreferredActivity(IntentFilter filter, int match,
12911            ComponentName[] set, ComponentName activity, int userId) {
12912        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12913                "Adding preferred");
12914    }
12915
12916    private void addPreferredActivityInternal(IntentFilter filter, int match,
12917            ComponentName[] set, ComponentName activity, boolean always, int userId,
12918            String opname) {
12919        // writer
12920        int callingUid = Binder.getCallingUid();
12921        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12922        if (filter.countActions() == 0) {
12923            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12924            return;
12925        }
12926        synchronized (mPackages) {
12927            if (mContext.checkCallingOrSelfPermission(
12928                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12929                    != PackageManager.PERMISSION_GRANTED) {
12930                if (getUidTargetSdkVersionLockedLPr(callingUid)
12931                        < Build.VERSION_CODES.FROYO) {
12932                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12933                            + callingUid);
12934                    return;
12935                }
12936                mContext.enforceCallingOrSelfPermission(
12937                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12938            }
12939
12940            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12941            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12942                    + userId + ":");
12943            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12944            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12945            scheduleWritePackageRestrictionsLocked(userId);
12946        }
12947    }
12948
12949    @Override
12950    public void replacePreferredActivity(IntentFilter filter, int match,
12951            ComponentName[] set, ComponentName activity, int userId) {
12952        if (filter.countActions() != 1) {
12953            throw new IllegalArgumentException(
12954                    "replacePreferredActivity expects filter to have only 1 action.");
12955        }
12956        if (filter.countDataAuthorities() != 0
12957                || filter.countDataPaths() != 0
12958                || filter.countDataSchemes() > 1
12959                || filter.countDataTypes() != 0) {
12960            throw new IllegalArgumentException(
12961                    "replacePreferredActivity expects filter to have no data authorities, " +
12962                    "paths, or types; and at most one scheme.");
12963        }
12964
12965        final int callingUid = Binder.getCallingUid();
12966        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12967        synchronized (mPackages) {
12968            if (mContext.checkCallingOrSelfPermission(
12969                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12970                    != PackageManager.PERMISSION_GRANTED) {
12971                if (getUidTargetSdkVersionLockedLPr(callingUid)
12972                        < Build.VERSION_CODES.FROYO) {
12973                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12974                            + Binder.getCallingUid());
12975                    return;
12976                }
12977                mContext.enforceCallingOrSelfPermission(
12978                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12979            }
12980
12981            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12982            if (pir != null) {
12983                // Get all of the existing entries that exactly match this filter.
12984                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12985                if (existing != null && existing.size() == 1) {
12986                    PreferredActivity cur = existing.get(0);
12987                    if (DEBUG_PREFERRED) {
12988                        Slog.i(TAG, "Checking replace of preferred:");
12989                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12990                        if (!cur.mPref.mAlways) {
12991                            Slog.i(TAG, "  -- CUR; not mAlways!");
12992                        } else {
12993                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12994                            Slog.i(TAG, "  -- CUR: mSet="
12995                                    + Arrays.toString(cur.mPref.mSetComponents));
12996                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12997                            Slog.i(TAG, "  -- NEW: mMatch="
12998                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12999                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13000                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13001                        }
13002                    }
13003                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13004                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13005                            && cur.mPref.sameSet(set)) {
13006                        // Setting the preferred activity to what it happens to be already
13007                        if (DEBUG_PREFERRED) {
13008                            Slog.i(TAG, "Replacing with same preferred activity "
13009                                    + cur.mPref.mShortComponent + " for user "
13010                                    + userId + ":");
13011                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13012                        }
13013                        return;
13014                    }
13015                }
13016
13017                if (existing != null) {
13018                    if (DEBUG_PREFERRED) {
13019                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13020                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13021                    }
13022                    for (int i = 0; i < existing.size(); i++) {
13023                        PreferredActivity pa = existing.get(i);
13024                        if (DEBUG_PREFERRED) {
13025                            Slog.i(TAG, "Removing existing preferred activity "
13026                                    + pa.mPref.mComponent + ":");
13027                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13028                        }
13029                        pir.removeFilter(pa);
13030                    }
13031                }
13032            }
13033            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13034                    "Replacing preferred");
13035        }
13036    }
13037
13038    @Override
13039    public void clearPackagePreferredActivities(String packageName) {
13040        final int uid = Binder.getCallingUid();
13041        // writer
13042        synchronized (mPackages) {
13043            PackageParser.Package pkg = mPackages.get(packageName);
13044            if (pkg == null || pkg.applicationInfo.uid != uid) {
13045                if (mContext.checkCallingOrSelfPermission(
13046                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13047                        != PackageManager.PERMISSION_GRANTED) {
13048                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13049                            < Build.VERSION_CODES.FROYO) {
13050                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13051                                + Binder.getCallingUid());
13052                        return;
13053                    }
13054                    mContext.enforceCallingOrSelfPermission(
13055                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13056                }
13057            }
13058
13059            int user = UserHandle.getCallingUserId();
13060            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13061                scheduleWritePackageRestrictionsLocked(user);
13062            }
13063        }
13064    }
13065
13066    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13067    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13068        ArrayList<PreferredActivity> removed = null;
13069        boolean changed = false;
13070        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13071            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13072            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13073            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13074                continue;
13075            }
13076            Iterator<PreferredActivity> it = pir.filterIterator();
13077            while (it.hasNext()) {
13078                PreferredActivity pa = it.next();
13079                // Mark entry for removal only if it matches the package name
13080                // and the entry is of type "always".
13081                if (packageName == null ||
13082                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13083                                && pa.mPref.mAlways)) {
13084                    if (removed == null) {
13085                        removed = new ArrayList<PreferredActivity>();
13086                    }
13087                    removed.add(pa);
13088                }
13089            }
13090            if (removed != null) {
13091                for (int j=0; j<removed.size(); j++) {
13092                    PreferredActivity pa = removed.get(j);
13093                    pir.removeFilter(pa);
13094                }
13095                changed = true;
13096            }
13097        }
13098        return changed;
13099    }
13100
13101    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13102    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13103        if (userId == UserHandle.USER_ALL) {
13104            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13105                    sUserManager.getUserIds())) {
13106                for (int oneUserId : sUserManager.getUserIds()) {
13107                    scheduleWritePackageRestrictionsLocked(oneUserId);
13108                }
13109            }
13110        } else {
13111            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13112                scheduleWritePackageRestrictionsLocked(userId);
13113            }
13114        }
13115    }
13116
13117
13118    void clearDefaultBrowserIfNeeded(String packageName) {
13119        for (int oneUserId : sUserManager.getUserIds()) {
13120            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13121            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13122            if (packageName.equals(defaultBrowserPackageName)) {
13123                setDefaultBrowserPackageName(null, oneUserId);
13124            }
13125        }
13126    }
13127
13128    @Override
13129    public void resetPreferredActivities(int userId) {
13130        /* TODO: Actually use userId. Why is it being passed in? */
13131        mContext.enforceCallingOrSelfPermission(
13132                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13133        // writer
13134        synchronized (mPackages) {
13135            int user = UserHandle.getCallingUserId();
13136            clearPackagePreferredActivitiesLPw(null, user);
13137            mSettings.readDefaultPreferredAppsLPw(this, user);
13138            scheduleWritePackageRestrictionsLocked(user);
13139        }
13140    }
13141
13142    @Override
13143    public int getPreferredActivities(List<IntentFilter> outFilters,
13144            List<ComponentName> outActivities, String packageName) {
13145
13146        int num = 0;
13147        final int userId = UserHandle.getCallingUserId();
13148        // reader
13149        synchronized (mPackages) {
13150            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13151            if (pir != null) {
13152                final Iterator<PreferredActivity> it = pir.filterIterator();
13153                while (it.hasNext()) {
13154                    final PreferredActivity pa = it.next();
13155                    if (packageName == null
13156                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13157                                    && pa.mPref.mAlways)) {
13158                        if (outFilters != null) {
13159                            outFilters.add(new IntentFilter(pa));
13160                        }
13161                        if (outActivities != null) {
13162                            outActivities.add(pa.mPref.mComponent);
13163                        }
13164                    }
13165                }
13166            }
13167        }
13168
13169        return num;
13170    }
13171
13172    @Override
13173    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13174            int userId) {
13175        int callingUid = Binder.getCallingUid();
13176        if (callingUid != Process.SYSTEM_UID) {
13177            throw new SecurityException(
13178                    "addPersistentPreferredActivity can only be run by the system");
13179        }
13180        if (filter.countActions() == 0) {
13181            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13182            return;
13183        }
13184        synchronized (mPackages) {
13185            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13186                    " :");
13187            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13188            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13189                    new PersistentPreferredActivity(filter, activity));
13190            scheduleWritePackageRestrictionsLocked(userId);
13191        }
13192    }
13193
13194    @Override
13195    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13196        int callingUid = Binder.getCallingUid();
13197        if (callingUid != Process.SYSTEM_UID) {
13198            throw new SecurityException(
13199                    "clearPackagePersistentPreferredActivities can only be run by the system");
13200        }
13201        ArrayList<PersistentPreferredActivity> removed = null;
13202        boolean changed = false;
13203        synchronized (mPackages) {
13204            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13205                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13206                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13207                        .valueAt(i);
13208                if (userId != thisUserId) {
13209                    continue;
13210                }
13211                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13212                while (it.hasNext()) {
13213                    PersistentPreferredActivity ppa = it.next();
13214                    // Mark entry for removal only if it matches the package name.
13215                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13216                        if (removed == null) {
13217                            removed = new ArrayList<PersistentPreferredActivity>();
13218                        }
13219                        removed.add(ppa);
13220                    }
13221                }
13222                if (removed != null) {
13223                    for (int j=0; j<removed.size(); j++) {
13224                        PersistentPreferredActivity ppa = removed.get(j);
13225                        ppir.removeFilter(ppa);
13226                    }
13227                    changed = true;
13228                }
13229            }
13230
13231            if (changed) {
13232                scheduleWritePackageRestrictionsLocked(userId);
13233            }
13234        }
13235    }
13236
13237    /**
13238     * Non-Binder method, support for the backup/restore mechanism: write the
13239     * full set of preferred activities in its canonical XML format.  Returns true
13240     * on success; false otherwise.
13241     */
13242    @Override
13243    public byte[] getPreferredActivityBackup(int userId) {
13244        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13245            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13246        }
13247
13248        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13249        try {
13250            final XmlSerializer serializer = new FastXmlSerializer();
13251            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13252            serializer.startDocument(null, true);
13253            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13254
13255            synchronized (mPackages) {
13256                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13257            }
13258
13259            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13260            serializer.endDocument();
13261            serializer.flush();
13262        } catch (Exception e) {
13263            if (DEBUG_BACKUP) {
13264                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13265            }
13266            return null;
13267        }
13268
13269        return dataStream.toByteArray();
13270    }
13271
13272    @Override
13273    public void restorePreferredActivities(byte[] backup, int userId) {
13274        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13275            throw new SecurityException("Only the system may call restorePreferredActivities()");
13276        }
13277
13278        try {
13279            final XmlPullParser parser = Xml.newPullParser();
13280            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13281
13282            int type;
13283            while ((type = parser.next()) != XmlPullParser.START_TAG
13284                    && type != XmlPullParser.END_DOCUMENT) {
13285            }
13286            if (type != XmlPullParser.START_TAG) {
13287                // oops didn't find a start tag?!
13288                if (DEBUG_BACKUP) {
13289                    Slog.e(TAG, "Didn't find start tag during restore");
13290                }
13291                return;
13292            }
13293
13294            // this is supposed to be TAG_PREFERRED_BACKUP
13295            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13296                if (DEBUG_BACKUP) {
13297                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13298                }
13299                return;
13300            }
13301
13302            // skip interfering stuff, then we're aligned with the backing implementation
13303            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13304            synchronized (mPackages) {
13305                mSettings.readPreferredActivitiesLPw(parser, userId);
13306            }
13307        } catch (Exception e) {
13308            if (DEBUG_BACKUP) {
13309                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13310            }
13311        }
13312    }
13313
13314    @Override
13315    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13316            int sourceUserId, int targetUserId, int flags) {
13317        mContext.enforceCallingOrSelfPermission(
13318                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13319        int callingUid = Binder.getCallingUid();
13320        enforceOwnerRights(ownerPackage, callingUid);
13321        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13322        if (intentFilter.countActions() == 0) {
13323            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13324            return;
13325        }
13326        synchronized (mPackages) {
13327            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13328                    ownerPackage, targetUserId, flags);
13329            CrossProfileIntentResolver resolver =
13330                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13331            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13332            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13333            if (existing != null) {
13334                int size = existing.size();
13335                for (int i = 0; i < size; i++) {
13336                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13337                        return;
13338                    }
13339                }
13340            }
13341            resolver.addFilter(newFilter);
13342            scheduleWritePackageRestrictionsLocked(sourceUserId);
13343        }
13344    }
13345
13346    @Override
13347    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13348        mContext.enforceCallingOrSelfPermission(
13349                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13350        int callingUid = Binder.getCallingUid();
13351        enforceOwnerRights(ownerPackage, callingUid);
13352        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13353        synchronized (mPackages) {
13354            CrossProfileIntentResolver resolver =
13355                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13356            ArraySet<CrossProfileIntentFilter> set =
13357                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13358            for (CrossProfileIntentFilter filter : set) {
13359                if (filter.getOwnerPackage().equals(ownerPackage)) {
13360                    resolver.removeFilter(filter);
13361                }
13362            }
13363            scheduleWritePackageRestrictionsLocked(sourceUserId);
13364        }
13365    }
13366
13367    // Enforcing that callingUid is owning pkg on userId
13368    private void enforceOwnerRights(String pkg, int callingUid) {
13369        // The system owns everything.
13370        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13371            return;
13372        }
13373        int callingUserId = UserHandle.getUserId(callingUid);
13374        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13375        if (pi == null) {
13376            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13377                    + callingUserId);
13378        }
13379        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13380            throw new SecurityException("Calling uid " + callingUid
13381                    + " does not own package " + pkg);
13382        }
13383    }
13384
13385    @Override
13386    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13387        Intent intent = new Intent(Intent.ACTION_MAIN);
13388        intent.addCategory(Intent.CATEGORY_HOME);
13389
13390        final int callingUserId = UserHandle.getCallingUserId();
13391        List<ResolveInfo> list = queryIntentActivities(intent, null,
13392                PackageManager.GET_META_DATA, callingUserId);
13393        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13394                true, false, false, callingUserId);
13395
13396        allHomeCandidates.clear();
13397        if (list != null) {
13398            for (ResolveInfo ri : list) {
13399                allHomeCandidates.add(ri);
13400            }
13401        }
13402        return (preferred == null || preferred.activityInfo == null)
13403                ? null
13404                : new ComponentName(preferred.activityInfo.packageName,
13405                        preferred.activityInfo.name);
13406    }
13407
13408    @Override
13409    public void setApplicationEnabledSetting(String appPackageName,
13410            int newState, int flags, int userId, String callingPackage) {
13411        if (!sUserManager.exists(userId)) return;
13412        if (callingPackage == null) {
13413            callingPackage = Integer.toString(Binder.getCallingUid());
13414        }
13415        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13416    }
13417
13418    @Override
13419    public void setComponentEnabledSetting(ComponentName componentName,
13420            int newState, int flags, int userId) {
13421        if (!sUserManager.exists(userId)) return;
13422        setEnabledSetting(componentName.getPackageName(),
13423                componentName.getClassName(), newState, flags, userId, null);
13424    }
13425
13426    private void setEnabledSetting(final String packageName, String className, int newState,
13427            final int flags, int userId, String callingPackage) {
13428        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13429              || newState == COMPONENT_ENABLED_STATE_ENABLED
13430              || newState == COMPONENT_ENABLED_STATE_DISABLED
13431              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13432              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13433            throw new IllegalArgumentException("Invalid new component state: "
13434                    + newState);
13435        }
13436        PackageSetting pkgSetting;
13437        final int uid = Binder.getCallingUid();
13438        final int permission = mContext.checkCallingOrSelfPermission(
13439                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13440        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13441        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13442        boolean sendNow = false;
13443        boolean isApp = (className == null);
13444        String componentName = isApp ? packageName : className;
13445        int packageUid = -1;
13446        ArrayList<String> components;
13447
13448        // writer
13449        synchronized (mPackages) {
13450            pkgSetting = mSettings.mPackages.get(packageName);
13451            if (pkgSetting == null) {
13452                if (className == null) {
13453                    throw new IllegalArgumentException(
13454                            "Unknown package: " + packageName);
13455                }
13456                throw new IllegalArgumentException(
13457                        "Unknown component: " + packageName
13458                        + "/" + className);
13459            }
13460            // Allow root and verify that userId is not being specified by a different user
13461            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13462                throw new SecurityException(
13463                        "Permission Denial: attempt to change component state from pid="
13464                        + Binder.getCallingPid()
13465                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13466            }
13467            if (className == null) {
13468                // We're dealing with an application/package level state change
13469                if (pkgSetting.getEnabled(userId) == newState) {
13470                    // Nothing to do
13471                    return;
13472                }
13473                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13474                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13475                    // Don't care about who enables an app.
13476                    callingPackage = null;
13477                }
13478                pkgSetting.setEnabled(newState, userId, callingPackage);
13479                // pkgSetting.pkg.mSetEnabled = newState;
13480            } else {
13481                // We're dealing with a component level state change
13482                // First, verify that this is a valid class name.
13483                PackageParser.Package pkg = pkgSetting.pkg;
13484                if (pkg == null || !pkg.hasComponentClassName(className)) {
13485                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13486                        throw new IllegalArgumentException("Component class " + className
13487                                + " does not exist in " + packageName);
13488                    } else {
13489                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13490                                + className + " does not exist in " + packageName);
13491                    }
13492                }
13493                switch (newState) {
13494                case COMPONENT_ENABLED_STATE_ENABLED:
13495                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13496                        return;
13497                    }
13498                    break;
13499                case COMPONENT_ENABLED_STATE_DISABLED:
13500                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13501                        return;
13502                    }
13503                    break;
13504                case COMPONENT_ENABLED_STATE_DEFAULT:
13505                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13506                        return;
13507                    }
13508                    break;
13509                default:
13510                    Slog.e(TAG, "Invalid new component state: " + newState);
13511                    return;
13512                }
13513            }
13514            scheduleWritePackageRestrictionsLocked(userId);
13515            components = mPendingBroadcasts.get(userId, packageName);
13516            final boolean newPackage = components == null;
13517            if (newPackage) {
13518                components = new ArrayList<String>();
13519            }
13520            if (!components.contains(componentName)) {
13521                components.add(componentName);
13522            }
13523            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13524                sendNow = true;
13525                // Purge entry from pending broadcast list if another one exists already
13526                // since we are sending one right away.
13527                mPendingBroadcasts.remove(userId, packageName);
13528            } else {
13529                if (newPackage) {
13530                    mPendingBroadcasts.put(userId, packageName, components);
13531                }
13532                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13533                    // Schedule a message
13534                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13535                }
13536            }
13537        }
13538
13539        long callingId = Binder.clearCallingIdentity();
13540        try {
13541            if (sendNow) {
13542                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13543                sendPackageChangedBroadcast(packageName,
13544                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13545            }
13546        } finally {
13547            Binder.restoreCallingIdentity(callingId);
13548        }
13549    }
13550
13551    private void sendPackageChangedBroadcast(String packageName,
13552            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13553        if (DEBUG_INSTALL)
13554            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13555                    + componentNames);
13556        Bundle extras = new Bundle(4);
13557        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13558        String nameList[] = new String[componentNames.size()];
13559        componentNames.toArray(nameList);
13560        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13561        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13562        extras.putInt(Intent.EXTRA_UID, packageUid);
13563        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13564                new int[] {UserHandle.getUserId(packageUid)});
13565    }
13566
13567    @Override
13568    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13569        if (!sUserManager.exists(userId)) return;
13570        final int uid = Binder.getCallingUid();
13571        final int permission = mContext.checkCallingOrSelfPermission(
13572                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13573        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13574        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13575        // writer
13576        synchronized (mPackages) {
13577            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13578                    allowedByPermission, uid, userId)) {
13579                scheduleWritePackageRestrictionsLocked(userId);
13580            }
13581        }
13582    }
13583
13584    @Override
13585    public String getInstallerPackageName(String packageName) {
13586        // reader
13587        synchronized (mPackages) {
13588            return mSettings.getInstallerPackageNameLPr(packageName);
13589        }
13590    }
13591
13592    @Override
13593    public int getApplicationEnabledSetting(String packageName, int userId) {
13594        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13595        int uid = Binder.getCallingUid();
13596        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13597        // reader
13598        synchronized (mPackages) {
13599            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13600        }
13601    }
13602
13603    @Override
13604    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13605        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13606        int uid = Binder.getCallingUid();
13607        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13608        // reader
13609        synchronized (mPackages) {
13610            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13611        }
13612    }
13613
13614    @Override
13615    public void enterSafeMode() {
13616        enforceSystemOrRoot("Only the system can request entering safe mode");
13617
13618        if (!mSystemReady) {
13619            mSafeMode = true;
13620        }
13621    }
13622
13623    @Override
13624    public void systemReady() {
13625        mSystemReady = true;
13626
13627        // Read the compatibilty setting when the system is ready.
13628        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13629                mContext.getContentResolver(),
13630                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13631        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13632        if (DEBUG_SETTINGS) {
13633            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13634        }
13635
13636        synchronized (mPackages) {
13637            // Verify that all of the preferred activity components actually
13638            // exist.  It is possible for applications to be updated and at
13639            // that point remove a previously declared activity component that
13640            // had been set as a preferred activity.  We try to clean this up
13641            // the next time we encounter that preferred activity, but it is
13642            // possible for the user flow to never be able to return to that
13643            // situation so here we do a sanity check to make sure we haven't
13644            // left any junk around.
13645            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13646            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13647                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13648                removed.clear();
13649                for (PreferredActivity pa : pir.filterSet()) {
13650                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13651                        removed.add(pa);
13652                    }
13653                }
13654                if (removed.size() > 0) {
13655                    for (int r=0; r<removed.size(); r++) {
13656                        PreferredActivity pa = removed.get(r);
13657                        Slog.w(TAG, "Removing dangling preferred activity: "
13658                                + pa.mPref.mComponent);
13659                        pir.removeFilter(pa);
13660                    }
13661                    mSettings.writePackageRestrictionsLPr(
13662                            mSettings.mPreferredActivities.keyAt(i));
13663                }
13664            }
13665        }
13666        sUserManager.systemReady();
13667
13668        // Kick off any messages waiting for system ready
13669        if (mPostSystemReadyMessages != null) {
13670            for (Message msg : mPostSystemReadyMessages) {
13671                msg.sendToTarget();
13672            }
13673            mPostSystemReadyMessages = null;
13674        }
13675
13676        // Watch for external volumes that come and go over time
13677        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13678        storage.registerListener(mStorageListener);
13679
13680        mInstallerService.systemReady();
13681        mPackageDexOptimizer.systemReady();
13682    }
13683
13684    @Override
13685    public boolean isSafeMode() {
13686        return mSafeMode;
13687    }
13688
13689    @Override
13690    public boolean hasSystemUidErrors() {
13691        return mHasSystemUidErrors;
13692    }
13693
13694    static String arrayToString(int[] array) {
13695        StringBuffer buf = new StringBuffer(128);
13696        buf.append('[');
13697        if (array != null) {
13698            for (int i=0; i<array.length; i++) {
13699                if (i > 0) buf.append(", ");
13700                buf.append(array[i]);
13701            }
13702        }
13703        buf.append(']');
13704        return buf.toString();
13705    }
13706
13707    static class DumpState {
13708        public static final int DUMP_LIBS = 1 << 0;
13709        public static final int DUMP_FEATURES = 1 << 1;
13710        public static final int DUMP_RESOLVERS = 1 << 2;
13711        public static final int DUMP_PERMISSIONS = 1 << 3;
13712        public static final int DUMP_PACKAGES = 1 << 4;
13713        public static final int DUMP_SHARED_USERS = 1 << 5;
13714        public static final int DUMP_MESSAGES = 1 << 6;
13715        public static final int DUMP_PROVIDERS = 1 << 7;
13716        public static final int DUMP_VERIFIERS = 1 << 8;
13717        public static final int DUMP_PREFERRED = 1 << 9;
13718        public static final int DUMP_PREFERRED_XML = 1 << 10;
13719        public static final int DUMP_KEYSETS = 1 << 11;
13720        public static final int DUMP_VERSION = 1 << 12;
13721        public static final int DUMP_INSTALLS = 1 << 13;
13722        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13723        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13724
13725        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13726
13727        private int mTypes;
13728
13729        private int mOptions;
13730
13731        private boolean mTitlePrinted;
13732
13733        private SharedUserSetting mSharedUser;
13734
13735        public boolean isDumping(int type) {
13736            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13737                return true;
13738            }
13739
13740            return (mTypes & type) != 0;
13741        }
13742
13743        public void setDump(int type) {
13744            mTypes |= type;
13745        }
13746
13747        public boolean isOptionEnabled(int option) {
13748            return (mOptions & option) != 0;
13749        }
13750
13751        public void setOptionEnabled(int option) {
13752            mOptions |= option;
13753        }
13754
13755        public boolean onTitlePrinted() {
13756            final boolean printed = mTitlePrinted;
13757            mTitlePrinted = true;
13758            return printed;
13759        }
13760
13761        public boolean getTitlePrinted() {
13762            return mTitlePrinted;
13763        }
13764
13765        public void setTitlePrinted(boolean enabled) {
13766            mTitlePrinted = enabled;
13767        }
13768
13769        public SharedUserSetting getSharedUser() {
13770            return mSharedUser;
13771        }
13772
13773        public void setSharedUser(SharedUserSetting user) {
13774            mSharedUser = user;
13775        }
13776    }
13777
13778    @Override
13779    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13780        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13781                != PackageManager.PERMISSION_GRANTED) {
13782            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13783                    + Binder.getCallingPid()
13784                    + ", uid=" + Binder.getCallingUid()
13785                    + " without permission "
13786                    + android.Manifest.permission.DUMP);
13787            return;
13788        }
13789
13790        DumpState dumpState = new DumpState();
13791        boolean fullPreferred = false;
13792        boolean checkin = false;
13793
13794        String packageName = null;
13795
13796        int opti = 0;
13797        while (opti < args.length) {
13798            String opt = args[opti];
13799            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13800                break;
13801            }
13802            opti++;
13803
13804            if ("-a".equals(opt)) {
13805                // Right now we only know how to print all.
13806            } else if ("-h".equals(opt)) {
13807                pw.println("Package manager dump options:");
13808                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13809                pw.println("    --checkin: dump for a checkin");
13810                pw.println("    -f: print details of intent filters");
13811                pw.println("    -h: print this help");
13812                pw.println("  cmd may be one of:");
13813                pw.println("    l[ibraries]: list known shared libraries");
13814                pw.println("    f[ibraries]: list device features");
13815                pw.println("    k[eysets]: print known keysets");
13816                pw.println("    r[esolvers]: dump intent resolvers");
13817                pw.println("    perm[issions]: dump permissions");
13818                pw.println("    pref[erred]: print preferred package settings");
13819                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13820                pw.println("    prov[iders]: dump content providers");
13821                pw.println("    p[ackages]: dump installed packages");
13822                pw.println("    s[hared-users]: dump shared user IDs");
13823                pw.println("    m[essages]: print collected runtime messages");
13824                pw.println("    v[erifiers]: print package verifier info");
13825                pw.println("    version: print database version info");
13826                pw.println("    write: write current settings now");
13827                pw.println("    <package.name>: info about given package");
13828                pw.println("    installs: details about install sessions");
13829                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13830                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13831                return;
13832            } else if ("--checkin".equals(opt)) {
13833                checkin = true;
13834            } else if ("-f".equals(opt)) {
13835                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13836            } else {
13837                pw.println("Unknown argument: " + opt + "; use -h for help");
13838            }
13839        }
13840
13841        // Is the caller requesting to dump a particular piece of data?
13842        if (opti < args.length) {
13843            String cmd = args[opti];
13844            opti++;
13845            // Is this a package name?
13846            if ("android".equals(cmd) || cmd.contains(".")) {
13847                packageName = cmd;
13848                // When dumping a single package, we always dump all of its
13849                // filter information since the amount of data will be reasonable.
13850                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13851            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13852                dumpState.setDump(DumpState.DUMP_LIBS);
13853            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13854                dumpState.setDump(DumpState.DUMP_FEATURES);
13855            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13856                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13857            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13858                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13859            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13860                dumpState.setDump(DumpState.DUMP_PREFERRED);
13861            } else if ("preferred-xml".equals(cmd)) {
13862                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13863                if (opti < args.length && "--full".equals(args[opti])) {
13864                    fullPreferred = true;
13865                    opti++;
13866                }
13867            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13868                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13869            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13870                dumpState.setDump(DumpState.DUMP_PACKAGES);
13871            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13872                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13873            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13874                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13875            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13876                dumpState.setDump(DumpState.DUMP_MESSAGES);
13877            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13878                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13879            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13880                    || "intent-filter-verifiers".equals(cmd)) {
13881                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13882            } else if ("version".equals(cmd)) {
13883                dumpState.setDump(DumpState.DUMP_VERSION);
13884            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13885                dumpState.setDump(DumpState.DUMP_KEYSETS);
13886            } else if ("installs".equals(cmd)) {
13887                dumpState.setDump(DumpState.DUMP_INSTALLS);
13888            } else if ("write".equals(cmd)) {
13889                synchronized (mPackages) {
13890                    mSettings.writeLPr();
13891                    pw.println("Settings written.");
13892                    return;
13893                }
13894            }
13895        }
13896
13897        if (checkin) {
13898            pw.println("vers,1");
13899        }
13900
13901        // reader
13902        synchronized (mPackages) {
13903            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13904                if (!checkin) {
13905                    if (dumpState.onTitlePrinted())
13906                        pw.println();
13907                    pw.println("Database versions:");
13908                    pw.print("  SDK Version:");
13909                    pw.print(" internal=");
13910                    pw.print(mSettings.mInternalSdkPlatform);
13911                    pw.print(" external=");
13912                    pw.println(mSettings.mExternalSdkPlatform);
13913                    pw.print("  DB Version:");
13914                    pw.print(" internal=");
13915                    pw.print(mSettings.mInternalDatabaseVersion);
13916                    pw.print(" external=");
13917                    pw.println(mSettings.mExternalDatabaseVersion);
13918                }
13919            }
13920
13921            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13922                if (!checkin) {
13923                    if (dumpState.onTitlePrinted())
13924                        pw.println();
13925                    pw.println("Verifiers:");
13926                    pw.print("  Required: ");
13927                    pw.print(mRequiredVerifierPackage);
13928                    pw.print(" (uid=");
13929                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13930                    pw.println(")");
13931                } else if (mRequiredVerifierPackage != null) {
13932                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13933                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13934                }
13935            }
13936
13937            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13938                    packageName == null) {
13939                if (mIntentFilterVerifierComponent != null) {
13940                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13941                    if (!checkin) {
13942                        if (dumpState.onTitlePrinted())
13943                            pw.println();
13944                        pw.println("Intent Filter Verifier:");
13945                        pw.print("  Using: ");
13946                        pw.print(verifierPackageName);
13947                        pw.print(" (uid=");
13948                        pw.print(getPackageUid(verifierPackageName, 0));
13949                        pw.println(")");
13950                    } else if (verifierPackageName != null) {
13951                        pw.print("ifv,"); pw.print(verifierPackageName);
13952                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13953                    }
13954                } else {
13955                    pw.println();
13956                    pw.println("No Intent Filter Verifier available!");
13957                }
13958            }
13959
13960            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13961                boolean printedHeader = false;
13962                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13963                while (it.hasNext()) {
13964                    String name = it.next();
13965                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13966                    if (!checkin) {
13967                        if (!printedHeader) {
13968                            if (dumpState.onTitlePrinted())
13969                                pw.println();
13970                            pw.println("Libraries:");
13971                            printedHeader = true;
13972                        }
13973                        pw.print("  ");
13974                    } else {
13975                        pw.print("lib,");
13976                    }
13977                    pw.print(name);
13978                    if (!checkin) {
13979                        pw.print(" -> ");
13980                    }
13981                    if (ent.path != null) {
13982                        if (!checkin) {
13983                            pw.print("(jar) ");
13984                            pw.print(ent.path);
13985                        } else {
13986                            pw.print(",jar,");
13987                            pw.print(ent.path);
13988                        }
13989                    } else {
13990                        if (!checkin) {
13991                            pw.print("(apk) ");
13992                            pw.print(ent.apk);
13993                        } else {
13994                            pw.print(",apk,");
13995                            pw.print(ent.apk);
13996                        }
13997                    }
13998                    pw.println();
13999                }
14000            }
14001
14002            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14003                if (dumpState.onTitlePrinted())
14004                    pw.println();
14005                if (!checkin) {
14006                    pw.println("Features:");
14007                }
14008                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14009                while (it.hasNext()) {
14010                    String name = it.next();
14011                    if (!checkin) {
14012                        pw.print("  ");
14013                    } else {
14014                        pw.print("feat,");
14015                    }
14016                    pw.println(name);
14017                }
14018            }
14019
14020            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14021                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14022                        : "Activity Resolver Table:", "  ", packageName,
14023                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14024                    dumpState.setTitlePrinted(true);
14025                }
14026                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14027                        : "Receiver Resolver Table:", "  ", packageName,
14028                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14029                    dumpState.setTitlePrinted(true);
14030                }
14031                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14032                        : "Service Resolver Table:", "  ", packageName,
14033                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14034                    dumpState.setTitlePrinted(true);
14035                }
14036                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14037                        : "Provider Resolver Table:", "  ", packageName,
14038                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14039                    dumpState.setTitlePrinted(true);
14040                }
14041            }
14042
14043            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14044                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14045                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14046                    int user = mSettings.mPreferredActivities.keyAt(i);
14047                    if (pir.dump(pw,
14048                            dumpState.getTitlePrinted()
14049                                ? "\nPreferred Activities User " + user + ":"
14050                                : "Preferred Activities User " + user + ":", "  ",
14051                            packageName, true, false)) {
14052                        dumpState.setTitlePrinted(true);
14053                    }
14054                }
14055            }
14056
14057            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14058                pw.flush();
14059                FileOutputStream fout = new FileOutputStream(fd);
14060                BufferedOutputStream str = new BufferedOutputStream(fout);
14061                XmlSerializer serializer = new FastXmlSerializer();
14062                try {
14063                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14064                    serializer.startDocument(null, true);
14065                    serializer.setFeature(
14066                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14067                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14068                    serializer.endDocument();
14069                    serializer.flush();
14070                } catch (IllegalArgumentException e) {
14071                    pw.println("Failed writing: " + e);
14072                } catch (IllegalStateException e) {
14073                    pw.println("Failed writing: " + e);
14074                } catch (IOException e) {
14075                    pw.println("Failed writing: " + e);
14076                }
14077            }
14078
14079            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
14080                pw.println();
14081                int count = mSettings.mPackages.size();
14082                if (count == 0) {
14083                    pw.println("No domain preferred apps!");
14084                    pw.println();
14085                } else {
14086                    final String prefix = "  ";
14087                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14088                    if (allPackageSettings.size() == 0) {
14089                        pw.println("No domain preferred apps!");
14090                        pw.println();
14091                    } else {
14092                        pw.println("Domain preferred apps status:");
14093                        pw.println();
14094                        count = 0;
14095                        for (PackageSetting ps : allPackageSettings) {
14096                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14097                            if (ivi == null || ivi.getPackageName() == null) continue;
14098                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14099                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14100                            pw.println(prefix + "Status: " + ivi.getStatusString());
14101                            pw.println();
14102                            count++;
14103                        }
14104                        if (count == 0) {
14105                            pw.println(prefix + "No domain preferred app status!");
14106                            pw.println();
14107                        }
14108                        for (int userId : sUserManager.getUserIds()) {
14109                            pw.println("Domain preferred apps for User " + userId + ":");
14110                            pw.println();
14111                            count = 0;
14112                            for (PackageSetting ps : allPackageSettings) {
14113                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14114                                if (ivi == null || ivi.getPackageName() == null) {
14115                                    continue;
14116                                }
14117                                final int status = ps.getDomainVerificationStatusForUser(userId);
14118                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14119                                    continue;
14120                                }
14121                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14122                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14123                                String statusStr = IntentFilterVerificationInfo.
14124                                        getStatusStringFromValue(status);
14125                                pw.println(prefix + "Status: " + statusStr);
14126                                pw.println();
14127                                count++;
14128                            }
14129                            if (count == 0) {
14130                                pw.println(prefix + "No domain preferred apps!");
14131                                pw.println();
14132                            }
14133                        }
14134                    }
14135                }
14136            }
14137
14138            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14139                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14140                if (packageName == null) {
14141                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14142                        if (iperm == 0) {
14143                            if (dumpState.onTitlePrinted())
14144                                pw.println();
14145                            pw.println("AppOp Permissions:");
14146                        }
14147                        pw.print("  AppOp Permission ");
14148                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14149                        pw.println(":");
14150                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14151                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14152                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14153                        }
14154                    }
14155                }
14156            }
14157
14158            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14159                boolean printedSomething = false;
14160                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14161                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14162                        continue;
14163                    }
14164                    if (!printedSomething) {
14165                        if (dumpState.onTitlePrinted())
14166                            pw.println();
14167                        pw.println("Registered ContentProviders:");
14168                        printedSomething = true;
14169                    }
14170                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14171                    pw.print("    "); pw.println(p.toString());
14172                }
14173                printedSomething = false;
14174                for (Map.Entry<String, PackageParser.Provider> entry :
14175                        mProvidersByAuthority.entrySet()) {
14176                    PackageParser.Provider p = entry.getValue();
14177                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14178                        continue;
14179                    }
14180                    if (!printedSomething) {
14181                        if (dumpState.onTitlePrinted())
14182                            pw.println();
14183                        pw.println("ContentProvider Authorities:");
14184                        printedSomething = true;
14185                    }
14186                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14187                    pw.print("    "); pw.println(p.toString());
14188                    if (p.info != null && p.info.applicationInfo != null) {
14189                        final String appInfo = p.info.applicationInfo.toString();
14190                        pw.print("      applicationInfo="); pw.println(appInfo);
14191                    }
14192                }
14193            }
14194
14195            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14196                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14197            }
14198
14199            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14200                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14201            }
14202
14203            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14204                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14205            }
14206
14207            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14208                // XXX should handle packageName != null by dumping only install data that
14209                // the given package is involved with.
14210                if (dumpState.onTitlePrinted()) pw.println();
14211                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14212            }
14213
14214            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14215                if (dumpState.onTitlePrinted()) pw.println();
14216                mSettings.dumpReadMessagesLPr(pw, dumpState);
14217
14218                pw.println();
14219                pw.println("Package warning messages:");
14220                BufferedReader in = null;
14221                String line = null;
14222                try {
14223                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14224                    while ((line = in.readLine()) != null) {
14225                        if (line.contains("ignored: updated version")) continue;
14226                        pw.println(line);
14227                    }
14228                } catch (IOException ignored) {
14229                } finally {
14230                    IoUtils.closeQuietly(in);
14231                }
14232            }
14233
14234            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14235                BufferedReader in = null;
14236                String line = null;
14237                try {
14238                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14239                    while ((line = in.readLine()) != null) {
14240                        if (line.contains("ignored: updated version")) continue;
14241                        pw.print("msg,");
14242                        pw.println(line);
14243                    }
14244                } catch (IOException ignored) {
14245                } finally {
14246                    IoUtils.closeQuietly(in);
14247                }
14248            }
14249        }
14250    }
14251
14252    // ------- apps on sdcard specific code -------
14253    static final boolean DEBUG_SD_INSTALL = false;
14254
14255    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14256
14257    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14258
14259    private boolean mMediaMounted = false;
14260
14261    static String getEncryptKey() {
14262        try {
14263            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14264                    SD_ENCRYPTION_KEYSTORE_NAME);
14265            if (sdEncKey == null) {
14266                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14267                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14268                if (sdEncKey == null) {
14269                    Slog.e(TAG, "Failed to create encryption keys");
14270                    return null;
14271                }
14272            }
14273            return sdEncKey;
14274        } catch (NoSuchAlgorithmException nsae) {
14275            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14276            return null;
14277        } catch (IOException ioe) {
14278            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14279            return null;
14280        }
14281    }
14282
14283    /*
14284     * Update media status on PackageManager.
14285     */
14286    @Override
14287    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14288        int callingUid = Binder.getCallingUid();
14289        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14290            throw new SecurityException("Media status can only be updated by the system");
14291        }
14292        // reader; this apparently protects mMediaMounted, but should probably
14293        // be a different lock in that case.
14294        synchronized (mPackages) {
14295            Log.i(TAG, "Updating external media status from "
14296                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14297                    + (mediaStatus ? "mounted" : "unmounted"));
14298            if (DEBUG_SD_INSTALL)
14299                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14300                        + ", mMediaMounted=" + mMediaMounted);
14301            if (mediaStatus == mMediaMounted) {
14302                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14303                        : 0, -1);
14304                mHandler.sendMessage(msg);
14305                return;
14306            }
14307            mMediaMounted = mediaStatus;
14308        }
14309        // Queue up an async operation since the package installation may take a
14310        // little while.
14311        mHandler.post(new Runnable() {
14312            public void run() {
14313                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14314            }
14315        });
14316    }
14317
14318    /**
14319     * Called by MountService when the initial ASECs to scan are available.
14320     * Should block until all the ASEC containers are finished being scanned.
14321     */
14322    public void scanAvailableAsecs() {
14323        updateExternalMediaStatusInner(true, false, false);
14324        if (mShouldRestoreconData) {
14325            SELinuxMMAC.setRestoreconDone();
14326            mShouldRestoreconData = false;
14327        }
14328    }
14329
14330    /*
14331     * Collect information of applications on external media, map them against
14332     * existing containers and update information based on current mount status.
14333     * Please note that we always have to report status if reportStatus has been
14334     * set to true especially when unloading packages.
14335     */
14336    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14337            boolean externalStorage) {
14338        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14339        int[] uidArr = EmptyArray.INT;
14340
14341        final String[] list = PackageHelper.getSecureContainerList();
14342        if (ArrayUtils.isEmpty(list)) {
14343            Log.i(TAG, "No secure containers found");
14344        } else {
14345            // Process list of secure containers and categorize them
14346            // as active or stale based on their package internal state.
14347
14348            // reader
14349            synchronized (mPackages) {
14350                for (String cid : list) {
14351                    // Leave stages untouched for now; installer service owns them
14352                    if (PackageInstallerService.isStageName(cid)) continue;
14353
14354                    if (DEBUG_SD_INSTALL)
14355                        Log.i(TAG, "Processing container " + cid);
14356                    String pkgName = getAsecPackageName(cid);
14357                    if (pkgName == null) {
14358                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14359                        continue;
14360                    }
14361                    if (DEBUG_SD_INSTALL)
14362                        Log.i(TAG, "Looking for pkg : " + pkgName);
14363
14364                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14365                    if (ps == null) {
14366                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14367                        continue;
14368                    }
14369
14370                    /*
14371                     * Skip packages that are not external if we're unmounting
14372                     * external storage.
14373                     */
14374                    if (externalStorage && !isMounted && !isExternal(ps)) {
14375                        continue;
14376                    }
14377
14378                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14379                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14380                    // The package status is changed only if the code path
14381                    // matches between settings and the container id.
14382                    if (ps.codePathString != null
14383                            && ps.codePathString.startsWith(args.getCodePath())) {
14384                        if (DEBUG_SD_INSTALL) {
14385                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14386                                    + " at code path: " + ps.codePathString);
14387                        }
14388
14389                        // We do have a valid package installed on sdcard
14390                        processCids.put(args, ps.codePathString);
14391                        final int uid = ps.appId;
14392                        if (uid != -1) {
14393                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14394                        }
14395                    } else {
14396                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14397                                + ps.codePathString);
14398                    }
14399                }
14400            }
14401
14402            Arrays.sort(uidArr);
14403        }
14404
14405        // Process packages with valid entries.
14406        if (isMounted) {
14407            if (DEBUG_SD_INSTALL)
14408                Log.i(TAG, "Loading packages");
14409            loadMediaPackages(processCids, uidArr);
14410            startCleaningPackages();
14411            mInstallerService.onSecureContainersAvailable();
14412        } else {
14413            if (DEBUG_SD_INSTALL)
14414                Log.i(TAG, "Unloading packages");
14415            unloadMediaPackages(processCids, uidArr, reportStatus);
14416        }
14417    }
14418
14419    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14420            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14421        final int size = infos.size();
14422        final String[] packageNames = new String[size];
14423        final int[] packageUids = new int[size];
14424        for (int i = 0; i < size; i++) {
14425            final ApplicationInfo info = infos.get(i);
14426            packageNames[i] = info.packageName;
14427            packageUids[i] = info.uid;
14428        }
14429        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14430                finishedReceiver);
14431    }
14432
14433    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14434            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14435        sendResourcesChangedBroadcast(mediaStatus, replacing,
14436                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14437    }
14438
14439    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14440            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14441        int size = pkgList.length;
14442        if (size > 0) {
14443            // Send broadcasts here
14444            Bundle extras = new Bundle();
14445            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14446            if (uidArr != null) {
14447                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14448            }
14449            if (replacing) {
14450                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14451            }
14452            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14453                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14454            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14455        }
14456    }
14457
14458   /*
14459     * Look at potentially valid container ids from processCids If package
14460     * information doesn't match the one on record or package scanning fails,
14461     * the cid is added to list of removeCids. We currently don't delete stale
14462     * containers.
14463     */
14464    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14465        ArrayList<String> pkgList = new ArrayList<String>();
14466        Set<AsecInstallArgs> keys = processCids.keySet();
14467
14468        for (AsecInstallArgs args : keys) {
14469            String codePath = processCids.get(args);
14470            if (DEBUG_SD_INSTALL)
14471                Log.i(TAG, "Loading container : " + args.cid);
14472            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14473            try {
14474                // Make sure there are no container errors first.
14475                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14476                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14477                            + " when installing from sdcard");
14478                    continue;
14479                }
14480                // Check code path here.
14481                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14482                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14483                            + " does not match one in settings " + codePath);
14484                    continue;
14485                }
14486                // Parse package
14487                int parseFlags = mDefParseFlags;
14488                if (args.isExternalAsec()) {
14489                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14490                }
14491                if (args.isFwdLocked()) {
14492                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14493                }
14494
14495                synchronized (mInstallLock) {
14496                    PackageParser.Package pkg = null;
14497                    try {
14498                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14499                    } catch (PackageManagerException e) {
14500                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14501                    }
14502                    // Scan the package
14503                    if (pkg != null) {
14504                        /*
14505                         * TODO why is the lock being held? doPostInstall is
14506                         * called in other places without the lock. This needs
14507                         * to be straightened out.
14508                         */
14509                        // writer
14510                        synchronized (mPackages) {
14511                            retCode = PackageManager.INSTALL_SUCCEEDED;
14512                            pkgList.add(pkg.packageName);
14513                            // Post process args
14514                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14515                                    pkg.applicationInfo.uid);
14516                        }
14517                    } else {
14518                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14519                    }
14520                }
14521
14522            } finally {
14523                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14524                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14525                }
14526            }
14527        }
14528        // writer
14529        synchronized (mPackages) {
14530            // If the platform SDK has changed since the last time we booted,
14531            // we need to re-grant app permission to catch any new ones that
14532            // appear. This is really a hack, and means that apps can in some
14533            // cases get permissions that the user didn't initially explicitly
14534            // allow... it would be nice to have some better way to handle
14535            // this situation.
14536            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14537            if (regrantPermissions)
14538                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14539                        + mSdkVersion + "; regranting permissions for external storage");
14540            mSettings.mExternalSdkPlatform = mSdkVersion;
14541
14542            // Make sure group IDs have been assigned, and any permission
14543            // changes in other apps are accounted for
14544            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14545                    | (regrantPermissions
14546                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14547                            : 0));
14548
14549            mSettings.updateExternalDatabaseVersion();
14550
14551            // can downgrade to reader
14552            // Persist settings
14553            mSettings.writeLPr();
14554        }
14555        // Send a broadcast to let everyone know we are done processing
14556        if (pkgList.size() > 0) {
14557            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14558        }
14559    }
14560
14561   /*
14562     * Utility method to unload a list of specified containers
14563     */
14564    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14565        // Just unmount all valid containers.
14566        for (AsecInstallArgs arg : cidArgs) {
14567            synchronized (mInstallLock) {
14568                arg.doPostDeleteLI(false);
14569           }
14570       }
14571   }
14572
14573    /*
14574     * Unload packages mounted on external media. This involves deleting package
14575     * data from internal structures, sending broadcasts about diabled packages,
14576     * gc'ing to free up references, unmounting all secure containers
14577     * corresponding to packages on external media, and posting a
14578     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14579     * that we always have to post this message if status has been requested no
14580     * matter what.
14581     */
14582    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14583            final boolean reportStatus) {
14584        if (DEBUG_SD_INSTALL)
14585            Log.i(TAG, "unloading media packages");
14586        ArrayList<String> pkgList = new ArrayList<String>();
14587        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14588        final Set<AsecInstallArgs> keys = processCids.keySet();
14589        for (AsecInstallArgs args : keys) {
14590            String pkgName = args.getPackageName();
14591            if (DEBUG_SD_INSTALL)
14592                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14593            // Delete package internally
14594            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14595            synchronized (mInstallLock) {
14596                boolean res = deletePackageLI(pkgName, null, false, null, null,
14597                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14598                if (res) {
14599                    pkgList.add(pkgName);
14600                } else {
14601                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14602                    failedList.add(args);
14603                }
14604            }
14605        }
14606
14607        // reader
14608        synchronized (mPackages) {
14609            // We didn't update the settings after removing each package;
14610            // write them now for all packages.
14611            mSettings.writeLPr();
14612        }
14613
14614        // We have to absolutely send UPDATED_MEDIA_STATUS only
14615        // after confirming that all the receivers processed the ordered
14616        // broadcast when packages get disabled, force a gc to clean things up.
14617        // and unload all the containers.
14618        if (pkgList.size() > 0) {
14619            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14620                    new IIntentReceiver.Stub() {
14621                public void performReceive(Intent intent, int resultCode, String data,
14622                        Bundle extras, boolean ordered, boolean sticky,
14623                        int sendingUser) throws RemoteException {
14624                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14625                            reportStatus ? 1 : 0, 1, keys);
14626                    mHandler.sendMessage(msg);
14627                }
14628            });
14629        } else {
14630            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14631                    keys);
14632            mHandler.sendMessage(msg);
14633        }
14634    }
14635
14636    private void loadPrivatePackages(VolumeInfo vol) {
14637        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14638        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14639        synchronized (mInstallLock) {
14640        synchronized (mPackages) {
14641            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14642            for (PackageSetting ps : packages) {
14643                final PackageParser.Package pkg;
14644                try {
14645                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14646                    loaded.add(pkg.applicationInfo);
14647                } catch (PackageManagerException e) {
14648                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14649                }
14650            }
14651
14652            // TODO: regrant any permissions that changed based since original install
14653
14654            mSettings.writeLPr();
14655        }
14656        }
14657
14658        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
14659        sendResourcesChangedBroadcast(true, false, loaded, null);
14660    }
14661
14662    private void unloadPrivatePackages(VolumeInfo vol) {
14663        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14664        synchronized (mInstallLock) {
14665        synchronized (mPackages) {
14666            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14667            for (PackageSetting ps : packages) {
14668                if (ps.pkg == null) continue;
14669
14670                final ApplicationInfo info = ps.pkg.applicationInfo;
14671                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14672                if (deletePackageLI(ps.name, null, false, null, null,
14673                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14674                    unloaded.add(info);
14675                } else {
14676                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14677                }
14678            }
14679
14680            mSettings.writeLPr();
14681        }
14682        }
14683
14684        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
14685        sendResourcesChangedBroadcast(false, false, unloaded, null);
14686    }
14687
14688    private void unfreezePackage(String packageName) {
14689        synchronized (mPackages) {
14690            final PackageSetting ps = mSettings.mPackages.get(packageName);
14691            if (ps != null) {
14692                ps.frozen = false;
14693            }
14694        }
14695    }
14696
14697    @Override
14698    public int movePackage(final String packageName, final String volumeUuid) {
14699        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14700
14701        final int moveId = mNextMoveId.getAndIncrement();
14702        try {
14703            movePackageInternal(packageName, volumeUuid, moveId);
14704        } catch (PackageManagerException e) {
14705            Slog.w(TAG, "Failed to move " + packageName, e);
14706            mMoveCallbacks.notifyStatusChanged(moveId,
14707                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14708        }
14709        return moveId;
14710    }
14711
14712    private void movePackageInternal(final String packageName, final String volumeUuid,
14713            final int moveId) throws PackageManagerException {
14714        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14715        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14716        final PackageManager pm = mContext.getPackageManager();
14717
14718        final boolean currentAsec;
14719        final String currentVolumeUuid;
14720        final File codeFile;
14721        final String installerPackageName;
14722        final String packageAbiOverride;
14723        final int appId;
14724        final String seinfo;
14725        final String label;
14726
14727        // reader
14728        synchronized (mPackages) {
14729            final PackageParser.Package pkg = mPackages.get(packageName);
14730            final PackageSetting ps = mSettings.mPackages.get(packageName);
14731            if (pkg == null || ps == null) {
14732                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14733            }
14734
14735            if (pkg.applicationInfo.isSystemApp()) {
14736                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14737                        "Cannot move system application");
14738            }
14739
14740            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14741                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14742                        "Package already moved to " + volumeUuid);
14743            }
14744
14745            final File probe = new File(pkg.codePath);
14746            final File probeOat = new File(probe, "oat");
14747            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14748                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14749                        "Move only supported for modern cluster style installs");
14750            }
14751
14752            if (ps.frozen) {
14753                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14754                        "Failed to move already frozen package");
14755            }
14756            ps.frozen = true;
14757
14758            currentAsec = pkg.applicationInfo.isForwardLocked()
14759                    || pkg.applicationInfo.isExternalAsec();
14760            currentVolumeUuid = ps.volumeUuid;
14761            codeFile = new File(pkg.codePath);
14762            installerPackageName = ps.installerPackageName;
14763            packageAbiOverride = ps.cpuAbiOverrideString;
14764            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14765            seinfo = pkg.applicationInfo.seinfo;
14766            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14767        }
14768
14769        // Now that we're guarded by frozen state, kill app during move
14770        killApplication(packageName, appId, "move pkg");
14771
14772        final Bundle extras = new Bundle();
14773        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14774        extras.putString(Intent.EXTRA_TITLE, label);
14775        mMoveCallbacks.notifyCreated(moveId, extras);
14776
14777        int installFlags;
14778        final boolean moveCompleteApp;
14779        final File measurePath;
14780
14781        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14782            installFlags = INSTALL_INTERNAL;
14783            moveCompleteApp = !currentAsec;
14784            measurePath = Environment.getDataAppDirectory(volumeUuid);
14785        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14786            installFlags = INSTALL_EXTERNAL;
14787            moveCompleteApp = false;
14788            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14789        } else {
14790            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14791            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14792                    || !volume.isMountedWritable()) {
14793                unfreezePackage(packageName);
14794                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14795                        "Move location not mounted private volume");
14796            }
14797
14798            Preconditions.checkState(!currentAsec);
14799
14800            installFlags = INSTALL_INTERNAL;
14801            moveCompleteApp = true;
14802            measurePath = Environment.getDataAppDirectory(volumeUuid);
14803        }
14804
14805        final PackageStats stats = new PackageStats(null, -1);
14806        synchronized (mInstaller) {
14807            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14808                unfreezePackage(packageName);
14809                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14810                        "Failed to measure package size");
14811            }
14812        }
14813
14814        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
14815                + stats.dataSize);
14816
14817        final long startFreeBytes = measurePath.getFreeSpace();
14818        final long sizeBytes;
14819        if (moveCompleteApp) {
14820            sizeBytes = stats.codeSize + stats.dataSize;
14821        } else {
14822            sizeBytes = stats.codeSize;
14823        }
14824
14825        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14826            unfreezePackage(packageName);
14827            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14828                    "Not enough free space to move");
14829        }
14830
14831        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14832
14833        final CountDownLatch installedLatch = new CountDownLatch(1);
14834        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14835            @Override
14836            public void onUserActionRequired(Intent intent) throws RemoteException {
14837                throw new IllegalStateException();
14838            }
14839
14840            @Override
14841            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14842                    Bundle extras) throws RemoteException {
14843                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
14844                        + PackageManager.installStatusToString(returnCode, msg));
14845
14846                installedLatch.countDown();
14847
14848                // Regardless of success or failure of the move operation,
14849                // always unfreeze the package
14850                unfreezePackage(packageName);
14851
14852                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14853                switch (status) {
14854                    case PackageInstaller.STATUS_SUCCESS:
14855                        mMoveCallbacks.notifyStatusChanged(moveId,
14856                                PackageManager.MOVE_SUCCEEDED);
14857                        break;
14858                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14859                        mMoveCallbacks.notifyStatusChanged(moveId,
14860                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14861                        break;
14862                    default:
14863                        mMoveCallbacks.notifyStatusChanged(moveId,
14864                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14865                        break;
14866                }
14867            }
14868        };
14869
14870        final MoveInfo move;
14871        if (moveCompleteApp) {
14872            // Kick off a thread to report progress estimates
14873            new Thread() {
14874                @Override
14875                public void run() {
14876                    while (true) {
14877                        try {
14878                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14879                                break;
14880                            }
14881                        } catch (InterruptedException ignored) {
14882                        }
14883
14884                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14885                        final int progress = 10 + (int) MathUtils.constrain(
14886                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14887                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14888                    }
14889                }
14890            }.start();
14891
14892            final String dataAppName = codeFile.getName();
14893            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14894                    dataAppName, appId, seinfo);
14895        } else {
14896            move = null;
14897        }
14898
14899        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14900
14901        final Message msg = mHandler.obtainMessage(INIT_COPY);
14902        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14903        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14904                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14905        mHandler.sendMessage(msg);
14906    }
14907
14908    @Override
14909    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14910        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14911
14912        final int realMoveId = mNextMoveId.getAndIncrement();
14913        final Bundle extras = new Bundle();
14914        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14915        mMoveCallbacks.notifyCreated(realMoveId, extras);
14916
14917        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14918            @Override
14919            public void onCreated(int moveId, Bundle extras) {
14920                // Ignored
14921            }
14922
14923            @Override
14924            public void onStatusChanged(int moveId, int status, long estMillis) {
14925                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14926            }
14927        };
14928
14929        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14930        storage.setPrimaryStorageUuid(volumeUuid, callback);
14931        return realMoveId;
14932    }
14933
14934    @Override
14935    public int getMoveStatus(int moveId) {
14936        mContext.enforceCallingOrSelfPermission(
14937                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14938        return mMoveCallbacks.mLastStatus.get(moveId);
14939    }
14940
14941    @Override
14942    public void registerMoveCallback(IPackageMoveObserver callback) {
14943        mContext.enforceCallingOrSelfPermission(
14944                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14945        mMoveCallbacks.register(callback);
14946    }
14947
14948    @Override
14949    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14950        mContext.enforceCallingOrSelfPermission(
14951                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14952        mMoveCallbacks.unregister(callback);
14953    }
14954
14955    @Override
14956    public boolean setInstallLocation(int loc) {
14957        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14958                null);
14959        if (getInstallLocation() == loc) {
14960            return true;
14961        }
14962        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14963                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14964            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14965                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14966            return true;
14967        }
14968        return false;
14969   }
14970
14971    @Override
14972    public int getInstallLocation() {
14973        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14974                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14975                PackageHelper.APP_INSTALL_AUTO);
14976    }
14977
14978    /** Called by UserManagerService */
14979    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14980        mDirtyUsers.remove(userHandle);
14981        mSettings.removeUserLPw(userHandle);
14982        mPendingBroadcasts.remove(userHandle);
14983        if (mInstaller != null) {
14984            // Technically, we shouldn't be doing this with the package lock
14985            // held.  However, this is very rare, and there is already so much
14986            // other disk I/O going on, that we'll let it slide for now.
14987            final StorageManager storage = StorageManager.from(mContext);
14988            final List<VolumeInfo> vols = storage.getVolumes();
14989            for (VolumeInfo vol : vols) {
14990                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14991                    final String volumeUuid = vol.getFsUuid();
14992                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14993                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14994                }
14995            }
14996        }
14997        mUserNeedsBadging.delete(userHandle);
14998        removeUnusedPackagesLILPw(userManager, userHandle);
14999    }
15000
15001    /**
15002     * We're removing userHandle and would like to remove any downloaded packages
15003     * that are no longer in use by any other user.
15004     * @param userHandle the user being removed
15005     */
15006    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15007        final boolean DEBUG_CLEAN_APKS = false;
15008        int [] users = userManager.getUserIdsLPr();
15009        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15010        while (psit.hasNext()) {
15011            PackageSetting ps = psit.next();
15012            if (ps.pkg == null) {
15013                continue;
15014            }
15015            final String packageName = ps.pkg.packageName;
15016            // Skip over if system app
15017            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15018                continue;
15019            }
15020            if (DEBUG_CLEAN_APKS) {
15021                Slog.i(TAG, "Checking package " + packageName);
15022            }
15023            boolean keep = false;
15024            for (int i = 0; i < users.length; i++) {
15025                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15026                    keep = true;
15027                    if (DEBUG_CLEAN_APKS) {
15028                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15029                                + users[i]);
15030                    }
15031                    break;
15032                }
15033            }
15034            if (!keep) {
15035                if (DEBUG_CLEAN_APKS) {
15036                    Slog.i(TAG, "  Removing package " + packageName);
15037                }
15038                mHandler.post(new Runnable() {
15039                    public void run() {
15040                        deletePackageX(packageName, userHandle, 0);
15041                    } //end run
15042                });
15043            }
15044        }
15045    }
15046
15047    /** Called by UserManagerService */
15048    void createNewUserLILPw(int userHandle, File path) {
15049        if (mInstaller != null) {
15050            mInstaller.createUserConfig(userHandle);
15051            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15052        }
15053    }
15054
15055    void newUserCreatedLILPw(int userHandle) {
15056        // Adding a user requires updating runtime permissions for system apps.
15057        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
15058    }
15059
15060    @Override
15061    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15062        mContext.enforceCallingOrSelfPermission(
15063                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15064                "Only package verification agents can read the verifier device identity");
15065
15066        synchronized (mPackages) {
15067            return mSettings.getVerifierDeviceIdentityLPw();
15068        }
15069    }
15070
15071    @Override
15072    public void setPermissionEnforced(String permission, boolean enforced) {
15073        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15074        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15075            synchronized (mPackages) {
15076                if (mSettings.mReadExternalStorageEnforced == null
15077                        || mSettings.mReadExternalStorageEnforced != enforced) {
15078                    mSettings.mReadExternalStorageEnforced = enforced;
15079                    mSettings.writeLPr();
15080                }
15081            }
15082            // kill any non-foreground processes so we restart them and
15083            // grant/revoke the GID.
15084            final IActivityManager am = ActivityManagerNative.getDefault();
15085            if (am != null) {
15086                final long token = Binder.clearCallingIdentity();
15087                try {
15088                    am.killProcessesBelowForeground("setPermissionEnforcement");
15089                } catch (RemoteException e) {
15090                } finally {
15091                    Binder.restoreCallingIdentity(token);
15092                }
15093            }
15094        } else {
15095            throw new IllegalArgumentException("No selective enforcement for " + permission);
15096        }
15097    }
15098
15099    @Override
15100    @Deprecated
15101    public boolean isPermissionEnforced(String permission) {
15102        return true;
15103    }
15104
15105    @Override
15106    public boolean isStorageLow() {
15107        final long token = Binder.clearCallingIdentity();
15108        try {
15109            final DeviceStorageMonitorInternal
15110                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15111            if (dsm != null) {
15112                return dsm.isMemoryLow();
15113            } else {
15114                return false;
15115            }
15116        } finally {
15117            Binder.restoreCallingIdentity(token);
15118        }
15119    }
15120
15121    @Override
15122    public IPackageInstaller getPackageInstaller() {
15123        return mInstallerService;
15124    }
15125
15126    private boolean userNeedsBadging(int userId) {
15127        int index = mUserNeedsBadging.indexOfKey(userId);
15128        if (index < 0) {
15129            final UserInfo userInfo;
15130            final long token = Binder.clearCallingIdentity();
15131            try {
15132                userInfo = sUserManager.getUserInfo(userId);
15133            } finally {
15134                Binder.restoreCallingIdentity(token);
15135            }
15136            final boolean b;
15137            if (userInfo != null && userInfo.isManagedProfile()) {
15138                b = true;
15139            } else {
15140                b = false;
15141            }
15142            mUserNeedsBadging.put(userId, b);
15143            return b;
15144        }
15145        return mUserNeedsBadging.valueAt(index);
15146    }
15147
15148    @Override
15149    public KeySet getKeySetByAlias(String packageName, String alias) {
15150        if (packageName == null || alias == null) {
15151            return null;
15152        }
15153        synchronized(mPackages) {
15154            final PackageParser.Package pkg = mPackages.get(packageName);
15155            if (pkg == null) {
15156                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15157                throw new IllegalArgumentException("Unknown package: " + packageName);
15158            }
15159            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15160            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15161        }
15162    }
15163
15164    @Override
15165    public KeySet getSigningKeySet(String packageName) {
15166        if (packageName == null) {
15167            return null;
15168        }
15169        synchronized(mPackages) {
15170            final PackageParser.Package pkg = mPackages.get(packageName);
15171            if (pkg == null) {
15172                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15173                throw new IllegalArgumentException("Unknown package: " + packageName);
15174            }
15175            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15176                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15177                throw new SecurityException("May not access signing KeySet of other apps.");
15178            }
15179            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15180            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15181        }
15182    }
15183
15184    @Override
15185    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15186        if (packageName == null || ks == null) {
15187            return false;
15188        }
15189        synchronized(mPackages) {
15190            final PackageParser.Package pkg = mPackages.get(packageName);
15191            if (pkg == null) {
15192                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15193                throw new IllegalArgumentException("Unknown package: " + packageName);
15194            }
15195            IBinder ksh = ks.getToken();
15196            if (ksh instanceof KeySetHandle) {
15197                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15198                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15199            }
15200            return false;
15201        }
15202    }
15203
15204    @Override
15205    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15206        if (packageName == null || ks == null) {
15207            return false;
15208        }
15209        synchronized(mPackages) {
15210            final PackageParser.Package pkg = mPackages.get(packageName);
15211            if (pkg == null) {
15212                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15213                throw new IllegalArgumentException("Unknown package: " + packageName);
15214            }
15215            IBinder ksh = ks.getToken();
15216            if (ksh instanceof KeySetHandle) {
15217                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15218                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15219            }
15220            return false;
15221        }
15222    }
15223
15224    public void getUsageStatsIfNoPackageUsageInfo() {
15225        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15226            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15227            if (usm == null) {
15228                throw new IllegalStateException("UsageStatsManager must be initialized");
15229            }
15230            long now = System.currentTimeMillis();
15231            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15232            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15233                String packageName = entry.getKey();
15234                PackageParser.Package pkg = mPackages.get(packageName);
15235                if (pkg == null) {
15236                    continue;
15237                }
15238                UsageStats usage = entry.getValue();
15239                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15240                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15241            }
15242        }
15243    }
15244
15245    /**
15246     * Check and throw if the given before/after packages would be considered a
15247     * downgrade.
15248     */
15249    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15250            throws PackageManagerException {
15251        if (after.versionCode < before.mVersionCode) {
15252            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15253                    "Update version code " + after.versionCode + " is older than current "
15254                    + before.mVersionCode);
15255        } else if (after.versionCode == before.mVersionCode) {
15256            if (after.baseRevisionCode < before.baseRevisionCode) {
15257                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15258                        "Update base revision code " + after.baseRevisionCode
15259                        + " is older than current " + before.baseRevisionCode);
15260            }
15261
15262            if (!ArrayUtils.isEmpty(after.splitNames)) {
15263                for (int i = 0; i < after.splitNames.length; i++) {
15264                    final String splitName = after.splitNames[i];
15265                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15266                    if (j != -1) {
15267                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15268                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15269                                    "Update split " + splitName + " revision code "
15270                                    + after.splitRevisionCodes[i] + " is older than current "
15271                                    + before.splitRevisionCodes[j]);
15272                        }
15273                    }
15274                }
15275            }
15276        }
15277    }
15278
15279    private static class MoveCallbacks extends Handler {
15280        private static final int MSG_CREATED = 1;
15281        private static final int MSG_STATUS_CHANGED = 2;
15282
15283        private final RemoteCallbackList<IPackageMoveObserver>
15284                mCallbacks = new RemoteCallbackList<>();
15285
15286        private final SparseIntArray mLastStatus = new SparseIntArray();
15287
15288        public MoveCallbacks(Looper looper) {
15289            super(looper);
15290        }
15291
15292        public void register(IPackageMoveObserver callback) {
15293            mCallbacks.register(callback);
15294        }
15295
15296        public void unregister(IPackageMoveObserver callback) {
15297            mCallbacks.unregister(callback);
15298        }
15299
15300        @Override
15301        public void handleMessage(Message msg) {
15302            final SomeArgs args = (SomeArgs) msg.obj;
15303            final int n = mCallbacks.beginBroadcast();
15304            for (int i = 0; i < n; i++) {
15305                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15306                try {
15307                    invokeCallback(callback, msg.what, args);
15308                } catch (RemoteException ignored) {
15309                }
15310            }
15311            mCallbacks.finishBroadcast();
15312            args.recycle();
15313        }
15314
15315        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15316                throws RemoteException {
15317            switch (what) {
15318                case MSG_CREATED: {
15319                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15320                    break;
15321                }
15322                case MSG_STATUS_CHANGED: {
15323                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15324                    break;
15325                }
15326            }
15327        }
15328
15329        private void notifyCreated(int moveId, Bundle extras) {
15330            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15331
15332            final SomeArgs args = SomeArgs.obtain();
15333            args.argi1 = moveId;
15334            args.arg2 = extras;
15335            obtainMessage(MSG_CREATED, args).sendToTarget();
15336        }
15337
15338        private void notifyStatusChanged(int moveId, int status) {
15339            notifyStatusChanged(moveId, status, -1);
15340        }
15341
15342        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15343            Slog.v(TAG, "Move " + moveId + " status " + status);
15344
15345            final SomeArgs args = SomeArgs.obtain();
15346            args.argi1 = moveId;
15347            args.argi2 = status;
15348            args.arg3 = estMillis;
15349            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15350
15351            synchronized (mLastStatus) {
15352                mLastStatus.put(moveId, status);
15353            }
15354        }
15355    }
15356
15357    private final class OnPermissionChangeListeners extends Handler {
15358        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15359
15360        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15361                new RemoteCallbackList<>();
15362
15363        public OnPermissionChangeListeners(Looper looper) {
15364            super(looper);
15365        }
15366
15367        @Override
15368        public void handleMessage(Message msg) {
15369            switch (msg.what) {
15370                case MSG_ON_PERMISSIONS_CHANGED: {
15371                    final int uid = msg.arg1;
15372                    handleOnPermissionsChanged(uid);
15373                } break;
15374            }
15375        }
15376
15377        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15378            mPermissionListeners.register(listener);
15379
15380        }
15381
15382        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15383            mPermissionListeners.unregister(listener);
15384        }
15385
15386        public void onPermissionsChanged(int uid) {
15387            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15388                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15389            }
15390        }
15391
15392        private void handleOnPermissionsChanged(int uid) {
15393            final int count = mPermissionListeners.beginBroadcast();
15394            try {
15395                for (int i = 0; i < count; i++) {
15396                    IOnPermissionsChangeListener callback = mPermissionListeners
15397                            .getBroadcastItem(i);
15398                    try {
15399                        callback.onPermissionsChanged(uid);
15400                    } catch (RemoteException e) {
15401                        Log.e(TAG, "Permission listener is dead", e);
15402                    }
15403                }
15404            } finally {
15405                mPermissionListeners.finishBroadcast();
15406            }
15407        }
15408    }
15409}
15410