PackageManagerService.java revision 726c45970e35e3fff3eeb4d86c3b772db73adcc7
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.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
68import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
69import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
70import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
71import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
72import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
73import static android.content.pm.PackageManager.PERMISSION_DENIED;
74import static android.content.pm.PackageManager.PERMISSION_GRANTED;
75import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
76import static android.content.pm.PackageParser.isApkFile;
77import static android.os.Process.PACKAGE_INFO_GID;
78import static android.os.Process.SYSTEM_UID;
79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
80import static android.system.OsConstants.O_CREAT;
81import static android.system.OsConstants.O_RDWR;
82
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
87import static com.android.internal.util.ArrayUtils.appendInt;
88import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
97
98import android.Manifest;
99import android.annotation.NonNull;
100import android.annotation.Nullable;
101import android.app.ActivityManager;
102import android.app.ActivityManagerNative;
103import android.app.IActivityManager;
104import android.app.admin.IDevicePolicyManager;
105import android.app.backup.IBackupManager;
106import android.content.BroadcastReceiver;
107import android.content.ComponentName;
108import android.content.Context;
109import android.content.IIntentReceiver;
110import android.content.Intent;
111import android.content.IntentFilter;
112import android.content.IntentSender;
113import android.content.IntentSender.SendIntentException;
114import android.content.ServiceConnection;
115import android.content.pm.ActivityInfo;
116import android.content.pm.ApplicationInfo;
117import android.content.pm.AppsQueryHelper;
118import android.content.pm.ComponentInfo;
119import android.content.pm.EphemeralApplicationInfo;
120import android.content.pm.EphemeralResolveInfo;
121import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
122import android.content.pm.FeatureInfo;
123import android.content.pm.IOnPermissionsChangeListener;
124import android.content.pm.IPackageDataObserver;
125import android.content.pm.IPackageDeleteObserver;
126import android.content.pm.IPackageDeleteObserver2;
127import android.content.pm.IPackageInstallObserver2;
128import android.content.pm.IPackageInstaller;
129import android.content.pm.IPackageManager;
130import android.content.pm.IPackageMoveObserver;
131import android.content.pm.IPackageStatsObserver;
132import android.content.pm.InstrumentationInfo;
133import android.content.pm.IntentFilterVerificationInfo;
134import android.content.pm.KeySet;
135import android.content.pm.PackageCleanItem;
136import android.content.pm.PackageInfo;
137import android.content.pm.PackageInfoLite;
138import android.content.pm.PackageInstaller;
139import android.content.pm.PackageManager;
140import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
141import android.content.pm.PackageManagerInternal;
142import android.content.pm.PackageParser;
143import android.content.pm.PackageParser.ActivityIntentInfo;
144import android.content.pm.PackageParser.PackageLite;
145import android.content.pm.PackageParser.PackageParserException;
146import android.content.pm.PackageStats;
147import android.content.pm.PackageUserState;
148import android.content.pm.ParceledListSlice;
149import android.content.pm.PermissionGroupInfo;
150import android.content.pm.PermissionInfo;
151import android.content.pm.ProviderInfo;
152import android.content.pm.ResolveInfo;
153import android.content.pm.ServiceInfo;
154import android.content.pm.Signature;
155import android.content.pm.UserInfo;
156import android.content.pm.VerificationParams;
157import android.content.pm.VerifierDeviceIdentity;
158import android.content.pm.VerifierInfo;
159import android.content.res.Resources;
160import android.graphics.Bitmap;
161import android.hardware.display.DisplayManager;
162import android.net.Uri;
163import android.os.Binder;
164import android.os.Build;
165import android.os.Bundle;
166import android.os.Debug;
167import android.os.Environment;
168import android.os.Environment.UserEnvironment;
169import android.os.FileUtils;
170import android.os.Handler;
171import android.os.IBinder;
172import android.os.Looper;
173import android.os.Message;
174import android.os.Parcel;
175import android.os.ParcelFileDescriptor;
176import android.os.Process;
177import android.os.RemoteCallbackList;
178import android.os.RemoteException;
179import android.os.ResultReceiver;
180import android.os.SELinux;
181import android.os.ServiceManager;
182import android.os.SystemClock;
183import android.os.SystemProperties;
184import android.os.Trace;
185import android.os.UserHandle;
186import android.os.UserManager;
187import android.os.storage.IMountService;
188import android.os.storage.MountServiceInternal;
189import android.os.storage.StorageEventListener;
190import android.os.storage.StorageManager;
191import android.os.storage.VolumeInfo;
192import android.os.storage.VolumeRecord;
193import android.security.KeyStore;
194import android.security.SystemKeyStore;
195import android.system.ErrnoException;
196import android.system.Os;
197import android.text.TextUtils;
198import android.text.format.DateUtils;
199import android.util.ArrayMap;
200import android.util.ArraySet;
201import android.util.AtomicFile;
202import android.util.DisplayMetrics;
203import android.util.EventLog;
204import android.util.ExceptionUtils;
205import android.util.Log;
206import android.util.LogPrinter;
207import android.util.MathUtils;
208import android.util.PrintStreamPrinter;
209import android.util.Slog;
210import android.util.SparseArray;
211import android.util.SparseBooleanArray;
212import android.util.SparseIntArray;
213import android.util.Xml;
214import android.view.Display;
215
216import com.android.internal.R;
217import com.android.internal.annotations.GuardedBy;
218import com.android.internal.app.IMediaContainerService;
219import com.android.internal.app.ResolverActivity;
220import com.android.internal.content.NativeLibraryHelper;
221import com.android.internal.content.PackageHelper;
222import com.android.internal.os.IParcelFileDescriptorFactory;
223import com.android.internal.os.InstallerConnection.InstallerException;
224import com.android.internal.os.SomeArgs;
225import com.android.internal.os.Zygote;
226import com.android.internal.util.ArrayUtils;
227import com.android.internal.util.FastPrintWriter;
228import com.android.internal.util.FastXmlSerializer;
229import com.android.internal.util.IndentingPrintWriter;
230import com.android.internal.util.Preconditions;
231import com.android.internal.util.XmlUtils;
232import com.android.server.EventLogTags;
233import com.android.server.FgThread;
234import com.android.server.IntentResolver;
235import com.android.server.LocalServices;
236import com.android.server.ServiceThread;
237import com.android.server.SystemConfig;
238import com.android.server.Watchdog;
239import com.android.server.pm.PermissionsState.PermissionState;
240import com.android.server.pm.Settings.DatabaseVersion;
241import com.android.server.pm.Settings.VersionInfo;
242import com.android.server.storage.DeviceStorageMonitorInternal;
243
244import dalvik.system.DexFile;
245import dalvik.system.VMRuntime;
246
247import libcore.io.IoUtils;
248import libcore.util.EmptyArray;
249
250import org.xmlpull.v1.XmlPullParser;
251import org.xmlpull.v1.XmlPullParserException;
252import org.xmlpull.v1.XmlSerializer;
253
254import java.io.BufferedInputStream;
255import java.io.BufferedOutputStream;
256import java.io.BufferedReader;
257import java.io.ByteArrayInputStream;
258import java.io.ByteArrayOutputStream;
259import java.io.File;
260import java.io.FileDescriptor;
261import java.io.FileNotFoundException;
262import java.io.FileOutputStream;
263import java.io.FileReader;
264import java.io.FilenameFilter;
265import java.io.IOException;
266import java.io.InputStream;
267import java.io.PrintWriter;
268import java.nio.charset.StandardCharsets;
269import java.security.MessageDigest;
270import java.security.NoSuchAlgorithmException;
271import java.security.PublicKey;
272import java.security.cert.CertificateEncodingException;
273import java.security.cert.CertificateException;
274import java.text.SimpleDateFormat;
275import java.util.ArrayList;
276import java.util.Arrays;
277import java.util.Collection;
278import java.util.Collections;
279import java.util.Comparator;
280import java.util.Date;
281import java.util.HashSet;
282import java.util.Iterator;
283import java.util.List;
284import java.util.Map;
285import java.util.Objects;
286import java.util.Set;
287import java.util.concurrent.CountDownLatch;
288import java.util.concurrent.TimeUnit;
289import java.util.concurrent.atomic.AtomicBoolean;
290import java.util.concurrent.atomic.AtomicInteger;
291import java.util.concurrent.atomic.AtomicLong;
292
293/**
294 * Keep track of all those .apks everywhere.
295 *
296 * This is very central to the platform's security; please run the unit
297 * tests whenever making modifications here:
298 *
299runtest -c android.content.pm.PackageManagerTests frameworks-core
300 *
301 * {@hide}
302 */
303public class PackageManagerService extends IPackageManager.Stub {
304    static final String TAG = "PackageManager";
305    static final boolean DEBUG_SETTINGS = false;
306    static final boolean DEBUG_PREFERRED = false;
307    static final boolean DEBUG_UPGRADE = false;
308    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
309    private static final boolean DEBUG_BACKUP = false;
310    private static final boolean DEBUG_INSTALL = false;
311    private static final boolean DEBUG_REMOVE = false;
312    private static final boolean DEBUG_BROADCASTS = false;
313    private static final boolean DEBUG_SHOW_INFO = false;
314    private static final boolean DEBUG_PACKAGE_INFO = false;
315    private static final boolean DEBUG_INTENT_MATCHING = false;
316    private static final boolean DEBUG_PACKAGE_SCANNING = false;
317    private static final boolean DEBUG_VERIFY = false;
318
319    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
320    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
321    // user, but by default initialize to this.
322    static final boolean DEBUG_DEXOPT = false;
323
324    private static final boolean DEBUG_ABI_SELECTION = false;
325    private static final boolean DEBUG_EPHEMERAL = false;
326    private static final boolean DEBUG_TRIAGED_MISSING = false;
327    private static final boolean DEBUG_APP_DATA = false;
328
329    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
330
331    private static final boolean DISABLE_EPHEMERAL_APPS = true;
332
333    private static final int RADIO_UID = Process.PHONE_UID;
334    private static final int LOG_UID = Process.LOG_UID;
335    private static final int NFC_UID = Process.NFC_UID;
336    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
337    private static final int SHELL_UID = Process.SHELL_UID;
338
339    // Cap the size of permission trees that 3rd party apps can define
340    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
341
342    // Suffix used during package installation when copying/moving
343    // package apks to install directory.
344    private static final String INSTALL_PACKAGE_SUFFIX = "-";
345
346    static final int SCAN_NO_DEX = 1<<1;
347    static final int SCAN_FORCE_DEX = 1<<2;
348    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
349    static final int SCAN_NEW_INSTALL = 1<<4;
350    static final int SCAN_NO_PATHS = 1<<5;
351    static final int SCAN_UPDATE_TIME = 1<<6;
352    static final int SCAN_DEFER_DEX = 1<<7;
353    static final int SCAN_BOOTING = 1<<8;
354    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
355    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
356    static final int SCAN_REPLACING = 1<<11;
357    static final int SCAN_REQUIRE_KNOWN = 1<<12;
358    static final int SCAN_MOVE = 1<<13;
359    static final int SCAN_INITIAL = 1<<14;
360    static final int SCAN_CHECK_ONLY = 1<<15;
361
362    static final int REMOVE_CHATTY = 1<<16;
363
364    private static final int[] EMPTY_INT_ARRAY = new int[0];
365
366    /**
367     * Timeout (in milliseconds) after which the watchdog should declare that
368     * our handler thread is wedged.  The usual default for such things is one
369     * minute but we sometimes do very lengthy I/O operations on this thread,
370     * such as installing multi-gigabyte applications, so ours needs to be longer.
371     */
372    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
373
374    /**
375     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
376     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
377     * settings entry if available, otherwise we use the hardcoded default.  If it's been
378     * more than this long since the last fstrim, we force one during the boot sequence.
379     *
380     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
381     * one gets run at the next available charging+idle time.  This final mandatory
382     * no-fstrim check kicks in only of the other scheduling criteria is never met.
383     */
384    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
385
386    /**
387     * Whether verification is enabled by default.
388     */
389    private static final boolean DEFAULT_VERIFY_ENABLE = true;
390
391    /**
392     * The default maximum time to wait for the verification agent to return in
393     * milliseconds.
394     */
395    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
396
397    /**
398     * The default response for package verification timeout.
399     *
400     * This can be either PackageManager.VERIFICATION_ALLOW or
401     * PackageManager.VERIFICATION_REJECT.
402     */
403    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
404
405    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
406
407    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
408            DEFAULT_CONTAINER_PACKAGE,
409            "com.android.defcontainer.DefaultContainerService");
410
411    private static final String KILL_APP_REASON_GIDS_CHANGED =
412            "permission grant or revoke changed gids";
413
414    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
415            "permissions revoked";
416
417    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
418
419    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
420
421    /** Permission grant: not grant the permission. */
422    private static final int GRANT_DENIED = 1;
423
424    /** Permission grant: grant the permission as an install permission. */
425    private static final int GRANT_INSTALL = 2;
426
427    /** Permission grant: grant the permission as a runtime one. */
428    private static final int GRANT_RUNTIME = 3;
429
430    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
431    private static final int GRANT_UPGRADE = 4;
432
433    /** Canonical intent used to identify what counts as a "web browser" app */
434    private static final Intent sBrowserIntent;
435    static {
436        sBrowserIntent = new Intent();
437        sBrowserIntent.setAction(Intent.ACTION_VIEW);
438        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
439        sBrowserIntent.setData(Uri.parse("http:"));
440    }
441
442    final ServiceThread mHandlerThread;
443
444    final PackageHandler mHandler;
445
446    /**
447     * Messages for {@link #mHandler} that need to wait for system ready before
448     * being dispatched.
449     */
450    private ArrayList<Message> mPostSystemReadyMessages;
451
452    final int mSdkVersion = Build.VERSION.SDK_INT;
453
454    final Context mContext;
455    final boolean mFactoryTest;
456    final boolean mOnlyCore;
457    final DisplayMetrics mMetrics;
458    final int mDefParseFlags;
459    final String[] mSeparateProcesses;
460    final boolean mIsUpgrade;
461
462    /** The location for ASEC container files on internal storage. */
463    final String mAsecInternalPath;
464
465    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
466    // LOCK HELD.  Can be called with mInstallLock held.
467    @GuardedBy("mInstallLock")
468    final Installer mInstaller;
469
470    /** Directory where installed third-party apps stored */
471    final File mAppInstallDir;
472    final File mEphemeralInstallDir;
473
474    /**
475     * Directory to which applications installed internally have their
476     * 32 bit native libraries copied.
477     */
478    private File mAppLib32InstallDir;
479
480    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
481    // apps.
482    final File mDrmAppPrivateInstallDir;
483
484    // ----------------------------------------------------------------
485
486    // Lock for state used when installing and doing other long running
487    // operations.  Methods that must be called with this lock held have
488    // the suffix "LI".
489    final Object mInstallLock = new Object();
490
491    // ----------------------------------------------------------------
492
493    // Keys are String (package name), values are Package.  This also serves
494    // as the lock for the global state.  Methods that must be called with
495    // this lock held have the prefix "LP".
496    @GuardedBy("mPackages")
497    final ArrayMap<String, PackageParser.Package> mPackages =
498            new ArrayMap<String, PackageParser.Package>();
499
500    // Tracks available target package names -> overlay package paths.
501    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
502        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
503
504    /**
505     * Tracks new system packages [received in an OTA] that we expect to
506     * find updated user-installed versions. Keys are package name, values
507     * are package location.
508     */
509    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
510
511    /**
512     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
513     */
514    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
515    /**
516     * Whether or not system app permissions should be promoted from install to runtime.
517     */
518    boolean mPromoteSystemApps;
519
520    final Settings mSettings;
521    boolean mRestoredSettings;
522
523    // System configuration read by SystemConfig.
524    final int[] mGlobalGids;
525    final SparseArray<ArraySet<String>> mSystemPermissions;
526    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
527
528    // If mac_permissions.xml was found for seinfo labeling.
529    boolean mFoundPolicyFile;
530
531    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
532
533    public static final class SharedLibraryEntry {
534        public final String path;
535        public final String apk;
536
537        SharedLibraryEntry(String _path, String _apk) {
538            path = _path;
539            apk = _apk;
540        }
541    }
542
543    // Currently known shared libraries.
544    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
545            new ArrayMap<String, SharedLibraryEntry>();
546
547    // All available activities, for your resolving pleasure.
548    final ActivityIntentResolver mActivities =
549            new ActivityIntentResolver();
550
551    // All available receivers, for your resolving pleasure.
552    final ActivityIntentResolver mReceivers =
553            new ActivityIntentResolver();
554
555    // All available services, for your resolving pleasure.
556    final ServiceIntentResolver mServices = new ServiceIntentResolver();
557
558    // All available providers, for your resolving pleasure.
559    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
560
561    // Mapping from provider base names (first directory in content URI codePath)
562    // to the provider information.
563    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
564            new ArrayMap<String, PackageParser.Provider>();
565
566    // Mapping from instrumentation class names to info about them.
567    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
568            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
569
570    // Mapping from permission names to info about them.
571    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
572            new ArrayMap<String, PackageParser.PermissionGroup>();
573
574    // Packages whose data we have transfered into another package, thus
575    // should no longer exist.
576    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
577
578    // Broadcast actions that are only available to the system.
579    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
580
581    /** List of packages waiting for verification. */
582    final SparseArray<PackageVerificationState> mPendingVerification
583            = new SparseArray<PackageVerificationState>();
584
585    /** Set of packages associated with each app op permission. */
586    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
587
588    final PackageInstallerService mInstallerService;
589
590    private final PackageDexOptimizer mPackageDexOptimizer;
591
592    private AtomicInteger mNextMoveId = new AtomicInteger();
593    private final MoveCallbacks mMoveCallbacks;
594
595    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
596
597    // Cache of users who need badging.
598    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
599
600    /** Token for keys in mPendingVerification. */
601    private int mPendingVerificationToken = 0;
602
603    volatile boolean mSystemReady;
604    volatile boolean mSafeMode;
605    volatile boolean mHasSystemUidErrors;
606
607    ApplicationInfo mAndroidApplication;
608    final ActivityInfo mResolveActivity = new ActivityInfo();
609    final ResolveInfo mResolveInfo = new ResolveInfo();
610    ComponentName mResolveComponentName;
611    PackageParser.Package mPlatformPackage;
612    ComponentName mCustomResolverComponentName;
613
614    boolean mResolverReplaced = false;
615
616    private final @Nullable ComponentName mIntentFilterVerifierComponent;
617    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
618
619    private int mIntentFilterVerificationToken = 0;
620
621    /** Component that knows whether or not an ephemeral application exists */
622    final ComponentName mEphemeralResolverComponent;
623    /** The service connection to the ephemeral resolver */
624    final EphemeralResolverConnection mEphemeralResolverConnection;
625
626    /** Component used to install ephemeral applications */
627    final ComponentName mEphemeralInstallerComponent;
628    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
629    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
630
631    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
632            = new SparseArray<IntentFilterVerificationState>();
633
634    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
635            new DefaultPermissionGrantPolicy(this);
636
637    // List of packages names to keep cached, even if they are uninstalled for all users
638    private List<String> mKeepUninstalledPackages;
639
640    private boolean mUseJitProfiles =
641            SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false);
642
643    private static class IFVerificationParams {
644        PackageParser.Package pkg;
645        boolean replacing;
646        int userId;
647        int verifierUid;
648
649        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
650                int _userId, int _verifierUid) {
651            pkg = _pkg;
652            replacing = _replacing;
653            userId = _userId;
654            replacing = _replacing;
655            verifierUid = _verifierUid;
656        }
657    }
658
659    private interface IntentFilterVerifier<T extends IntentFilter> {
660        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
661                                               T filter, String packageName);
662        void startVerifications(int userId);
663        void receiveVerificationResponse(int verificationId);
664    }
665
666    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
667        private Context mContext;
668        private ComponentName mIntentFilterVerifierComponent;
669        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
670
671        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
672            mContext = context;
673            mIntentFilterVerifierComponent = verifierComponent;
674        }
675
676        private String getDefaultScheme() {
677            return IntentFilter.SCHEME_HTTPS;
678        }
679
680        @Override
681        public void startVerifications(int userId) {
682            // Launch verifications requests
683            int count = mCurrentIntentFilterVerifications.size();
684            for (int n=0; n<count; n++) {
685                int verificationId = mCurrentIntentFilterVerifications.get(n);
686                final IntentFilterVerificationState ivs =
687                        mIntentFilterVerificationStates.get(verificationId);
688
689                String packageName = ivs.getPackageName();
690
691                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
692                final int filterCount = filters.size();
693                ArraySet<String> domainsSet = new ArraySet<>();
694                for (int m=0; m<filterCount; m++) {
695                    PackageParser.ActivityIntentInfo filter = filters.get(m);
696                    domainsSet.addAll(filter.getHostsList());
697                }
698                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
699                synchronized (mPackages) {
700                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
701                            packageName, domainsList) != null) {
702                        scheduleWriteSettingsLocked();
703                    }
704                }
705                sendVerificationRequest(userId, verificationId, ivs);
706            }
707            mCurrentIntentFilterVerifications.clear();
708        }
709
710        private void sendVerificationRequest(int userId, int verificationId,
711                IntentFilterVerificationState ivs) {
712
713            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
714            verificationIntent.putExtra(
715                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
716                    verificationId);
717            verificationIntent.putExtra(
718                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
719                    getDefaultScheme());
720            verificationIntent.putExtra(
721                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
722                    ivs.getHostsString());
723            verificationIntent.putExtra(
724                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
725                    ivs.getPackageName());
726            verificationIntent.setComponent(mIntentFilterVerifierComponent);
727            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
728
729            UserHandle user = new UserHandle(userId);
730            mContext.sendBroadcastAsUser(verificationIntent, user);
731            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
732                    "Sending IntentFilter verification broadcast");
733        }
734
735        public void receiveVerificationResponse(int verificationId) {
736            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
737
738            final boolean verified = ivs.isVerified();
739
740            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
741            final int count = filters.size();
742            if (DEBUG_DOMAIN_VERIFICATION) {
743                Slog.i(TAG, "Received verification response " + verificationId
744                        + " for " + count + " filters, verified=" + verified);
745            }
746            for (int n=0; n<count; n++) {
747                PackageParser.ActivityIntentInfo filter = filters.get(n);
748                filter.setVerified(verified);
749
750                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
751                        + " verified with result:" + verified + " and hosts:"
752                        + ivs.getHostsString());
753            }
754
755            mIntentFilterVerificationStates.remove(verificationId);
756
757            final String packageName = ivs.getPackageName();
758            IntentFilterVerificationInfo ivi = null;
759
760            synchronized (mPackages) {
761                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
762            }
763            if (ivi == null) {
764                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
765                        + verificationId + " packageName:" + packageName);
766                return;
767            }
768            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
769                    "Updating IntentFilterVerificationInfo for package " + packageName
770                            +" verificationId:" + verificationId);
771
772            synchronized (mPackages) {
773                if (verified) {
774                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
775                } else {
776                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
777                }
778                scheduleWriteSettingsLocked();
779
780                final int userId = ivs.getUserId();
781                if (userId != UserHandle.USER_ALL) {
782                    final int userStatus =
783                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
784
785                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
786                    boolean needUpdate = false;
787
788                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
789                    // already been set by the User thru the Disambiguation dialog
790                    switch (userStatus) {
791                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
792                            if (verified) {
793                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
794                            } else {
795                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
796                            }
797                            needUpdate = true;
798                            break;
799
800                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
801                            if (verified) {
802                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
803                                needUpdate = true;
804                            }
805                            break;
806
807                        default:
808                            // Nothing to do
809                    }
810
811                    if (needUpdate) {
812                        mSettings.updateIntentFilterVerificationStatusLPw(
813                                packageName, updatedStatus, userId);
814                        scheduleWritePackageRestrictionsLocked(userId);
815                    }
816                }
817            }
818        }
819
820        @Override
821        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
822                    ActivityIntentInfo filter, String packageName) {
823            if (!hasValidDomains(filter)) {
824                return false;
825            }
826            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
827            if (ivs == null) {
828                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
829                        packageName);
830            }
831            if (DEBUG_DOMAIN_VERIFICATION) {
832                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
833            }
834            ivs.addFilter(filter);
835            return true;
836        }
837
838        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
839                int userId, int verificationId, String packageName) {
840            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
841                    verifierUid, userId, packageName);
842            ivs.setPendingState();
843            synchronized (mPackages) {
844                mIntentFilterVerificationStates.append(verificationId, ivs);
845                mCurrentIntentFilterVerifications.add(verificationId);
846            }
847            return ivs;
848        }
849    }
850
851    private static boolean hasValidDomains(ActivityIntentInfo filter) {
852        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
853                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
854                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
855    }
856
857    // Set of pending broadcasts for aggregating enable/disable of components.
858    static class PendingPackageBroadcasts {
859        // for each user id, a map of <package name -> components within that package>
860        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
861
862        public PendingPackageBroadcasts() {
863            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
864        }
865
866        public ArrayList<String> get(int userId, String packageName) {
867            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
868            return packages.get(packageName);
869        }
870
871        public void put(int userId, String packageName, ArrayList<String> components) {
872            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
873            packages.put(packageName, components);
874        }
875
876        public void remove(int userId, String packageName) {
877            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
878            if (packages != null) {
879                packages.remove(packageName);
880            }
881        }
882
883        public void remove(int userId) {
884            mUidMap.remove(userId);
885        }
886
887        public int userIdCount() {
888            return mUidMap.size();
889        }
890
891        public int userIdAt(int n) {
892            return mUidMap.keyAt(n);
893        }
894
895        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
896            return mUidMap.get(userId);
897        }
898
899        public int size() {
900            // total number of pending broadcast entries across all userIds
901            int num = 0;
902            for (int i = 0; i< mUidMap.size(); i++) {
903                num += mUidMap.valueAt(i).size();
904            }
905            return num;
906        }
907
908        public void clear() {
909            mUidMap.clear();
910        }
911
912        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
913            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
914            if (map == null) {
915                map = new ArrayMap<String, ArrayList<String>>();
916                mUidMap.put(userId, map);
917            }
918            return map;
919        }
920    }
921    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
922
923    // Service Connection to remote media container service to copy
924    // package uri's from external media onto secure containers
925    // or internal storage.
926    private IMediaContainerService mContainerService = null;
927
928    static final int SEND_PENDING_BROADCAST = 1;
929    static final int MCS_BOUND = 3;
930    static final int END_COPY = 4;
931    static final int INIT_COPY = 5;
932    static final int MCS_UNBIND = 6;
933    static final int START_CLEANING_PACKAGE = 7;
934    static final int FIND_INSTALL_LOC = 8;
935    static final int POST_INSTALL = 9;
936    static final int MCS_RECONNECT = 10;
937    static final int MCS_GIVE_UP = 11;
938    static final int UPDATED_MEDIA_STATUS = 12;
939    static final int WRITE_SETTINGS = 13;
940    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
941    static final int PACKAGE_VERIFIED = 15;
942    static final int CHECK_PENDING_VERIFICATION = 16;
943    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
944    static final int INTENT_FILTER_VERIFIED = 18;
945
946    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
947
948    // Delay time in millisecs
949    static final int BROADCAST_DELAY = 10 * 1000;
950
951    static UserManagerService sUserManager;
952
953    // Stores a list of users whose package restrictions file needs to be updated
954    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
955
956    final private DefaultContainerConnection mDefContainerConn =
957            new DefaultContainerConnection();
958    class DefaultContainerConnection implements ServiceConnection {
959        public void onServiceConnected(ComponentName name, IBinder service) {
960            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
961            IMediaContainerService imcs =
962                IMediaContainerService.Stub.asInterface(service);
963            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
964        }
965
966        public void onServiceDisconnected(ComponentName name) {
967            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
968        }
969    }
970
971    // Recordkeeping of restore-after-install operations that are currently in flight
972    // between the Package Manager and the Backup Manager
973    static class PostInstallData {
974        public InstallArgs args;
975        public PackageInstalledInfo res;
976
977        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
978            args = _a;
979            res = _r;
980        }
981    }
982
983    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
984    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
985
986    // XML tags for backup/restore of various bits of state
987    private static final String TAG_PREFERRED_BACKUP = "pa";
988    private static final String TAG_DEFAULT_APPS = "da";
989    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
990
991    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
992    private static final String TAG_ALL_GRANTS = "rt-grants";
993    private static final String TAG_GRANT = "grant";
994    private static final String ATTR_PACKAGE_NAME = "pkg";
995
996    private static final String TAG_PERMISSION = "perm";
997    private static final String ATTR_PERMISSION_NAME = "name";
998    private static final String ATTR_IS_GRANTED = "g";
999    private static final String ATTR_USER_SET = "set";
1000    private static final String ATTR_USER_FIXED = "fixed";
1001    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1002
1003    // System/policy permission grants are not backed up
1004    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1005            FLAG_PERMISSION_POLICY_FIXED
1006            | FLAG_PERMISSION_SYSTEM_FIXED
1007            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1008
1009    // And we back up these user-adjusted states
1010    private static final int USER_RUNTIME_GRANT_MASK =
1011            FLAG_PERMISSION_USER_SET
1012            | FLAG_PERMISSION_USER_FIXED
1013            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1014
1015    final @Nullable String mRequiredVerifierPackage;
1016    final @Nullable String mRequiredInstallerPackage;
1017
1018    private final PackageUsage mPackageUsage = new PackageUsage();
1019
1020    private class PackageUsage {
1021        private static final int WRITE_INTERVAL
1022            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1023
1024        private final Object mFileLock = new Object();
1025        private final AtomicLong mLastWritten = new AtomicLong(0);
1026        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1027
1028        private boolean mIsHistoricalPackageUsageAvailable = true;
1029
1030        boolean isHistoricalPackageUsageAvailable() {
1031            return mIsHistoricalPackageUsageAvailable;
1032        }
1033
1034        void write(boolean force) {
1035            if (force) {
1036                writeInternal();
1037                return;
1038            }
1039            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1040                && !DEBUG_DEXOPT) {
1041                return;
1042            }
1043            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1044                new Thread("PackageUsage_DiskWriter") {
1045                    @Override
1046                    public void run() {
1047                        try {
1048                            writeInternal();
1049                        } finally {
1050                            mBackgroundWriteRunning.set(false);
1051                        }
1052                    }
1053                }.start();
1054            }
1055        }
1056
1057        private void writeInternal() {
1058            synchronized (mPackages) {
1059                synchronized (mFileLock) {
1060                    AtomicFile file = getFile();
1061                    FileOutputStream f = null;
1062                    try {
1063                        f = file.startWrite();
1064                        BufferedOutputStream out = new BufferedOutputStream(f);
1065                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1066                        StringBuilder sb = new StringBuilder();
1067                        for (PackageParser.Package pkg : mPackages.values()) {
1068                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1069                                continue;
1070                            }
1071                            sb.setLength(0);
1072                            sb.append(pkg.packageName);
1073                            sb.append(' ');
1074                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1075                            sb.append('\n');
1076                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1077                        }
1078                        out.flush();
1079                        file.finishWrite(f);
1080                    } catch (IOException e) {
1081                        if (f != null) {
1082                            file.failWrite(f);
1083                        }
1084                        Log.e(TAG, "Failed to write package usage times", e);
1085                    }
1086                }
1087            }
1088            mLastWritten.set(SystemClock.elapsedRealtime());
1089        }
1090
1091        void readLP() {
1092            synchronized (mFileLock) {
1093                AtomicFile file = getFile();
1094                BufferedInputStream in = null;
1095                try {
1096                    in = new BufferedInputStream(file.openRead());
1097                    StringBuffer sb = new StringBuffer();
1098                    while (true) {
1099                        String packageName = readToken(in, sb, ' ');
1100                        if (packageName == null) {
1101                            break;
1102                        }
1103                        String timeInMillisString = readToken(in, sb, '\n');
1104                        if (timeInMillisString == null) {
1105                            throw new IOException("Failed to find last usage time for package "
1106                                                  + packageName);
1107                        }
1108                        PackageParser.Package pkg = mPackages.get(packageName);
1109                        if (pkg == null) {
1110                            continue;
1111                        }
1112                        long timeInMillis;
1113                        try {
1114                            timeInMillis = Long.parseLong(timeInMillisString);
1115                        } catch (NumberFormatException e) {
1116                            throw new IOException("Failed to parse " + timeInMillisString
1117                                                  + " as a long.", e);
1118                        }
1119                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1120                    }
1121                } catch (FileNotFoundException expected) {
1122                    mIsHistoricalPackageUsageAvailable = false;
1123                } catch (IOException e) {
1124                    Log.w(TAG, "Failed to read package usage times", e);
1125                } finally {
1126                    IoUtils.closeQuietly(in);
1127                }
1128            }
1129            mLastWritten.set(SystemClock.elapsedRealtime());
1130        }
1131
1132        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1133                throws IOException {
1134            sb.setLength(0);
1135            while (true) {
1136                int ch = in.read();
1137                if (ch == -1) {
1138                    if (sb.length() == 0) {
1139                        return null;
1140                    }
1141                    throw new IOException("Unexpected EOF");
1142                }
1143                if (ch == endOfToken) {
1144                    return sb.toString();
1145                }
1146                sb.append((char)ch);
1147            }
1148        }
1149
1150        private AtomicFile getFile() {
1151            File dataDir = Environment.getDataDirectory();
1152            File systemDir = new File(dataDir, "system");
1153            File fname = new File(systemDir, "package-usage.list");
1154            return new AtomicFile(fname);
1155        }
1156    }
1157
1158    class PackageHandler extends Handler {
1159        private boolean mBound = false;
1160        final ArrayList<HandlerParams> mPendingInstalls =
1161            new ArrayList<HandlerParams>();
1162
1163        private boolean connectToService() {
1164            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1165                    " DefaultContainerService");
1166            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1167            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1168            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1169                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1170                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1171                mBound = true;
1172                return true;
1173            }
1174            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1175            return false;
1176        }
1177
1178        private void disconnectService() {
1179            mContainerService = null;
1180            mBound = false;
1181            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1182            mContext.unbindService(mDefContainerConn);
1183            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1184        }
1185
1186        PackageHandler(Looper looper) {
1187            super(looper);
1188        }
1189
1190        public void handleMessage(Message msg) {
1191            try {
1192                doHandleMessage(msg);
1193            } finally {
1194                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1195            }
1196        }
1197
1198        void doHandleMessage(Message msg) {
1199            switch (msg.what) {
1200                case INIT_COPY: {
1201                    HandlerParams params = (HandlerParams) msg.obj;
1202                    int idx = mPendingInstalls.size();
1203                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1204                    // If a bind was already initiated we dont really
1205                    // need to do anything. The pending install
1206                    // will be processed later on.
1207                    if (!mBound) {
1208                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1209                                System.identityHashCode(mHandler));
1210                        // If this is the only one pending we might
1211                        // have to bind to the service again.
1212                        if (!connectToService()) {
1213                            Slog.e(TAG, "Failed to bind to media container service");
1214                            params.serviceError();
1215                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1216                                    System.identityHashCode(mHandler));
1217                            if (params.traceMethod != null) {
1218                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1219                                        params.traceCookie);
1220                            }
1221                            return;
1222                        } else {
1223                            // Once we bind to the service, the first
1224                            // pending request will be processed.
1225                            mPendingInstalls.add(idx, params);
1226                        }
1227                    } else {
1228                        mPendingInstalls.add(idx, params);
1229                        // Already bound to the service. Just make
1230                        // sure we trigger off processing the first request.
1231                        if (idx == 0) {
1232                            mHandler.sendEmptyMessage(MCS_BOUND);
1233                        }
1234                    }
1235                    break;
1236                }
1237                case MCS_BOUND: {
1238                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1239                    if (msg.obj != null) {
1240                        mContainerService = (IMediaContainerService) msg.obj;
1241                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1242                                System.identityHashCode(mHandler));
1243                    }
1244                    if (mContainerService == null) {
1245                        if (!mBound) {
1246                            // Something seriously wrong since we are not bound and we are not
1247                            // waiting for connection. Bail out.
1248                            Slog.e(TAG, "Cannot bind to media container service");
1249                            for (HandlerParams params : mPendingInstalls) {
1250                                // Indicate service bind error
1251                                params.serviceError();
1252                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1253                                        System.identityHashCode(params));
1254                                if (params.traceMethod != null) {
1255                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1256                                            params.traceMethod, params.traceCookie);
1257                                }
1258                                return;
1259                            }
1260                            mPendingInstalls.clear();
1261                        } else {
1262                            Slog.w(TAG, "Waiting to connect to media container service");
1263                        }
1264                    } else if (mPendingInstalls.size() > 0) {
1265                        HandlerParams params = mPendingInstalls.get(0);
1266                        if (params != null) {
1267                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1268                                    System.identityHashCode(params));
1269                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1270                            if (params.startCopy()) {
1271                                // We are done...  look for more work or to
1272                                // go idle.
1273                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1274                                        "Checking for more work or unbind...");
1275                                // Delete pending install
1276                                if (mPendingInstalls.size() > 0) {
1277                                    mPendingInstalls.remove(0);
1278                                }
1279                                if (mPendingInstalls.size() == 0) {
1280                                    if (mBound) {
1281                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1282                                                "Posting delayed MCS_UNBIND");
1283                                        removeMessages(MCS_UNBIND);
1284                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1285                                        // Unbind after a little delay, to avoid
1286                                        // continual thrashing.
1287                                        sendMessageDelayed(ubmsg, 10000);
1288                                    }
1289                                } else {
1290                                    // There are more pending requests in queue.
1291                                    // Just post MCS_BOUND message to trigger processing
1292                                    // of next pending install.
1293                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1294                                            "Posting MCS_BOUND for next work");
1295                                    mHandler.sendEmptyMessage(MCS_BOUND);
1296                                }
1297                            }
1298                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1299                        }
1300                    } else {
1301                        // Should never happen ideally.
1302                        Slog.w(TAG, "Empty queue");
1303                    }
1304                    break;
1305                }
1306                case MCS_RECONNECT: {
1307                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1308                    if (mPendingInstalls.size() > 0) {
1309                        if (mBound) {
1310                            disconnectService();
1311                        }
1312                        if (!connectToService()) {
1313                            Slog.e(TAG, "Failed to bind to media container service");
1314                            for (HandlerParams params : mPendingInstalls) {
1315                                // Indicate service bind error
1316                                params.serviceError();
1317                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1318                                        System.identityHashCode(params));
1319                            }
1320                            mPendingInstalls.clear();
1321                        }
1322                    }
1323                    break;
1324                }
1325                case MCS_UNBIND: {
1326                    // If there is no actual work left, then time to unbind.
1327                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1328
1329                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1330                        if (mBound) {
1331                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1332
1333                            disconnectService();
1334                        }
1335                    } else if (mPendingInstalls.size() > 0) {
1336                        // There are more pending requests in queue.
1337                        // Just post MCS_BOUND message to trigger processing
1338                        // of next pending install.
1339                        mHandler.sendEmptyMessage(MCS_BOUND);
1340                    }
1341
1342                    break;
1343                }
1344                case MCS_GIVE_UP: {
1345                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1346                    HandlerParams params = mPendingInstalls.remove(0);
1347                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1348                            System.identityHashCode(params));
1349                    break;
1350                }
1351                case SEND_PENDING_BROADCAST: {
1352                    String packages[];
1353                    ArrayList<String> components[];
1354                    int size = 0;
1355                    int uids[];
1356                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1357                    synchronized (mPackages) {
1358                        if (mPendingBroadcasts == null) {
1359                            return;
1360                        }
1361                        size = mPendingBroadcasts.size();
1362                        if (size <= 0) {
1363                            // Nothing to be done. Just return
1364                            return;
1365                        }
1366                        packages = new String[size];
1367                        components = new ArrayList[size];
1368                        uids = new int[size];
1369                        int i = 0;  // filling out the above arrays
1370
1371                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1372                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1373                            Iterator<Map.Entry<String, ArrayList<String>>> it
1374                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1375                                            .entrySet().iterator();
1376                            while (it.hasNext() && i < size) {
1377                                Map.Entry<String, ArrayList<String>> ent = it.next();
1378                                packages[i] = ent.getKey();
1379                                components[i] = ent.getValue();
1380                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1381                                uids[i] = (ps != null)
1382                                        ? UserHandle.getUid(packageUserId, ps.appId)
1383                                        : -1;
1384                                i++;
1385                            }
1386                        }
1387                        size = i;
1388                        mPendingBroadcasts.clear();
1389                    }
1390                    // Send broadcasts
1391                    for (int i = 0; i < size; i++) {
1392                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1393                    }
1394                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1395                    break;
1396                }
1397                case START_CLEANING_PACKAGE: {
1398                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1399                    final String packageName = (String)msg.obj;
1400                    final int userId = msg.arg1;
1401                    final boolean andCode = msg.arg2 != 0;
1402                    synchronized (mPackages) {
1403                        if (userId == UserHandle.USER_ALL) {
1404                            int[] users = sUserManager.getUserIds();
1405                            for (int user : users) {
1406                                mSettings.addPackageToCleanLPw(
1407                                        new PackageCleanItem(user, packageName, andCode));
1408                            }
1409                        } else {
1410                            mSettings.addPackageToCleanLPw(
1411                                    new PackageCleanItem(userId, packageName, andCode));
1412                        }
1413                    }
1414                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415                    startCleaningPackages();
1416                } break;
1417                case POST_INSTALL: {
1418                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1419
1420                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1421                    mRunningInstalls.delete(msg.arg1);
1422
1423                    if (data != null) {
1424                        InstallArgs args = data.args;
1425                        PackageInstalledInfo parentRes = data.res;
1426
1427                        final boolean grantPermissions = (args.installFlags
1428                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1429                        final String[] grantedPermissions = args.installGrantPermissions;
1430
1431                        // Handle the parent package
1432                        handlePackagePostInstall(parentRes, grantPermissions, grantedPermissions,
1433                                args.observer);
1434
1435                        // Handle the child packages
1436                        final int childCount = (parentRes.addedChildPackages != null)
1437                                ? parentRes.addedChildPackages.size() : 0;
1438                        for (int i = 0; i < childCount; i++) {
1439                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1440                            handlePackagePostInstall(childRes, grantPermissions, grantedPermissions,
1441                                    args.observer);
1442                        }
1443
1444                        // Log tracing if needed
1445                        if (args.traceMethod != null) {
1446                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1447                                    args.traceCookie);
1448                        }
1449                    } else {
1450                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1451                    }
1452
1453                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1454                } break;
1455                case UPDATED_MEDIA_STATUS: {
1456                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1457                    boolean reportStatus = msg.arg1 == 1;
1458                    boolean doGc = msg.arg2 == 1;
1459                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1460                    if (doGc) {
1461                        // Force a gc to clear up stale containers.
1462                        Runtime.getRuntime().gc();
1463                    }
1464                    if (msg.obj != null) {
1465                        @SuppressWarnings("unchecked")
1466                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1467                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1468                        // Unload containers
1469                        unloadAllContainers(args);
1470                    }
1471                    if (reportStatus) {
1472                        try {
1473                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1474                            PackageHelper.getMountService().finishMediaUpdate();
1475                        } catch (RemoteException e) {
1476                            Log.e(TAG, "MountService not running?");
1477                        }
1478                    }
1479                } break;
1480                case WRITE_SETTINGS: {
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1482                    synchronized (mPackages) {
1483                        removeMessages(WRITE_SETTINGS);
1484                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1485                        mSettings.writeLPr();
1486                        mDirtyUsers.clear();
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                } break;
1490                case WRITE_PACKAGE_RESTRICTIONS: {
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1492                    synchronized (mPackages) {
1493                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1494                        for (int userId : mDirtyUsers) {
1495                            mSettings.writePackageRestrictionsLPr(userId);
1496                        }
1497                        mDirtyUsers.clear();
1498                    }
1499                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1500                } break;
1501                case CHECK_PENDING_VERIFICATION: {
1502                    final int verificationId = msg.arg1;
1503                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1504
1505                    if ((state != null) && !state.timeoutExtended()) {
1506                        final InstallArgs args = state.getInstallArgs();
1507                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1508
1509                        Slog.i(TAG, "Verification timed out for " + originUri);
1510                        mPendingVerification.remove(verificationId);
1511
1512                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1513
1514                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1515                            Slog.i(TAG, "Continuing with installation of " + originUri);
1516                            state.setVerifierResponse(Binder.getCallingUid(),
1517                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1518                            broadcastPackageVerified(verificationId, originUri,
1519                                    PackageManager.VERIFICATION_ALLOW,
1520                                    state.getInstallArgs().getUser());
1521                            try {
1522                                ret = args.copyApk(mContainerService, true);
1523                            } catch (RemoteException e) {
1524                                Slog.e(TAG, "Could not contact the ContainerService");
1525                            }
1526                        } else {
1527                            broadcastPackageVerified(verificationId, originUri,
1528                                    PackageManager.VERIFICATION_REJECT,
1529                                    state.getInstallArgs().getUser());
1530                        }
1531
1532                        Trace.asyncTraceEnd(
1533                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1534
1535                        processPendingInstall(args, ret);
1536                        mHandler.sendEmptyMessage(MCS_UNBIND);
1537                    }
1538                    break;
1539                }
1540                case PACKAGE_VERIFIED: {
1541                    final int verificationId = msg.arg1;
1542
1543                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1544                    if (state == null) {
1545                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1546                        break;
1547                    }
1548
1549                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1550
1551                    state.setVerifierResponse(response.callerUid, response.code);
1552
1553                    if (state.isVerificationComplete()) {
1554                        mPendingVerification.remove(verificationId);
1555
1556                        final InstallArgs args = state.getInstallArgs();
1557                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1558
1559                        int ret;
1560                        if (state.isInstallAllowed()) {
1561                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1562                            broadcastPackageVerified(verificationId, originUri,
1563                                    response.code, state.getInstallArgs().getUser());
1564                            try {
1565                                ret = args.copyApk(mContainerService, true);
1566                            } catch (RemoteException e) {
1567                                Slog.e(TAG, "Could not contact the ContainerService");
1568                            }
1569                        } else {
1570                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1571                        }
1572
1573                        Trace.asyncTraceEnd(
1574                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1575
1576                        processPendingInstall(args, ret);
1577                        mHandler.sendEmptyMessage(MCS_UNBIND);
1578                    }
1579
1580                    break;
1581                }
1582                case START_INTENT_FILTER_VERIFICATIONS: {
1583                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1584                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1585                            params.replacing, params.pkg);
1586                    break;
1587                }
1588                case INTENT_FILTER_VERIFIED: {
1589                    final int verificationId = msg.arg1;
1590
1591                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1592                            verificationId);
1593                    if (state == null) {
1594                        Slog.w(TAG, "Invalid IntentFilter verification token "
1595                                + verificationId + " received");
1596                        break;
1597                    }
1598
1599                    final int userId = state.getUserId();
1600
1601                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1602                            "Processing IntentFilter verification with token:"
1603                            + verificationId + " and userId:" + userId);
1604
1605                    final IntentFilterVerificationResponse response =
1606                            (IntentFilterVerificationResponse) msg.obj;
1607
1608                    state.setVerifierResponse(response.callerUid, response.code);
1609
1610                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1611                            "IntentFilter verification with token:" + verificationId
1612                            + " and userId:" + userId
1613                            + " is settings verifier response with response code:"
1614                            + response.code);
1615
1616                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1617                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1618                                + response.getFailedDomainsString());
1619                    }
1620
1621                    if (state.isVerificationComplete()) {
1622                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1623                    } else {
1624                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1625                                "IntentFilter verification with token:" + verificationId
1626                                + " was not said to be complete");
1627                    }
1628
1629                    break;
1630                }
1631            }
1632        }
1633    }
1634
1635    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1636            String[] grantedPermissions, IPackageInstallObserver2 installObserver) {
1637        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1638            // Send the removed broadcasts
1639            if (res.removedInfo != null) {
1640                res.removedInfo.sendPackageRemovedBroadcasts();
1641            }
1642
1643            // Now that we successfully installed the package, grant runtime
1644            // permissions if requested before broadcasting the install.
1645            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1646                    >= Build.VERSION_CODES.M) {
1647                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1648            }
1649
1650            final boolean update = res.removedInfo != null
1651                    && res.removedInfo.removedPackage != null;
1652
1653            // If this is the first time we have child packages for a disabled privileged
1654            // app that had no children, we grant requested runtime permissions to the new
1655            // children if the parent on the system image had them already granted.
1656            if (res.pkg.parentPackage != null) {
1657                synchronized (mPackages) {
1658                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1659                }
1660            }
1661
1662            synchronized (mPackages) {
1663                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1664            }
1665
1666            final String packageName = res.pkg.applicationInfo.packageName;
1667            Bundle extras = new Bundle(1);
1668            extras.putInt(Intent.EXTRA_UID, res.uid);
1669
1670            // Determine the set of users who are adding this package for
1671            // the first time vs. those who are seeing an update.
1672            int[] firstUsers = EMPTY_INT_ARRAY;
1673            int[] updateUsers = EMPTY_INT_ARRAY;
1674            if (res.origUsers == null || res.origUsers.length == 0) {
1675                firstUsers = res.newUsers;
1676            } else {
1677                for (int newUser : res.newUsers) {
1678                    boolean isNew = true;
1679                    for (int origUser : res.origUsers) {
1680                        if (origUser == newUser) {
1681                            isNew = false;
1682                            break;
1683                        }
1684                    }
1685                    if (isNew) {
1686                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1687                    } else {
1688                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1689                    }
1690                }
1691            }
1692
1693            // Send installed broadcasts if the install/update is not ephemeral
1694            if (!isEphemeral(res.pkg)) {
1695                // Send added for users that see the package for the first time
1696                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1697                        extras, 0 /*flags*/, null /*targetPackage*/,
1698                        null /*finishedReceiver*/, firstUsers);
1699
1700                // Send added for users that don't see the package for the first time
1701                if (update) {
1702                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1703                }
1704                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1705                        extras, 0 /*flags*/, null /*targetPackage*/,
1706                        null /*finishedReceiver*/, updateUsers);
1707
1708                // Send replaced for users that don't see the package for the first time
1709                if (update) {
1710                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1711                            packageName, extras, 0 /*flags*/,
1712                            null /*targetPackage*/, null /*finishedReceiver*/,
1713                            updateUsers);
1714                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1715                            null /*package*/, null /*extras*/, 0 /*flags*/,
1716                            packageName /*targetPackage*/,
1717                            null /*finishedReceiver*/, updateUsers);
1718                }
1719
1720                // Send broadcast package appeared if forward locked/external for all users
1721                // treat asec-hosted packages like removable media on upgrade
1722                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1723                    if (DEBUG_INSTALL) {
1724                        Slog.i(TAG, "upgrading pkg " + res.pkg
1725                                + " is ASEC-hosted -> AVAILABLE");
1726                    }
1727                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1728                    ArrayList<String> pkgList = new ArrayList<>(1);
1729                    pkgList.add(packageName);
1730                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1731                }
1732            }
1733
1734            // Work that needs to happen on first install within each user
1735            if (firstUsers != null && firstUsers.length > 0) {
1736                synchronized (mPackages) {
1737                    for (int userId : firstUsers) {
1738                        // If this app is a browser and it's newly-installed for some
1739                        // users, clear any default-browser state in those users. The
1740                        // app's nature doesn't depend on the user, so we can just check
1741                        // its browser nature in any user and generalize.
1742                        if (packageIsBrowser(packageName, userId)) {
1743                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1744                        }
1745
1746                        // We may also need to apply pending (restored) runtime
1747                        // permission grants within these users.
1748                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1749                    }
1750                }
1751            }
1752
1753            // Log current value of "unknown sources" setting
1754            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1755                    getUnknownSourcesSettings());
1756
1757            // Force a gc to clear up things
1758            Runtime.getRuntime().gc();
1759
1760            // Remove the replaced package's older resources safely now
1761            // We delete after a gc for applications  on sdcard.
1762            if (res.removedInfo != null && res.removedInfo.args != null) {
1763                synchronized (mInstallLock) {
1764                    res.removedInfo.args.doPostDeleteLI(true);
1765                }
1766            }
1767        }
1768
1769        // If someone is watching installs - notify them
1770        if (installObserver != null) {
1771            try {
1772                Bundle extras = extrasForInstallResult(res);
1773                installObserver.onPackageInstalled(res.name, res.returnCode,
1774                        res.returnMsg, extras);
1775            } catch (RemoteException e) {
1776                Slog.i(TAG, "Observer no longer exists.");
1777            }
1778        }
1779    }
1780
1781    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1782            PackageParser.Package pkg) {
1783        if (pkg.parentPackage == null) {
1784            return;
1785        }
1786        if (pkg.requestedPermissions == null) {
1787            return;
1788        }
1789        final PackageSetting disabledSysParentPs = mSettings
1790                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1791        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1792                || !disabledSysParentPs.isPrivileged()
1793                || (disabledSysParentPs.childPackageNames != null
1794                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1795            return;
1796        }
1797        final int[] allUserIds = sUserManager.getUserIds();
1798        final int permCount = pkg.requestedPermissions.size();
1799        for (int i = 0; i < permCount; i++) {
1800            String permission = pkg.requestedPermissions.get(i);
1801            BasePermission bp = mSettings.mPermissions.get(permission);
1802            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1803                continue;
1804            }
1805            for (int userId : allUserIds) {
1806                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1807                        permission, userId)) {
1808                    grantRuntimePermission(pkg.packageName, permission, userId);
1809                }
1810            }
1811        }
1812    }
1813
1814    private StorageEventListener mStorageListener = new StorageEventListener() {
1815        @Override
1816        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1817            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1818                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1819                    final String volumeUuid = vol.getFsUuid();
1820
1821                    // Clean up any users or apps that were removed or recreated
1822                    // while this volume was missing
1823                    reconcileUsers(volumeUuid);
1824                    reconcileApps(volumeUuid);
1825
1826                    // Clean up any install sessions that expired or were
1827                    // cancelled while this volume was missing
1828                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1829
1830                    loadPrivatePackages(vol);
1831
1832                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1833                    unloadPrivatePackages(vol);
1834                }
1835            }
1836
1837            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1838                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1839                    updateExternalMediaStatus(true, false);
1840                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1841                    updateExternalMediaStatus(false, false);
1842                }
1843            }
1844        }
1845
1846        @Override
1847        public void onVolumeForgotten(String fsUuid) {
1848            if (TextUtils.isEmpty(fsUuid)) {
1849                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1850                return;
1851            }
1852
1853            // Remove any apps installed on the forgotten volume
1854            synchronized (mPackages) {
1855                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1856                for (PackageSetting ps : packages) {
1857                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1858                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1859                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1860                }
1861
1862                mSettings.onVolumeForgotten(fsUuid);
1863                mSettings.writeLPr();
1864            }
1865        }
1866    };
1867
1868    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1869            String[] grantedPermissions) {
1870        for (int userId : userIds) {
1871            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1872        }
1873
1874        // We could have touched GID membership, so flush out packages.list
1875        synchronized (mPackages) {
1876            mSettings.writePackageListLPr();
1877        }
1878    }
1879
1880    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1881            String[] grantedPermissions) {
1882        SettingBase sb = (SettingBase) pkg.mExtras;
1883        if (sb == null) {
1884            return;
1885        }
1886
1887        PermissionsState permissionsState = sb.getPermissionsState();
1888
1889        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1890                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1891
1892        synchronized (mPackages) {
1893            for (String permission : pkg.requestedPermissions) {
1894                BasePermission bp = mSettings.mPermissions.get(permission);
1895                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1896                        && (grantedPermissions == null
1897                               || ArrayUtils.contains(grantedPermissions, permission))) {
1898                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1899                    // Installer cannot change immutable permissions.
1900                    if ((flags & immutableFlags) == 0) {
1901                        grantRuntimePermission(pkg.packageName, permission, userId);
1902                    }
1903                }
1904            }
1905        }
1906    }
1907
1908    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1909        Bundle extras = null;
1910        switch (res.returnCode) {
1911            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1912                extras = new Bundle();
1913                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1914                        res.origPermission);
1915                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1916                        res.origPackage);
1917                break;
1918            }
1919            case PackageManager.INSTALL_SUCCEEDED: {
1920                extras = new Bundle();
1921                extras.putBoolean(Intent.EXTRA_REPLACING,
1922                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1923                break;
1924            }
1925        }
1926        return extras;
1927    }
1928
1929    void scheduleWriteSettingsLocked() {
1930        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1931            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1932        }
1933    }
1934
1935    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1936        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1937        scheduleWritePackageRestrictionsLocked(userId);
1938    }
1939
1940    void scheduleWritePackageRestrictionsLocked(int userId) {
1941        final int[] userIds = (userId == UserHandle.USER_ALL)
1942                ? sUserManager.getUserIds() : new int[]{userId};
1943        for (int nextUserId : userIds) {
1944            if (!sUserManager.exists(nextUserId)) return;
1945            mDirtyUsers.add(nextUserId);
1946            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1947                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1948            }
1949        }
1950    }
1951
1952    public static PackageManagerService main(Context context, Installer installer,
1953            boolean factoryTest, boolean onlyCore) {
1954        PackageManagerService m = new PackageManagerService(context, installer,
1955                factoryTest, onlyCore);
1956        m.enableSystemUserPackages();
1957        ServiceManager.addService("package", m);
1958        return m;
1959    }
1960
1961    private void enableSystemUserPackages() {
1962        if (!UserManager.isSplitSystemUser()) {
1963            return;
1964        }
1965        // For system user, enable apps based on the following conditions:
1966        // - app is whitelisted or belong to one of these groups:
1967        //   -- system app which has no launcher icons
1968        //   -- system app which has INTERACT_ACROSS_USERS permission
1969        //   -- system IME app
1970        // - app is not in the blacklist
1971        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1972        Set<String> enableApps = new ArraySet<>();
1973        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1974                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1975                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1976        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1977        enableApps.addAll(wlApps);
1978        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1979                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1980        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1981        enableApps.removeAll(blApps);
1982        Log.i(TAG, "Applications installed for system user: " + enableApps);
1983        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1984                UserHandle.SYSTEM);
1985        final int allAppsSize = allAps.size();
1986        synchronized (mPackages) {
1987            for (int i = 0; i < allAppsSize; i++) {
1988                String pName = allAps.get(i);
1989                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1990                // Should not happen, but we shouldn't be failing if it does
1991                if (pkgSetting == null) {
1992                    continue;
1993                }
1994                boolean install = enableApps.contains(pName);
1995                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1996                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1997                            + " for system user");
1998                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1999                }
2000            }
2001        }
2002    }
2003
2004    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2005        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2006                Context.DISPLAY_SERVICE);
2007        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2008    }
2009
2010    public PackageManagerService(Context context, Installer installer,
2011            boolean factoryTest, boolean onlyCore) {
2012        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2013                SystemClock.uptimeMillis());
2014
2015        if (mSdkVersion <= 0) {
2016            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2017        }
2018
2019        mContext = context;
2020        mFactoryTest = factoryTest;
2021        mOnlyCore = onlyCore;
2022        mMetrics = new DisplayMetrics();
2023        mSettings = new Settings(mPackages);
2024        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2025                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2026        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2027                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2028        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2029                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2030        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2031                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2032        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2033                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2034        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2035                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2036
2037        String separateProcesses = SystemProperties.get("debug.separate_processes");
2038        if (separateProcesses != null && separateProcesses.length() > 0) {
2039            if ("*".equals(separateProcesses)) {
2040                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2041                mSeparateProcesses = null;
2042                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2043            } else {
2044                mDefParseFlags = 0;
2045                mSeparateProcesses = separateProcesses.split(",");
2046                Slog.w(TAG, "Running with debug.separate_processes: "
2047                        + separateProcesses);
2048            }
2049        } else {
2050            mDefParseFlags = 0;
2051            mSeparateProcesses = null;
2052        }
2053
2054        mInstaller = installer;
2055        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2056                "*dexopt*");
2057        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2058
2059        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2060                FgThread.get().getLooper());
2061
2062        getDefaultDisplayMetrics(context, mMetrics);
2063
2064        SystemConfig systemConfig = SystemConfig.getInstance();
2065        mGlobalGids = systemConfig.getGlobalGids();
2066        mSystemPermissions = systemConfig.getSystemPermissions();
2067        mAvailableFeatures = systemConfig.getAvailableFeatures();
2068
2069        synchronized (mInstallLock) {
2070        // writer
2071        synchronized (mPackages) {
2072            mHandlerThread = new ServiceThread(TAG,
2073                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2074            mHandlerThread.start();
2075            mHandler = new PackageHandler(mHandlerThread.getLooper());
2076            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2077
2078            File dataDir = Environment.getDataDirectory();
2079            mAppInstallDir = new File(dataDir, "app");
2080            mAppLib32InstallDir = new File(dataDir, "app-lib");
2081            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2082            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2083            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2084
2085            sUserManager = new UserManagerService(context, this, mPackages);
2086
2087            // Propagate permission configuration in to package manager.
2088            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2089                    = systemConfig.getPermissions();
2090            for (int i=0; i<permConfig.size(); i++) {
2091                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2092                BasePermission bp = mSettings.mPermissions.get(perm.name);
2093                if (bp == null) {
2094                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2095                    mSettings.mPermissions.put(perm.name, bp);
2096                }
2097                if (perm.gids != null) {
2098                    bp.setGids(perm.gids, perm.perUser);
2099                }
2100            }
2101
2102            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2103            for (int i=0; i<libConfig.size(); i++) {
2104                mSharedLibraries.put(libConfig.keyAt(i),
2105                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2106            }
2107
2108            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2109
2110            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2111
2112            String customResolverActivity = Resources.getSystem().getString(
2113                    R.string.config_customResolverActivity);
2114            if (TextUtils.isEmpty(customResolverActivity)) {
2115                customResolverActivity = null;
2116            } else {
2117                mCustomResolverComponentName = ComponentName.unflattenFromString(
2118                        customResolverActivity);
2119            }
2120
2121            long startTime = SystemClock.uptimeMillis();
2122
2123            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2124                    startTime);
2125
2126            // Set flag to monitor and not change apk file paths when
2127            // scanning install directories.
2128            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2129
2130            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2131            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2132
2133            if (bootClassPath == null) {
2134                Slog.w(TAG, "No BOOTCLASSPATH found!");
2135            }
2136
2137            if (systemServerClassPath == null) {
2138                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2139            }
2140
2141            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2142            final String[] dexCodeInstructionSets =
2143                    getDexCodeInstructionSets(
2144                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2145
2146            /**
2147             * Ensure all external libraries have had dexopt run on them.
2148             */
2149            if (mSharedLibraries.size() > 0) {
2150                // NOTE: For now, we're compiling these system "shared libraries"
2151                // (and framework jars) into all available architectures. It's possible
2152                // to compile them only when we come across an app that uses them (there's
2153                // already logic for that in scanPackageLI) but that adds some complexity.
2154                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2155                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2156                        final String lib = libEntry.path;
2157                        if (lib == null) {
2158                            continue;
2159                        }
2160
2161                        try {
2162                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2163                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2164                                // Shared libraries do not have profiles so we perform a full
2165                                // AOT compilation.
2166                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2167                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2168                                        StorageManager.UUID_PRIVATE_INTERNAL,
2169                                        false /*useProfiles*/);
2170                            }
2171                        } catch (FileNotFoundException e) {
2172                            Slog.w(TAG, "Library not found: " + lib);
2173                        } catch (IOException | InstallerException e) {
2174                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2175                                    + e.getMessage());
2176                        }
2177                    }
2178                }
2179            }
2180
2181            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2182
2183            final VersionInfo ver = mSettings.getInternalVersion();
2184            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2185            // when upgrading from pre-M, promote system app permissions from install to runtime
2186            mPromoteSystemApps =
2187                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2188
2189            // save off the names of pre-existing system packages prior to scanning; we don't
2190            // want to automatically grant runtime permissions for new system apps
2191            if (mPromoteSystemApps) {
2192                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2193                while (pkgSettingIter.hasNext()) {
2194                    PackageSetting ps = pkgSettingIter.next();
2195                    if (isSystemApp(ps)) {
2196                        mExistingSystemPackages.add(ps.name);
2197                    }
2198                }
2199            }
2200
2201            // Collect vendor overlay packages.
2202            // (Do this before scanning any apps.)
2203            // For security and version matching reason, only consider
2204            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2205            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2206            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2207                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2208
2209            // Find base frameworks (resource packages without code).
2210            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2211                    | PackageParser.PARSE_IS_SYSTEM_DIR
2212                    | PackageParser.PARSE_IS_PRIVILEGED,
2213                    scanFlags | SCAN_NO_DEX, 0);
2214
2215            // Collected privileged system packages.
2216            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2217            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2218                    | PackageParser.PARSE_IS_SYSTEM_DIR
2219                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2220
2221            // Collect ordinary system packages.
2222            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2223            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2224                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2225
2226            // Collect all vendor packages.
2227            File vendorAppDir = new File("/vendor/app");
2228            try {
2229                vendorAppDir = vendorAppDir.getCanonicalFile();
2230            } catch (IOException e) {
2231                // failed to look up canonical path, continue with original one
2232            }
2233            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2234                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2235
2236            // Collect all OEM packages.
2237            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2238            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2239                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2240
2241            // Prune any system packages that no longer exist.
2242            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2243            if (!mOnlyCore) {
2244                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2245                while (psit.hasNext()) {
2246                    PackageSetting ps = psit.next();
2247
2248                    /*
2249                     * If this is not a system app, it can't be a
2250                     * disable system app.
2251                     */
2252                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2253                        continue;
2254                    }
2255
2256                    /*
2257                     * If the package is scanned, it's not erased.
2258                     */
2259                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2260                    if (scannedPkg != null) {
2261                        /*
2262                         * If the system app is both scanned and in the
2263                         * disabled packages list, then it must have been
2264                         * added via OTA. Remove it from the currently
2265                         * scanned package so the previously user-installed
2266                         * application can be scanned.
2267                         */
2268                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2269                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2270                                    + ps.name + "; removing system app.  Last known codePath="
2271                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2272                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2273                                    + scannedPkg.mVersionCode);
2274                            removePackageLI(scannedPkg, true);
2275                            mExpectingBetter.put(ps.name, ps.codePath);
2276                        }
2277
2278                        continue;
2279                    }
2280
2281                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2282                        psit.remove();
2283                        logCriticalInfo(Log.WARN, "System package " + ps.name
2284                                + " no longer exists; wiping its data");
2285                        removeDataDirsLI(null, ps.name);
2286                    } else {
2287                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2288                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2289                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2290                        }
2291                    }
2292                }
2293            }
2294
2295            //look for any incomplete package installations
2296            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2297            //clean up list
2298            for(int i = 0; i < deletePkgsList.size(); i++) {
2299                //clean up here
2300                cleanupInstallFailedPackage(deletePkgsList.get(i));
2301            }
2302            //delete tmp files
2303            deleteTempPackageFiles();
2304
2305            // Remove any shared userIDs that have no associated packages
2306            mSettings.pruneSharedUsersLPw();
2307
2308            if (!mOnlyCore) {
2309                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2310                        SystemClock.uptimeMillis());
2311                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2312
2313                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2314                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2315
2316                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2317                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2318
2319                /**
2320                 * Remove disable package settings for any updated system
2321                 * apps that were removed via an OTA. If they're not a
2322                 * previously-updated app, remove them completely.
2323                 * Otherwise, just revoke their system-level permissions.
2324                 */
2325                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2326                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2327                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2328
2329                    String msg;
2330                    if (deletedPkg == null) {
2331                        msg = "Updated system package " + deletedAppName
2332                                + " no longer exists; wiping its data";
2333                        removeDataDirsLI(null, deletedAppName);
2334                    } else {
2335                        msg = "Updated system app + " + deletedAppName
2336                                + " no longer present; removing system privileges for "
2337                                + deletedAppName;
2338
2339                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2340
2341                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2342                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2343                    }
2344                    logCriticalInfo(Log.WARN, msg);
2345                }
2346
2347                /**
2348                 * Make sure all system apps that we expected to appear on
2349                 * the userdata partition actually showed up. If they never
2350                 * appeared, crawl back and revive the system version.
2351                 */
2352                for (int i = 0; i < mExpectingBetter.size(); i++) {
2353                    final String packageName = mExpectingBetter.keyAt(i);
2354                    if (!mPackages.containsKey(packageName)) {
2355                        final File scanFile = mExpectingBetter.valueAt(i);
2356
2357                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2358                                + " but never showed up; reverting to system");
2359
2360                        final int reparseFlags;
2361                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2362                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2363                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2364                                    | PackageParser.PARSE_IS_PRIVILEGED;
2365                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2366                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2367                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2368                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2369                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2370                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2371                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2372                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2373                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2374                        } else {
2375                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2376                            continue;
2377                        }
2378
2379                        mSettings.enableSystemPackageLPw(packageName);
2380
2381                        try {
2382                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2383                        } catch (PackageManagerException e) {
2384                            Slog.e(TAG, "Failed to parse original system package: "
2385                                    + e.getMessage());
2386                        }
2387                    }
2388                }
2389            }
2390            mExpectingBetter.clear();
2391
2392            // Now that we know all of the shared libraries, update all clients to have
2393            // the correct library paths.
2394            updateAllSharedLibrariesLPw();
2395
2396            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2397                // NOTE: We ignore potential failures here during a system scan (like
2398                // the rest of the commands above) because there's precious little we
2399                // can do about it. A settings error is reported, though.
2400                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2401                        false /* boot complete */);
2402            }
2403
2404            // Now that we know all the packages we are keeping,
2405            // read and update their last usage times.
2406            mPackageUsage.readLP();
2407
2408            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2409                    SystemClock.uptimeMillis());
2410            Slog.i(TAG, "Time to scan packages: "
2411                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2412                    + " seconds");
2413
2414            // If the platform SDK has changed since the last time we booted,
2415            // we need to re-grant app permission to catch any new ones that
2416            // appear.  This is really a hack, and means that apps can in some
2417            // cases get permissions that the user didn't initially explicitly
2418            // allow...  it would be nice to have some better way to handle
2419            // this situation.
2420            int updateFlags = UPDATE_PERMISSIONS_ALL;
2421            if (ver.sdkVersion != mSdkVersion) {
2422                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2423                        + mSdkVersion + "; regranting permissions for internal storage");
2424                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2425            }
2426            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2427            ver.sdkVersion = mSdkVersion;
2428
2429            // If this is the first boot or an update from pre-M, and it is a normal
2430            // boot, then we need to initialize the default preferred apps across
2431            // all defined users.
2432            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2433                for (UserInfo user : sUserManager.getUsers(true)) {
2434                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2435                    applyFactoryDefaultBrowserLPw(user.id);
2436                    primeDomainVerificationsLPw(user.id);
2437                }
2438            }
2439
2440            // Prepare storage for system user really early during boot,
2441            // since core system apps like SettingsProvider and SystemUI
2442            // can't wait for user to start
2443            final int storageFlags;
2444            if (StorageManager.isFileBasedEncryptionEnabled()) {
2445                storageFlags = StorageManager.FLAG_STORAGE_DE;
2446            } else {
2447                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2448            }
2449            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2450                    storageFlags);
2451
2452            if (!StorageManager.isFileBasedEncryptionEnabled()
2453                    && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
2454                // When upgrading a non-FBE device, we might need to shuffle
2455                // around the default storage location of system apps
2456                final List<UserInfo> users = sUserManager.getUsers(true);
2457                for (PackageSetting ps : mSettings.mPackages.values()) {
2458                    if (ps.pkg == null || !ps.isSystem()) continue;
2459                    final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted()
2460                            ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
2461                    for (UserInfo user : users) {
2462                        if (ps.getInstalled(user.id)) {
2463                            try {
2464                                mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2465                                        ps.name, user.id, storageTarget);
2466                            } catch (InstallerException e) {
2467                                logCriticalInfo(Log.WARN,
2468                                        "Failed to migrate " + ps.name + ": " + e.getMessage());
2469                            }
2470                            // We may have just shuffled around app data
2471                            // directories, so prepare it one more time
2472                            prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id,
2473                                    storageFlags, ps.pkg, false);
2474                        }
2475                    }
2476                }
2477            }
2478
2479            // If this is first boot after an OTA, and a normal boot, then
2480            // we need to clear code cache directories.
2481            if (mIsUpgrade && !onlyCore) {
2482                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2483                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2484                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2485                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2486                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2487                    }
2488                }
2489                ver.fingerprint = Build.FINGERPRINT;
2490            }
2491
2492            checkDefaultBrowser();
2493
2494            // clear only after permissions and other defaults have been updated
2495            mExistingSystemPackages.clear();
2496            mPromoteSystemApps = false;
2497
2498            // All the changes are done during package scanning.
2499            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2500
2501            // can downgrade to reader
2502            mSettings.writeLPr();
2503
2504            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2505                    SystemClock.uptimeMillis());
2506
2507            if (!mOnlyCore) {
2508                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2509                mRequiredInstallerPackage = getRequiredInstallerLPr();
2510                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2511                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2512                        mIntentFilterVerifierComponent);
2513            } else {
2514                mRequiredVerifierPackage = null;
2515                mRequiredInstallerPackage = null;
2516                mIntentFilterVerifierComponent = null;
2517                mIntentFilterVerifier = null;
2518            }
2519
2520            mInstallerService = new PackageInstallerService(context, this);
2521
2522            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2523            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2524            // both the installer and resolver must be present to enable ephemeral
2525            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2526                if (DEBUG_EPHEMERAL) {
2527                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2528                            + " installer:" + ephemeralInstallerComponent);
2529                }
2530                mEphemeralResolverComponent = ephemeralResolverComponent;
2531                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2532                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2533                mEphemeralResolverConnection =
2534                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2535            } else {
2536                if (DEBUG_EPHEMERAL) {
2537                    final String missingComponent =
2538                            (ephemeralResolverComponent == null)
2539                            ? (ephemeralInstallerComponent == null)
2540                                    ? "resolver and installer"
2541                                    : "resolver"
2542                            : "installer";
2543                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2544                }
2545                mEphemeralResolverComponent = null;
2546                mEphemeralInstallerComponent = null;
2547                mEphemeralResolverConnection = null;
2548            }
2549
2550            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2551        } // synchronized (mPackages)
2552        } // synchronized (mInstallLock)
2553
2554        // Now after opening every single application zip, make sure they
2555        // are all flushed.  Not really needed, but keeps things nice and
2556        // tidy.
2557        Runtime.getRuntime().gc();
2558
2559        // The initial scanning above does many calls into installd while
2560        // holding the mPackages lock, but we're mostly interested in yelling
2561        // once we have a booted system.
2562        mInstaller.setWarnIfHeld(mPackages);
2563
2564        // Expose private service for system components to use.
2565        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2566    }
2567
2568    @Override
2569    public boolean isFirstBoot() {
2570        return !mRestoredSettings;
2571    }
2572
2573    @Override
2574    public boolean isOnlyCoreApps() {
2575        return mOnlyCore;
2576    }
2577
2578    @Override
2579    public boolean isUpgrade() {
2580        return mIsUpgrade;
2581    }
2582
2583    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2584        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2585
2586        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2587                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2588        if (matches.size() == 1) {
2589            return matches.get(0).getComponentInfo().packageName;
2590        } else {
2591            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2592            return null;
2593        }
2594    }
2595
2596    private @NonNull String getRequiredInstallerLPr() {
2597        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2598        intent.addCategory(Intent.CATEGORY_DEFAULT);
2599        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2600
2601        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2602                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2603        if (matches.size() == 1) {
2604            return matches.get(0).getComponentInfo().packageName;
2605        } else {
2606            throw new RuntimeException("There must be exactly one installer; found " + matches);
2607        }
2608    }
2609
2610    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2611        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2612
2613        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2614                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2615        ResolveInfo best = null;
2616        final int N = matches.size();
2617        for (int i = 0; i < N; i++) {
2618            final ResolveInfo cur = matches.get(i);
2619            final String packageName = cur.getComponentInfo().packageName;
2620            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2621                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2622                continue;
2623            }
2624
2625            if (best == null || cur.priority > best.priority) {
2626                best = cur;
2627            }
2628        }
2629
2630        if (best != null) {
2631            return best.getComponentInfo().getComponentName();
2632        } else {
2633            throw new RuntimeException("There must be at least one intent filter verifier");
2634        }
2635    }
2636
2637    private @Nullable ComponentName getEphemeralResolverLPr() {
2638        final String[] packageArray =
2639                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2640        if (packageArray.length == 0) {
2641            if (DEBUG_EPHEMERAL) {
2642                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2643            }
2644            return null;
2645        }
2646
2647        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2648        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2649                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2650
2651        final int N = resolvers.size();
2652        if (N == 0) {
2653            if (DEBUG_EPHEMERAL) {
2654                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2655            }
2656            return null;
2657        }
2658
2659        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2660        for (int i = 0; i < N; i++) {
2661            final ResolveInfo info = resolvers.get(i);
2662
2663            if (info.serviceInfo == null) {
2664                continue;
2665            }
2666
2667            final String packageName = info.serviceInfo.packageName;
2668            if (!possiblePackages.contains(packageName)) {
2669                if (DEBUG_EPHEMERAL) {
2670                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2671                            + " pkg: " + packageName + ", info:" + info);
2672                }
2673                continue;
2674            }
2675
2676            if (DEBUG_EPHEMERAL) {
2677                Slog.v(TAG, "Ephemeral resolver found;"
2678                        + " pkg: " + packageName + ", info:" + info);
2679            }
2680            return new ComponentName(packageName, info.serviceInfo.name);
2681        }
2682        if (DEBUG_EPHEMERAL) {
2683            Slog.v(TAG, "Ephemeral resolver NOT found");
2684        }
2685        return null;
2686    }
2687
2688    private @Nullable ComponentName getEphemeralInstallerLPr() {
2689        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2690        intent.addCategory(Intent.CATEGORY_DEFAULT);
2691        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2692
2693        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2694                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2695        if (matches.size() == 0) {
2696            return null;
2697        } else if (matches.size() == 1) {
2698            return matches.get(0).getComponentInfo().getComponentName();
2699        } else {
2700            throw new RuntimeException(
2701                    "There must be at most one ephemeral installer; found " + matches);
2702        }
2703    }
2704
2705    private void primeDomainVerificationsLPw(int userId) {
2706        if (DEBUG_DOMAIN_VERIFICATION) {
2707            Slog.d(TAG, "Priming domain verifications in user " + userId);
2708        }
2709
2710        SystemConfig systemConfig = SystemConfig.getInstance();
2711        ArraySet<String> packages = systemConfig.getLinkedApps();
2712        ArraySet<String> domains = new ArraySet<String>();
2713
2714        for (String packageName : packages) {
2715            PackageParser.Package pkg = mPackages.get(packageName);
2716            if (pkg != null) {
2717                if (!pkg.isSystemApp()) {
2718                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2719                    continue;
2720                }
2721
2722                domains.clear();
2723                for (PackageParser.Activity a : pkg.activities) {
2724                    for (ActivityIntentInfo filter : a.intents) {
2725                        if (hasValidDomains(filter)) {
2726                            domains.addAll(filter.getHostsList());
2727                        }
2728                    }
2729                }
2730
2731                if (domains.size() > 0) {
2732                    if (DEBUG_DOMAIN_VERIFICATION) {
2733                        Slog.v(TAG, "      + " + packageName);
2734                    }
2735                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2736                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2737                    // and then 'always' in the per-user state actually used for intent resolution.
2738                    final IntentFilterVerificationInfo ivi;
2739                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2740                            new ArrayList<String>(domains));
2741                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2742                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2743                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2744                } else {
2745                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2746                            + "' does not handle web links");
2747                }
2748            } else {
2749                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2750            }
2751        }
2752
2753        scheduleWritePackageRestrictionsLocked(userId);
2754        scheduleWriteSettingsLocked();
2755    }
2756
2757    private void applyFactoryDefaultBrowserLPw(int userId) {
2758        // The default browser app's package name is stored in a string resource,
2759        // with a product-specific overlay used for vendor customization.
2760        String browserPkg = mContext.getResources().getString(
2761                com.android.internal.R.string.default_browser);
2762        if (!TextUtils.isEmpty(browserPkg)) {
2763            // non-empty string => required to be a known package
2764            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2765            if (ps == null) {
2766                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2767                browserPkg = null;
2768            } else {
2769                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2770            }
2771        }
2772
2773        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2774        // default.  If there's more than one, just leave everything alone.
2775        if (browserPkg == null) {
2776            calculateDefaultBrowserLPw(userId);
2777        }
2778    }
2779
2780    private void calculateDefaultBrowserLPw(int userId) {
2781        List<String> allBrowsers = resolveAllBrowserApps(userId);
2782        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2783        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2784    }
2785
2786    private List<String> resolveAllBrowserApps(int userId) {
2787        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2788        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2789                PackageManager.MATCH_ALL, userId);
2790
2791        final int count = list.size();
2792        List<String> result = new ArrayList<String>(count);
2793        for (int i=0; i<count; i++) {
2794            ResolveInfo info = list.get(i);
2795            if (info.activityInfo == null
2796                    || !info.handleAllWebDataURI
2797                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2798                    || result.contains(info.activityInfo.packageName)) {
2799                continue;
2800            }
2801            result.add(info.activityInfo.packageName);
2802        }
2803
2804        return result;
2805    }
2806
2807    private boolean packageIsBrowser(String packageName, int userId) {
2808        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2809                PackageManager.MATCH_ALL, userId);
2810        final int N = list.size();
2811        for (int i = 0; i < N; i++) {
2812            ResolveInfo info = list.get(i);
2813            if (packageName.equals(info.activityInfo.packageName)) {
2814                return true;
2815            }
2816        }
2817        return false;
2818    }
2819
2820    private void checkDefaultBrowser() {
2821        final int myUserId = UserHandle.myUserId();
2822        final String packageName = getDefaultBrowserPackageName(myUserId);
2823        if (packageName != null) {
2824            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2825            if (info == null) {
2826                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2827                synchronized (mPackages) {
2828                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2829                }
2830            }
2831        }
2832    }
2833
2834    @Override
2835    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2836            throws RemoteException {
2837        try {
2838            return super.onTransact(code, data, reply, flags);
2839        } catch (RuntimeException e) {
2840            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2841                Slog.wtf(TAG, "Package Manager Crash", e);
2842            }
2843            throw e;
2844        }
2845    }
2846
2847    void cleanupInstallFailedPackage(PackageSetting ps) {
2848        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2849
2850        removeDataDirsLI(ps.volumeUuid, ps.name);
2851        if (ps.codePath != null) {
2852            removeCodePathLI(ps.codePath);
2853        }
2854        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2855            if (ps.resourcePath.isDirectory()) {
2856                FileUtils.deleteContents(ps.resourcePath);
2857            }
2858            ps.resourcePath.delete();
2859        }
2860        mSettings.removePackageLPw(ps.name);
2861    }
2862
2863    static int[] appendInts(int[] cur, int[] add) {
2864        if (add == null) return cur;
2865        if (cur == null) return add;
2866        final int N = add.length;
2867        for (int i=0; i<N; i++) {
2868            cur = appendInt(cur, add[i]);
2869        }
2870        return cur;
2871    }
2872
2873    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2874        if (!sUserManager.exists(userId)) return null;
2875        final PackageSetting ps = (PackageSetting) p.mExtras;
2876        if (ps == null) {
2877            return null;
2878        }
2879
2880        final PermissionsState permissionsState = ps.getPermissionsState();
2881
2882        final int[] gids = permissionsState.computeGids(userId);
2883        final Set<String> permissions = permissionsState.getPermissions(userId);
2884        final PackageUserState state = ps.readUserState(userId);
2885
2886        return PackageParser.generatePackageInfo(p, gids, flags,
2887                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2888    }
2889
2890    @Override
2891    public void checkPackageStartable(String packageName, int userId) {
2892        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2893
2894        synchronized (mPackages) {
2895            final PackageSetting ps = mSettings.mPackages.get(packageName);
2896            if (ps == null) {
2897                throw new SecurityException("Package " + packageName + " was not found!");
2898            }
2899
2900            if (mSafeMode && !ps.isSystem()) {
2901                throw new SecurityException("Package " + packageName + " not a system app!");
2902            }
2903
2904            if (ps.frozen) {
2905                throw new SecurityException("Package " + packageName + " is currently frozen!");
2906            }
2907
2908            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2909                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2910                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2911            }
2912        }
2913    }
2914
2915    @Override
2916    public boolean isPackageAvailable(String packageName, int userId) {
2917        if (!sUserManager.exists(userId)) return false;
2918        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2919        synchronized (mPackages) {
2920            PackageParser.Package p = mPackages.get(packageName);
2921            if (p != null) {
2922                final PackageSetting ps = (PackageSetting) p.mExtras;
2923                if (ps != null) {
2924                    final PackageUserState state = ps.readUserState(userId);
2925                    if (state != null) {
2926                        return PackageParser.isAvailable(state);
2927                    }
2928                }
2929            }
2930        }
2931        return false;
2932    }
2933
2934    @Override
2935    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2936        if (!sUserManager.exists(userId)) return null;
2937        flags = updateFlagsForPackage(flags, userId, packageName);
2938        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2939        // reader
2940        synchronized (mPackages) {
2941            PackageParser.Package p = mPackages.get(packageName);
2942            if (DEBUG_PACKAGE_INFO)
2943                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2944            if (p != null) {
2945                return generatePackageInfo(p, flags, userId);
2946            }
2947            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2948                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2949            }
2950        }
2951        return null;
2952    }
2953
2954    @Override
2955    public String[] currentToCanonicalPackageNames(String[] names) {
2956        String[] out = new String[names.length];
2957        // reader
2958        synchronized (mPackages) {
2959            for (int i=names.length-1; i>=0; i--) {
2960                PackageSetting ps = mSettings.mPackages.get(names[i]);
2961                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2962            }
2963        }
2964        return out;
2965    }
2966
2967    @Override
2968    public String[] canonicalToCurrentPackageNames(String[] names) {
2969        String[] out = new String[names.length];
2970        // reader
2971        synchronized (mPackages) {
2972            for (int i=names.length-1; i>=0; i--) {
2973                String cur = mSettings.mRenamedPackages.get(names[i]);
2974                out[i] = cur != null ? cur : names[i];
2975            }
2976        }
2977        return out;
2978    }
2979
2980    @Override
2981    public int getPackageUid(String packageName, int flags, int userId) {
2982        if (!sUserManager.exists(userId)) return -1;
2983        flags = updateFlagsForPackage(flags, userId, packageName);
2984        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2985
2986        // reader
2987        synchronized (mPackages) {
2988            final PackageParser.Package p = mPackages.get(packageName);
2989            if (p != null && p.isMatch(flags)) {
2990                return UserHandle.getUid(userId, p.applicationInfo.uid);
2991            }
2992            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2993                final PackageSetting ps = mSettings.mPackages.get(packageName);
2994                if (ps != null && ps.isMatch(flags)) {
2995                    return UserHandle.getUid(userId, ps.appId);
2996                }
2997            }
2998        }
2999
3000        return -1;
3001    }
3002
3003    @Override
3004    public int[] getPackageGids(String packageName, int flags, int userId) {
3005        if (!sUserManager.exists(userId)) return null;
3006        flags = updateFlagsForPackage(flags, userId, packageName);
3007        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3008                "getPackageGids");
3009
3010        // reader
3011        synchronized (mPackages) {
3012            final PackageParser.Package p = mPackages.get(packageName);
3013            if (p != null && p.isMatch(flags)) {
3014                PackageSetting ps = (PackageSetting) p.mExtras;
3015                return ps.getPermissionsState().computeGids(userId);
3016            }
3017            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3018                final PackageSetting ps = mSettings.mPackages.get(packageName);
3019                if (ps != null && ps.isMatch(flags)) {
3020                    return ps.getPermissionsState().computeGids(userId);
3021                }
3022            }
3023        }
3024
3025        return null;
3026    }
3027
3028    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3029        if (bp.perm != null) {
3030            return PackageParser.generatePermissionInfo(bp.perm, flags);
3031        }
3032        PermissionInfo pi = new PermissionInfo();
3033        pi.name = bp.name;
3034        pi.packageName = bp.sourcePackage;
3035        pi.nonLocalizedLabel = bp.name;
3036        pi.protectionLevel = bp.protectionLevel;
3037        return pi;
3038    }
3039
3040    @Override
3041    public PermissionInfo getPermissionInfo(String name, int flags) {
3042        // reader
3043        synchronized (mPackages) {
3044            final BasePermission p = mSettings.mPermissions.get(name);
3045            if (p != null) {
3046                return generatePermissionInfo(p, flags);
3047            }
3048            return null;
3049        }
3050    }
3051
3052    @Override
3053    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
3054        // reader
3055        synchronized (mPackages) {
3056            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3057            for (BasePermission p : mSettings.mPermissions.values()) {
3058                if (group == null) {
3059                    if (p.perm == null || p.perm.info.group == null) {
3060                        out.add(generatePermissionInfo(p, flags));
3061                    }
3062                } else {
3063                    if (p.perm != null && group.equals(p.perm.info.group)) {
3064                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3065                    }
3066                }
3067            }
3068
3069            if (out.size() > 0) {
3070                return out;
3071            }
3072            return mPermissionGroups.containsKey(group) ? out : null;
3073        }
3074    }
3075
3076    @Override
3077    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3078        // reader
3079        synchronized (mPackages) {
3080            return PackageParser.generatePermissionGroupInfo(
3081                    mPermissionGroups.get(name), flags);
3082        }
3083    }
3084
3085    @Override
3086    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3087        // reader
3088        synchronized (mPackages) {
3089            final int N = mPermissionGroups.size();
3090            ArrayList<PermissionGroupInfo> out
3091                    = new ArrayList<PermissionGroupInfo>(N);
3092            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3093                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3094            }
3095            return out;
3096        }
3097    }
3098
3099    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3100            int userId) {
3101        if (!sUserManager.exists(userId)) return null;
3102        PackageSetting ps = mSettings.mPackages.get(packageName);
3103        if (ps != null) {
3104            if (ps.pkg == null) {
3105                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3106                        flags, userId);
3107                if (pInfo != null) {
3108                    return pInfo.applicationInfo;
3109                }
3110                return null;
3111            }
3112            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3113                    ps.readUserState(userId), userId);
3114        }
3115        return null;
3116    }
3117
3118    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3119            int userId) {
3120        if (!sUserManager.exists(userId)) return null;
3121        PackageSetting ps = mSettings.mPackages.get(packageName);
3122        if (ps != null) {
3123            PackageParser.Package pkg = ps.pkg;
3124            if (pkg == null) {
3125                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3126                    return null;
3127                }
3128                // Only data remains, so we aren't worried about code paths
3129                pkg = new PackageParser.Package(packageName);
3130                pkg.applicationInfo.packageName = packageName;
3131                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3132                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3133                pkg.applicationInfo.uid = ps.appId;
3134                pkg.applicationInfo.initForUser(userId);
3135                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3136                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3137            }
3138            return generatePackageInfo(pkg, flags, userId);
3139        }
3140        return null;
3141    }
3142
3143    @Override
3144    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3145        if (!sUserManager.exists(userId)) return null;
3146        flags = updateFlagsForApplication(flags, userId, packageName);
3147        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3148        // writer
3149        synchronized (mPackages) {
3150            PackageParser.Package p = mPackages.get(packageName);
3151            if (DEBUG_PACKAGE_INFO) Log.v(
3152                    TAG, "getApplicationInfo " + packageName
3153                    + ": " + p);
3154            if (p != null) {
3155                PackageSetting ps = mSettings.mPackages.get(packageName);
3156                if (ps == null) return null;
3157                // Note: isEnabledLP() does not apply here - always return info
3158                return PackageParser.generateApplicationInfo(
3159                        p, flags, ps.readUserState(userId), userId);
3160            }
3161            if ("android".equals(packageName)||"system".equals(packageName)) {
3162                return mAndroidApplication;
3163            }
3164            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3165                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3166            }
3167        }
3168        return null;
3169    }
3170
3171    @Override
3172    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3173            final IPackageDataObserver observer) {
3174        mContext.enforceCallingOrSelfPermission(
3175                android.Manifest.permission.CLEAR_APP_CACHE, null);
3176        // Queue up an async operation since clearing cache may take a little while.
3177        mHandler.post(new Runnable() {
3178            public void run() {
3179                mHandler.removeCallbacks(this);
3180                boolean success = true;
3181                synchronized (mInstallLock) {
3182                    try {
3183                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3184                    } catch (InstallerException e) {
3185                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3186                        success = false;
3187                    }
3188                }
3189                if (observer != null) {
3190                    try {
3191                        observer.onRemoveCompleted(null, success);
3192                    } catch (RemoteException e) {
3193                        Slog.w(TAG, "RemoveException when invoking call back");
3194                    }
3195                }
3196            }
3197        });
3198    }
3199
3200    @Override
3201    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3202            final IntentSender pi) {
3203        mContext.enforceCallingOrSelfPermission(
3204                android.Manifest.permission.CLEAR_APP_CACHE, null);
3205        // Queue up an async operation since clearing cache may take a little while.
3206        mHandler.post(new Runnable() {
3207            public void run() {
3208                mHandler.removeCallbacks(this);
3209                boolean success = true;
3210                synchronized (mInstallLock) {
3211                    try {
3212                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3213                    } catch (InstallerException e) {
3214                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3215                        success = false;
3216                    }
3217                }
3218                if(pi != null) {
3219                    try {
3220                        // Callback via pending intent
3221                        int code = success ? 1 : 0;
3222                        pi.sendIntent(null, code, null,
3223                                null, null);
3224                    } catch (SendIntentException e1) {
3225                        Slog.i(TAG, "Failed to send pending intent");
3226                    }
3227                }
3228            }
3229        });
3230    }
3231
3232    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3233        synchronized (mInstallLock) {
3234            try {
3235                mInstaller.freeCache(volumeUuid, freeStorageSize);
3236            } catch (InstallerException e) {
3237                throw new IOException("Failed to free enough space", e);
3238            }
3239        }
3240    }
3241
3242    /**
3243     * Return if the user key is currently unlocked.
3244     */
3245    private boolean isUserKeyUnlocked(int userId) {
3246        if (StorageManager.isFileBasedEncryptionEnabled()) {
3247            final IMountService mount = IMountService.Stub
3248                    .asInterface(ServiceManager.getService("mount"));
3249            if (mount == null) {
3250                Slog.w(TAG, "Early during boot, assuming locked");
3251                return false;
3252            }
3253            final long token = Binder.clearCallingIdentity();
3254            try {
3255                return mount.isUserKeyUnlocked(userId);
3256            } catch (RemoteException e) {
3257                throw e.rethrowAsRuntimeException();
3258            } finally {
3259                Binder.restoreCallingIdentity(token);
3260            }
3261        } else {
3262            return true;
3263        }
3264    }
3265
3266    /**
3267     * Update given flags based on encryption status of current user.
3268     */
3269    private int updateFlags(int flags, int userId) {
3270        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3271                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3272            // Caller expressed an explicit opinion about what encryption
3273            // aware/unaware components they want to see, so fall through and
3274            // give them what they want
3275        } else {
3276            // Caller expressed no opinion, so match based on user state
3277            if (isUserKeyUnlocked(userId)) {
3278                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3279            } else {
3280                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3281            }
3282        }
3283        return flags;
3284    }
3285
3286    /**
3287     * Update given flags when being used to request {@link PackageInfo}.
3288     */
3289    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3290        boolean triaged = true;
3291        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3292                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3293            // Caller is asking for component details, so they'd better be
3294            // asking for specific encryption matching behavior, or be triaged
3295            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3296                    | PackageManager.MATCH_ENCRYPTION_AWARE
3297                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3298                triaged = false;
3299            }
3300        }
3301        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3302                | PackageManager.MATCH_SYSTEM_ONLY
3303                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3304            triaged = false;
3305        }
3306        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3307            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3308                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3309        }
3310        return updateFlags(flags, userId);
3311    }
3312
3313    /**
3314     * Update given flags when being used to request {@link ApplicationInfo}.
3315     */
3316    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3317        return updateFlagsForPackage(flags, userId, cookie);
3318    }
3319
3320    /**
3321     * Update given flags when being used to request {@link ComponentInfo}.
3322     */
3323    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3324        if (cookie instanceof Intent) {
3325            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3326                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3327            }
3328        }
3329
3330        boolean triaged = true;
3331        // Caller is asking for component details, so they'd better be
3332        // asking for specific encryption matching behavior, or be triaged
3333        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3334                | PackageManager.MATCH_ENCRYPTION_AWARE
3335                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3336            triaged = false;
3337        }
3338        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3339            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3340                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3341        }
3342
3343        // Safe mode means we shouldn't match any third-party components
3344        if (mSafeMode) {
3345            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3346        }
3347
3348        return updateFlags(flags, userId);
3349    }
3350
3351    /**
3352     * Update given flags when being used to request {@link ResolveInfo}.
3353     */
3354    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3355        return updateFlagsForComponent(flags, userId, cookie);
3356    }
3357
3358    @Override
3359    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3360        if (!sUserManager.exists(userId)) return null;
3361        flags = updateFlagsForComponent(flags, userId, component);
3362        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3363        synchronized (mPackages) {
3364            PackageParser.Activity a = mActivities.mActivities.get(component);
3365
3366            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3367            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3368                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3369                if (ps == null) return null;
3370                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3371                        userId);
3372            }
3373            if (mResolveComponentName.equals(component)) {
3374                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3375                        new PackageUserState(), userId);
3376            }
3377        }
3378        return null;
3379    }
3380
3381    @Override
3382    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3383            String resolvedType) {
3384        synchronized (mPackages) {
3385            if (component.equals(mResolveComponentName)) {
3386                // The resolver supports EVERYTHING!
3387                return true;
3388            }
3389            PackageParser.Activity a = mActivities.mActivities.get(component);
3390            if (a == null) {
3391                return false;
3392            }
3393            for (int i=0; i<a.intents.size(); i++) {
3394                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3395                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3396                    return true;
3397                }
3398            }
3399            return false;
3400        }
3401    }
3402
3403    @Override
3404    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3405        if (!sUserManager.exists(userId)) return null;
3406        flags = updateFlagsForComponent(flags, userId, component);
3407        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3408        synchronized (mPackages) {
3409            PackageParser.Activity a = mReceivers.mActivities.get(component);
3410            if (DEBUG_PACKAGE_INFO) Log.v(
3411                TAG, "getReceiverInfo " + component + ": " + a);
3412            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3413                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3414                if (ps == null) return null;
3415                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3416                        userId);
3417            }
3418        }
3419        return null;
3420    }
3421
3422    @Override
3423    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3424        if (!sUserManager.exists(userId)) return null;
3425        flags = updateFlagsForComponent(flags, userId, component);
3426        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3427        synchronized (mPackages) {
3428            PackageParser.Service s = mServices.mServices.get(component);
3429            if (DEBUG_PACKAGE_INFO) Log.v(
3430                TAG, "getServiceInfo " + component + ": " + s);
3431            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3432                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3433                if (ps == null) return null;
3434                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3435                        userId);
3436            }
3437        }
3438        return null;
3439    }
3440
3441    @Override
3442    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3443        if (!sUserManager.exists(userId)) return null;
3444        flags = updateFlagsForComponent(flags, userId, component);
3445        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3446        synchronized (mPackages) {
3447            PackageParser.Provider p = mProviders.mProviders.get(component);
3448            if (DEBUG_PACKAGE_INFO) Log.v(
3449                TAG, "getProviderInfo " + component + ": " + p);
3450            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3451                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3452                if (ps == null) return null;
3453                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3454                        userId);
3455            }
3456        }
3457        return null;
3458    }
3459
3460    @Override
3461    public String[] getSystemSharedLibraryNames() {
3462        Set<String> libSet;
3463        synchronized (mPackages) {
3464            libSet = mSharedLibraries.keySet();
3465            int size = libSet.size();
3466            if (size > 0) {
3467                String[] libs = new String[size];
3468                libSet.toArray(libs);
3469                return libs;
3470            }
3471        }
3472        return null;
3473    }
3474
3475    @Override
3476    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3477        synchronized (mPackages) {
3478            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3479                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3480            if (libraryEntry != null) {
3481                return libraryEntry.apk;
3482            }
3483        }
3484        return null;
3485    }
3486
3487    @Override
3488    public FeatureInfo[] getSystemAvailableFeatures() {
3489        Collection<FeatureInfo> featSet;
3490        synchronized (mPackages) {
3491            featSet = mAvailableFeatures.values();
3492            int size = featSet.size();
3493            if (size > 0) {
3494                FeatureInfo[] features = new FeatureInfo[size+1];
3495                featSet.toArray(features);
3496                FeatureInfo fi = new FeatureInfo();
3497                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3498                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3499                features[size] = fi;
3500                return features;
3501            }
3502        }
3503        return null;
3504    }
3505
3506    @Override
3507    public boolean hasSystemFeature(String name, int version) {
3508        synchronized (mPackages) {
3509            final FeatureInfo feat = mAvailableFeatures.get(name);
3510            if (feat == null) {
3511                return false;
3512            } else {
3513                return feat.version >= version;
3514            }
3515        }
3516    }
3517
3518    @Override
3519    public int checkPermission(String permName, String pkgName, int userId) {
3520        if (!sUserManager.exists(userId)) {
3521            return PackageManager.PERMISSION_DENIED;
3522        }
3523
3524        synchronized (mPackages) {
3525            final PackageParser.Package p = mPackages.get(pkgName);
3526            if (p != null && p.mExtras != null) {
3527                final PackageSetting ps = (PackageSetting) p.mExtras;
3528                final PermissionsState permissionsState = ps.getPermissionsState();
3529                if (permissionsState.hasPermission(permName, userId)) {
3530                    return PackageManager.PERMISSION_GRANTED;
3531                }
3532                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3533                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3534                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3535                    return PackageManager.PERMISSION_GRANTED;
3536                }
3537            }
3538        }
3539
3540        return PackageManager.PERMISSION_DENIED;
3541    }
3542
3543    @Override
3544    public int checkUidPermission(String permName, int uid) {
3545        final int userId = UserHandle.getUserId(uid);
3546
3547        if (!sUserManager.exists(userId)) {
3548            return PackageManager.PERMISSION_DENIED;
3549        }
3550
3551        synchronized (mPackages) {
3552            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3553            if (obj != null) {
3554                final SettingBase ps = (SettingBase) obj;
3555                final PermissionsState permissionsState = ps.getPermissionsState();
3556                if (permissionsState.hasPermission(permName, userId)) {
3557                    return PackageManager.PERMISSION_GRANTED;
3558                }
3559                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3560                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3561                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3562                    return PackageManager.PERMISSION_GRANTED;
3563                }
3564            } else {
3565                ArraySet<String> perms = mSystemPermissions.get(uid);
3566                if (perms != null) {
3567                    if (perms.contains(permName)) {
3568                        return PackageManager.PERMISSION_GRANTED;
3569                    }
3570                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3571                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3572                        return PackageManager.PERMISSION_GRANTED;
3573                    }
3574                }
3575            }
3576        }
3577
3578        return PackageManager.PERMISSION_DENIED;
3579    }
3580
3581    @Override
3582    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3583        if (UserHandle.getCallingUserId() != userId) {
3584            mContext.enforceCallingPermission(
3585                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3586                    "isPermissionRevokedByPolicy for user " + userId);
3587        }
3588
3589        if (checkPermission(permission, packageName, userId)
3590                == PackageManager.PERMISSION_GRANTED) {
3591            return false;
3592        }
3593
3594        final long identity = Binder.clearCallingIdentity();
3595        try {
3596            final int flags = getPermissionFlags(permission, packageName, userId);
3597            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3598        } finally {
3599            Binder.restoreCallingIdentity(identity);
3600        }
3601    }
3602
3603    @Override
3604    public String getPermissionControllerPackageName() {
3605        synchronized (mPackages) {
3606            return mRequiredInstallerPackage;
3607        }
3608    }
3609
3610    /**
3611     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3612     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3613     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3614     * @param message the message to log on security exception
3615     */
3616    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3617            boolean checkShell, String message) {
3618        if (userId < 0) {
3619            throw new IllegalArgumentException("Invalid userId " + userId);
3620        }
3621        if (checkShell) {
3622            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3623        }
3624        if (userId == UserHandle.getUserId(callingUid)) return;
3625        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3626            if (requireFullPermission) {
3627                mContext.enforceCallingOrSelfPermission(
3628                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3629            } else {
3630                try {
3631                    mContext.enforceCallingOrSelfPermission(
3632                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3633                } catch (SecurityException se) {
3634                    mContext.enforceCallingOrSelfPermission(
3635                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3636                }
3637            }
3638        }
3639    }
3640
3641    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3642        if (callingUid == Process.SHELL_UID) {
3643            if (userHandle >= 0
3644                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3645                throw new SecurityException("Shell does not have permission to access user "
3646                        + userHandle);
3647            } else if (userHandle < 0) {
3648                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3649                        + Debug.getCallers(3));
3650            }
3651        }
3652    }
3653
3654    private BasePermission findPermissionTreeLP(String permName) {
3655        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3656            if (permName.startsWith(bp.name) &&
3657                    permName.length() > bp.name.length() &&
3658                    permName.charAt(bp.name.length()) == '.') {
3659                return bp;
3660            }
3661        }
3662        return null;
3663    }
3664
3665    private BasePermission checkPermissionTreeLP(String permName) {
3666        if (permName != null) {
3667            BasePermission bp = findPermissionTreeLP(permName);
3668            if (bp != null) {
3669                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3670                    return bp;
3671                }
3672                throw new SecurityException("Calling uid "
3673                        + Binder.getCallingUid()
3674                        + " is not allowed to add to permission tree "
3675                        + bp.name + " owned by uid " + bp.uid);
3676            }
3677        }
3678        throw new SecurityException("No permission tree found for " + permName);
3679    }
3680
3681    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3682        if (s1 == null) {
3683            return s2 == null;
3684        }
3685        if (s2 == null) {
3686            return false;
3687        }
3688        if (s1.getClass() != s2.getClass()) {
3689            return false;
3690        }
3691        return s1.equals(s2);
3692    }
3693
3694    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3695        if (pi1.icon != pi2.icon) return false;
3696        if (pi1.logo != pi2.logo) return false;
3697        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3698        if (!compareStrings(pi1.name, pi2.name)) return false;
3699        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3700        // We'll take care of setting this one.
3701        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3702        // These are not currently stored in settings.
3703        //if (!compareStrings(pi1.group, pi2.group)) return false;
3704        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3705        //if (pi1.labelRes != pi2.labelRes) return false;
3706        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3707        return true;
3708    }
3709
3710    int permissionInfoFootprint(PermissionInfo info) {
3711        int size = info.name.length();
3712        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3713        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3714        return size;
3715    }
3716
3717    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3718        int size = 0;
3719        for (BasePermission perm : mSettings.mPermissions.values()) {
3720            if (perm.uid == tree.uid) {
3721                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3722            }
3723        }
3724        return size;
3725    }
3726
3727    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3728        // We calculate the max size of permissions defined by this uid and throw
3729        // if that plus the size of 'info' would exceed our stated maximum.
3730        if (tree.uid != Process.SYSTEM_UID) {
3731            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3732            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3733                throw new SecurityException("Permission tree size cap exceeded");
3734            }
3735        }
3736    }
3737
3738    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3739        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3740            throw new SecurityException("Label must be specified in permission");
3741        }
3742        BasePermission tree = checkPermissionTreeLP(info.name);
3743        BasePermission bp = mSettings.mPermissions.get(info.name);
3744        boolean added = bp == null;
3745        boolean changed = true;
3746        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3747        if (added) {
3748            enforcePermissionCapLocked(info, tree);
3749            bp = new BasePermission(info.name, tree.sourcePackage,
3750                    BasePermission.TYPE_DYNAMIC);
3751        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3752            throw new SecurityException(
3753                    "Not allowed to modify non-dynamic permission "
3754                    + info.name);
3755        } else {
3756            if (bp.protectionLevel == fixedLevel
3757                    && bp.perm.owner.equals(tree.perm.owner)
3758                    && bp.uid == tree.uid
3759                    && comparePermissionInfos(bp.perm.info, info)) {
3760                changed = false;
3761            }
3762        }
3763        bp.protectionLevel = fixedLevel;
3764        info = new PermissionInfo(info);
3765        info.protectionLevel = fixedLevel;
3766        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3767        bp.perm.info.packageName = tree.perm.info.packageName;
3768        bp.uid = tree.uid;
3769        if (added) {
3770            mSettings.mPermissions.put(info.name, bp);
3771        }
3772        if (changed) {
3773            if (!async) {
3774                mSettings.writeLPr();
3775            } else {
3776                scheduleWriteSettingsLocked();
3777            }
3778        }
3779        return added;
3780    }
3781
3782    @Override
3783    public boolean addPermission(PermissionInfo info) {
3784        synchronized (mPackages) {
3785            return addPermissionLocked(info, false);
3786        }
3787    }
3788
3789    @Override
3790    public boolean addPermissionAsync(PermissionInfo info) {
3791        synchronized (mPackages) {
3792            return addPermissionLocked(info, true);
3793        }
3794    }
3795
3796    @Override
3797    public void removePermission(String name) {
3798        synchronized (mPackages) {
3799            checkPermissionTreeLP(name);
3800            BasePermission bp = mSettings.mPermissions.get(name);
3801            if (bp != null) {
3802                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3803                    throw new SecurityException(
3804                            "Not allowed to modify non-dynamic permission "
3805                            + name);
3806                }
3807                mSettings.mPermissions.remove(name);
3808                mSettings.writeLPr();
3809            }
3810        }
3811    }
3812
3813    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3814            BasePermission bp) {
3815        int index = pkg.requestedPermissions.indexOf(bp.name);
3816        if (index == -1) {
3817            throw new SecurityException("Package " + pkg.packageName
3818                    + " has not requested permission " + bp.name);
3819        }
3820        if (!bp.isRuntime() && !bp.isDevelopment()) {
3821            throw new SecurityException("Permission " + bp.name
3822                    + " is not a changeable permission type");
3823        }
3824    }
3825
3826    @Override
3827    public void grantRuntimePermission(String packageName, String name, final int userId) {
3828        if (!sUserManager.exists(userId)) {
3829            Log.e(TAG, "No such user:" + userId);
3830            return;
3831        }
3832
3833        mContext.enforceCallingOrSelfPermission(
3834                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3835                "grantRuntimePermission");
3836
3837        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3838                "grantRuntimePermission");
3839
3840        final int uid;
3841        final SettingBase sb;
3842
3843        synchronized (mPackages) {
3844            final PackageParser.Package pkg = mPackages.get(packageName);
3845            if (pkg == null) {
3846                throw new IllegalArgumentException("Unknown package: " + packageName);
3847            }
3848
3849            final BasePermission bp = mSettings.mPermissions.get(name);
3850            if (bp == null) {
3851                throw new IllegalArgumentException("Unknown permission: " + name);
3852            }
3853
3854            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3855
3856            // If a permission review is required for legacy apps we represent
3857            // their permissions as always granted runtime ones since we need
3858            // to keep the review required permission flag per user while an
3859            // install permission's state is shared across all users.
3860            if (Build.PERMISSIONS_REVIEW_REQUIRED
3861                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3862                    && bp.isRuntime()) {
3863                return;
3864            }
3865
3866            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3867            sb = (SettingBase) pkg.mExtras;
3868            if (sb == null) {
3869                throw new IllegalArgumentException("Unknown package: " + packageName);
3870            }
3871
3872            final PermissionsState permissionsState = sb.getPermissionsState();
3873
3874            final int flags = permissionsState.getPermissionFlags(name, userId);
3875            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3876                throw new SecurityException("Cannot grant system fixed permission "
3877                        + name + " for package " + packageName);
3878            }
3879
3880            if (bp.isDevelopment()) {
3881                // Development permissions must be handled specially, since they are not
3882                // normal runtime permissions.  For now they apply to all users.
3883                if (permissionsState.grantInstallPermission(bp) !=
3884                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3885                    scheduleWriteSettingsLocked();
3886                }
3887                return;
3888            }
3889
3890            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3891                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3892                return;
3893            }
3894
3895            final int result = permissionsState.grantRuntimePermission(bp, userId);
3896            switch (result) {
3897                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3898                    return;
3899                }
3900
3901                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3902                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3903                    mHandler.post(new Runnable() {
3904                        @Override
3905                        public void run() {
3906                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3907                        }
3908                    });
3909                }
3910                break;
3911            }
3912
3913            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3914
3915            // Not critical if that is lost - app has to request again.
3916            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3917        }
3918
3919        // Only need to do this if user is initialized. Otherwise it's a new user
3920        // and there are no processes running as the user yet and there's no need
3921        // to make an expensive call to remount processes for the changed permissions.
3922        if (READ_EXTERNAL_STORAGE.equals(name)
3923                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3924            final long token = Binder.clearCallingIdentity();
3925            try {
3926                if (sUserManager.isInitialized(userId)) {
3927                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3928                            MountServiceInternal.class);
3929                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3930                }
3931            } finally {
3932                Binder.restoreCallingIdentity(token);
3933            }
3934        }
3935    }
3936
3937    @Override
3938    public void revokeRuntimePermission(String packageName, String name, int userId) {
3939        if (!sUserManager.exists(userId)) {
3940            Log.e(TAG, "No such user:" + userId);
3941            return;
3942        }
3943
3944        mContext.enforceCallingOrSelfPermission(
3945                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3946                "revokeRuntimePermission");
3947
3948        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3949                "revokeRuntimePermission");
3950
3951        final int appId;
3952
3953        synchronized (mPackages) {
3954            final PackageParser.Package pkg = mPackages.get(packageName);
3955            if (pkg == null) {
3956                throw new IllegalArgumentException("Unknown package: " + packageName);
3957            }
3958
3959            final BasePermission bp = mSettings.mPermissions.get(name);
3960            if (bp == null) {
3961                throw new IllegalArgumentException("Unknown permission: " + name);
3962            }
3963
3964            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3965
3966            // If a permission review is required for legacy apps we represent
3967            // their permissions as always granted runtime ones since we need
3968            // to keep the review required permission flag per user while an
3969            // install permission's state is shared across all users.
3970            if (Build.PERMISSIONS_REVIEW_REQUIRED
3971                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3972                    && bp.isRuntime()) {
3973                return;
3974            }
3975
3976            SettingBase sb = (SettingBase) pkg.mExtras;
3977            if (sb == null) {
3978                throw new IllegalArgumentException("Unknown package: " + packageName);
3979            }
3980
3981            final PermissionsState permissionsState = sb.getPermissionsState();
3982
3983            final int flags = permissionsState.getPermissionFlags(name, userId);
3984            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3985                throw new SecurityException("Cannot revoke system fixed permission "
3986                        + name + " for package " + packageName);
3987            }
3988
3989            if (bp.isDevelopment()) {
3990                // Development permissions must be handled specially, since they are not
3991                // normal runtime permissions.  For now they apply to all users.
3992                if (permissionsState.revokeInstallPermission(bp) !=
3993                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3994                    scheduleWriteSettingsLocked();
3995                }
3996                return;
3997            }
3998
3999            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4000                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4001                return;
4002            }
4003
4004            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4005
4006            // Critical, after this call app should never have the permission.
4007            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4008
4009            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4010        }
4011
4012        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4013    }
4014
4015    @Override
4016    public void resetRuntimePermissions() {
4017        mContext.enforceCallingOrSelfPermission(
4018                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4019                "revokeRuntimePermission");
4020
4021        int callingUid = Binder.getCallingUid();
4022        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4023            mContext.enforceCallingOrSelfPermission(
4024                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4025                    "resetRuntimePermissions");
4026        }
4027
4028        synchronized (mPackages) {
4029            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4030            for (int userId : UserManagerService.getInstance().getUserIds()) {
4031                final int packageCount = mPackages.size();
4032                for (int i = 0; i < packageCount; i++) {
4033                    PackageParser.Package pkg = mPackages.valueAt(i);
4034                    if (!(pkg.mExtras instanceof PackageSetting)) {
4035                        continue;
4036                    }
4037                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4038                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4039                }
4040            }
4041        }
4042    }
4043
4044    @Override
4045    public int getPermissionFlags(String name, String packageName, int userId) {
4046        if (!sUserManager.exists(userId)) {
4047            return 0;
4048        }
4049
4050        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4051
4052        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4053                "getPermissionFlags");
4054
4055        synchronized (mPackages) {
4056            final PackageParser.Package pkg = mPackages.get(packageName);
4057            if (pkg == null) {
4058                throw new IllegalArgumentException("Unknown package: " + packageName);
4059            }
4060
4061            final BasePermission bp = mSettings.mPermissions.get(name);
4062            if (bp == null) {
4063                throw new IllegalArgumentException("Unknown permission: " + name);
4064            }
4065
4066            SettingBase sb = (SettingBase) pkg.mExtras;
4067            if (sb == null) {
4068                throw new IllegalArgumentException("Unknown package: " + packageName);
4069            }
4070
4071            PermissionsState permissionsState = sb.getPermissionsState();
4072            return permissionsState.getPermissionFlags(name, userId);
4073        }
4074    }
4075
4076    @Override
4077    public void updatePermissionFlags(String name, String packageName, int flagMask,
4078            int flagValues, int userId) {
4079        if (!sUserManager.exists(userId)) {
4080            return;
4081        }
4082
4083        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4084
4085        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4086                "updatePermissionFlags");
4087
4088        // Only the system can change these flags and nothing else.
4089        if (getCallingUid() != Process.SYSTEM_UID) {
4090            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4091            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4092            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4093            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4094            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4095        }
4096
4097        synchronized (mPackages) {
4098            final PackageParser.Package pkg = mPackages.get(packageName);
4099            if (pkg == null) {
4100                throw new IllegalArgumentException("Unknown package: " + packageName);
4101            }
4102
4103            final BasePermission bp = mSettings.mPermissions.get(name);
4104            if (bp == null) {
4105                throw new IllegalArgumentException("Unknown permission: " + name);
4106            }
4107
4108            SettingBase sb = (SettingBase) pkg.mExtras;
4109            if (sb == null) {
4110                throw new IllegalArgumentException("Unknown package: " + packageName);
4111            }
4112
4113            PermissionsState permissionsState = sb.getPermissionsState();
4114
4115            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4116
4117            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4118                // Install and runtime permissions are stored in different places,
4119                // so figure out what permission changed and persist the change.
4120                if (permissionsState.getInstallPermissionState(name) != null) {
4121                    scheduleWriteSettingsLocked();
4122                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4123                        || hadState) {
4124                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4125                }
4126            }
4127        }
4128    }
4129
4130    /**
4131     * Update the permission flags for all packages and runtime permissions of a user in order
4132     * to allow device or profile owner to remove POLICY_FIXED.
4133     */
4134    @Override
4135    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4136        if (!sUserManager.exists(userId)) {
4137            return;
4138        }
4139
4140        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4141
4142        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4143                "updatePermissionFlagsForAllApps");
4144
4145        // Only the system can change system fixed flags.
4146        if (getCallingUid() != Process.SYSTEM_UID) {
4147            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4148            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4149        }
4150
4151        synchronized (mPackages) {
4152            boolean changed = false;
4153            final int packageCount = mPackages.size();
4154            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4155                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4156                SettingBase sb = (SettingBase) pkg.mExtras;
4157                if (sb == null) {
4158                    continue;
4159                }
4160                PermissionsState permissionsState = sb.getPermissionsState();
4161                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4162                        userId, flagMask, flagValues);
4163            }
4164            if (changed) {
4165                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4166            }
4167        }
4168    }
4169
4170    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4171        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4172                != PackageManager.PERMISSION_GRANTED
4173            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4174                != PackageManager.PERMISSION_GRANTED) {
4175            throw new SecurityException(message + " requires "
4176                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4177                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4178        }
4179    }
4180
4181    @Override
4182    public boolean shouldShowRequestPermissionRationale(String permissionName,
4183            String packageName, int userId) {
4184        if (UserHandle.getCallingUserId() != userId) {
4185            mContext.enforceCallingPermission(
4186                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4187                    "canShowRequestPermissionRationale for user " + userId);
4188        }
4189
4190        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4191        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4192            return false;
4193        }
4194
4195        if (checkPermission(permissionName, packageName, userId)
4196                == PackageManager.PERMISSION_GRANTED) {
4197            return false;
4198        }
4199
4200        final int flags;
4201
4202        final long identity = Binder.clearCallingIdentity();
4203        try {
4204            flags = getPermissionFlags(permissionName,
4205                    packageName, userId);
4206        } finally {
4207            Binder.restoreCallingIdentity(identity);
4208        }
4209
4210        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4211                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4212                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4213
4214        if ((flags & fixedFlags) != 0) {
4215            return false;
4216        }
4217
4218        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4219    }
4220
4221    @Override
4222    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4223        mContext.enforceCallingOrSelfPermission(
4224                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4225                "addOnPermissionsChangeListener");
4226
4227        synchronized (mPackages) {
4228            mOnPermissionChangeListeners.addListenerLocked(listener);
4229        }
4230    }
4231
4232    @Override
4233    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4234        synchronized (mPackages) {
4235            mOnPermissionChangeListeners.removeListenerLocked(listener);
4236        }
4237    }
4238
4239    @Override
4240    public boolean isProtectedBroadcast(String actionName) {
4241        synchronized (mPackages) {
4242            if (mProtectedBroadcasts.contains(actionName)) {
4243                return true;
4244            } else if (actionName != null) {
4245                // TODO: remove these terrible hacks
4246                if (actionName.startsWith("android.net.netmon.lingerExpired")
4247                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4248                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")) {
4249                    return true;
4250                }
4251            }
4252        }
4253        return false;
4254    }
4255
4256    @Override
4257    public int checkSignatures(String pkg1, String pkg2) {
4258        synchronized (mPackages) {
4259            final PackageParser.Package p1 = mPackages.get(pkg1);
4260            final PackageParser.Package p2 = mPackages.get(pkg2);
4261            if (p1 == null || p1.mExtras == null
4262                    || p2 == null || p2.mExtras == null) {
4263                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4264            }
4265            return compareSignatures(p1.mSignatures, p2.mSignatures);
4266        }
4267    }
4268
4269    @Override
4270    public int checkUidSignatures(int uid1, int uid2) {
4271        // Map to base uids.
4272        uid1 = UserHandle.getAppId(uid1);
4273        uid2 = UserHandle.getAppId(uid2);
4274        // reader
4275        synchronized (mPackages) {
4276            Signature[] s1;
4277            Signature[] s2;
4278            Object obj = mSettings.getUserIdLPr(uid1);
4279            if (obj != null) {
4280                if (obj instanceof SharedUserSetting) {
4281                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4282                } else if (obj instanceof PackageSetting) {
4283                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4284                } else {
4285                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4286                }
4287            } else {
4288                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4289            }
4290            obj = mSettings.getUserIdLPr(uid2);
4291            if (obj != null) {
4292                if (obj instanceof SharedUserSetting) {
4293                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4294                } else if (obj instanceof PackageSetting) {
4295                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4296                } else {
4297                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4298                }
4299            } else {
4300                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4301            }
4302            return compareSignatures(s1, s2);
4303        }
4304    }
4305
4306    private void killUid(int appId, int userId, String reason) {
4307        final long identity = Binder.clearCallingIdentity();
4308        try {
4309            IActivityManager am = ActivityManagerNative.getDefault();
4310            if (am != null) {
4311                try {
4312                    am.killUid(appId, userId, reason);
4313                } catch (RemoteException e) {
4314                    /* ignore - same process */
4315                }
4316            }
4317        } finally {
4318            Binder.restoreCallingIdentity(identity);
4319        }
4320    }
4321
4322    /**
4323     * Compares two sets of signatures. Returns:
4324     * <br />
4325     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4326     * <br />
4327     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4328     * <br />
4329     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4330     * <br />
4331     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4332     * <br />
4333     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4334     */
4335    static int compareSignatures(Signature[] s1, Signature[] s2) {
4336        if (s1 == null) {
4337            return s2 == null
4338                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4339                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4340        }
4341
4342        if (s2 == null) {
4343            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4344        }
4345
4346        if (s1.length != s2.length) {
4347            return PackageManager.SIGNATURE_NO_MATCH;
4348        }
4349
4350        // Since both signature sets are of size 1, we can compare without HashSets.
4351        if (s1.length == 1) {
4352            return s1[0].equals(s2[0]) ?
4353                    PackageManager.SIGNATURE_MATCH :
4354                    PackageManager.SIGNATURE_NO_MATCH;
4355        }
4356
4357        ArraySet<Signature> set1 = new ArraySet<Signature>();
4358        for (Signature sig : s1) {
4359            set1.add(sig);
4360        }
4361        ArraySet<Signature> set2 = new ArraySet<Signature>();
4362        for (Signature sig : s2) {
4363            set2.add(sig);
4364        }
4365        // Make sure s2 contains all signatures in s1.
4366        if (set1.equals(set2)) {
4367            return PackageManager.SIGNATURE_MATCH;
4368        }
4369        return PackageManager.SIGNATURE_NO_MATCH;
4370    }
4371
4372    /**
4373     * If the database version for this type of package (internal storage or
4374     * external storage) is less than the version where package signatures
4375     * were updated, return true.
4376     */
4377    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4378        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4379        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4380    }
4381
4382    /**
4383     * Used for backward compatibility to make sure any packages with
4384     * certificate chains get upgraded to the new style. {@code existingSigs}
4385     * will be in the old format (since they were stored on disk from before the
4386     * system upgrade) and {@code scannedSigs} will be in the newer format.
4387     */
4388    private int compareSignaturesCompat(PackageSignatures existingSigs,
4389            PackageParser.Package scannedPkg) {
4390        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4391            return PackageManager.SIGNATURE_NO_MATCH;
4392        }
4393
4394        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4395        for (Signature sig : existingSigs.mSignatures) {
4396            existingSet.add(sig);
4397        }
4398        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4399        for (Signature sig : scannedPkg.mSignatures) {
4400            try {
4401                Signature[] chainSignatures = sig.getChainSignatures();
4402                for (Signature chainSig : chainSignatures) {
4403                    scannedCompatSet.add(chainSig);
4404                }
4405            } catch (CertificateEncodingException e) {
4406                scannedCompatSet.add(sig);
4407            }
4408        }
4409        /*
4410         * Make sure the expanded scanned set contains all signatures in the
4411         * existing one.
4412         */
4413        if (scannedCompatSet.equals(existingSet)) {
4414            // Migrate the old signatures to the new scheme.
4415            existingSigs.assignSignatures(scannedPkg.mSignatures);
4416            // The new KeySets will be re-added later in the scanning process.
4417            synchronized (mPackages) {
4418                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4419            }
4420            return PackageManager.SIGNATURE_MATCH;
4421        }
4422        return PackageManager.SIGNATURE_NO_MATCH;
4423    }
4424
4425    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4426        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4427        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4428    }
4429
4430    private int compareSignaturesRecover(PackageSignatures existingSigs,
4431            PackageParser.Package scannedPkg) {
4432        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4433            return PackageManager.SIGNATURE_NO_MATCH;
4434        }
4435
4436        String msg = null;
4437        try {
4438            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4439                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4440                        + scannedPkg.packageName);
4441                return PackageManager.SIGNATURE_MATCH;
4442            }
4443        } catch (CertificateException e) {
4444            msg = e.getMessage();
4445        }
4446
4447        logCriticalInfo(Log.INFO,
4448                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4449        return PackageManager.SIGNATURE_NO_MATCH;
4450    }
4451
4452    @Override
4453    public String[] getPackagesForUid(int uid) {
4454        uid = UserHandle.getAppId(uid);
4455        // reader
4456        synchronized (mPackages) {
4457            Object obj = mSettings.getUserIdLPr(uid);
4458            if (obj instanceof SharedUserSetting) {
4459                final SharedUserSetting sus = (SharedUserSetting) obj;
4460                final int N = sus.packages.size();
4461                final String[] res = new String[N];
4462                final Iterator<PackageSetting> it = sus.packages.iterator();
4463                int i = 0;
4464                while (it.hasNext()) {
4465                    res[i++] = it.next().name;
4466                }
4467                return res;
4468            } else if (obj instanceof PackageSetting) {
4469                final PackageSetting ps = (PackageSetting) obj;
4470                return new String[] { ps.name };
4471            }
4472        }
4473        return null;
4474    }
4475
4476    @Override
4477    public String getNameForUid(int uid) {
4478        // reader
4479        synchronized (mPackages) {
4480            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4481            if (obj instanceof SharedUserSetting) {
4482                final SharedUserSetting sus = (SharedUserSetting) obj;
4483                return sus.name + ":" + sus.userId;
4484            } else if (obj instanceof PackageSetting) {
4485                final PackageSetting ps = (PackageSetting) obj;
4486                return ps.name;
4487            }
4488        }
4489        return null;
4490    }
4491
4492    @Override
4493    public int getUidForSharedUser(String sharedUserName) {
4494        if(sharedUserName == null) {
4495            return -1;
4496        }
4497        // reader
4498        synchronized (mPackages) {
4499            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4500            if (suid == null) {
4501                return -1;
4502            }
4503            return suid.userId;
4504        }
4505    }
4506
4507    @Override
4508    public int getFlagsForUid(int uid) {
4509        synchronized (mPackages) {
4510            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4511            if (obj instanceof SharedUserSetting) {
4512                final SharedUserSetting sus = (SharedUserSetting) obj;
4513                return sus.pkgFlags;
4514            } else if (obj instanceof PackageSetting) {
4515                final PackageSetting ps = (PackageSetting) obj;
4516                return ps.pkgFlags;
4517            }
4518        }
4519        return 0;
4520    }
4521
4522    @Override
4523    public int getPrivateFlagsForUid(int uid) {
4524        synchronized (mPackages) {
4525            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4526            if (obj instanceof SharedUserSetting) {
4527                final SharedUserSetting sus = (SharedUserSetting) obj;
4528                return sus.pkgPrivateFlags;
4529            } else if (obj instanceof PackageSetting) {
4530                final PackageSetting ps = (PackageSetting) obj;
4531                return ps.pkgPrivateFlags;
4532            }
4533        }
4534        return 0;
4535    }
4536
4537    @Override
4538    public boolean isUidPrivileged(int uid) {
4539        uid = UserHandle.getAppId(uid);
4540        // reader
4541        synchronized (mPackages) {
4542            Object obj = mSettings.getUserIdLPr(uid);
4543            if (obj instanceof SharedUserSetting) {
4544                final SharedUserSetting sus = (SharedUserSetting) obj;
4545                final Iterator<PackageSetting> it = sus.packages.iterator();
4546                while (it.hasNext()) {
4547                    if (it.next().isPrivileged()) {
4548                        return true;
4549                    }
4550                }
4551            } else if (obj instanceof PackageSetting) {
4552                final PackageSetting ps = (PackageSetting) obj;
4553                return ps.isPrivileged();
4554            }
4555        }
4556        return false;
4557    }
4558
4559    @Override
4560    public String[] getAppOpPermissionPackages(String permissionName) {
4561        synchronized (mPackages) {
4562            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4563            if (pkgs == null) {
4564                return null;
4565            }
4566            return pkgs.toArray(new String[pkgs.size()]);
4567        }
4568    }
4569
4570    @Override
4571    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4572            int flags, int userId) {
4573        if (!sUserManager.exists(userId)) return null;
4574        flags = updateFlagsForResolve(flags, userId, intent);
4575        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4576        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4577        final ResolveInfo bestChoice =
4578                chooseBestActivity(intent, resolvedType, flags, query, userId);
4579
4580        if (isEphemeralAllowed(intent, query, userId)) {
4581            final EphemeralResolveInfo ai =
4582                    getEphemeralResolveInfo(intent, resolvedType, userId);
4583            if (ai != null) {
4584                if (DEBUG_EPHEMERAL) {
4585                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4586                }
4587                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4588                bestChoice.ephemeralResolveInfo = ai;
4589            }
4590        }
4591        return bestChoice;
4592    }
4593
4594    @Override
4595    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4596            IntentFilter filter, int match, ComponentName activity) {
4597        final int userId = UserHandle.getCallingUserId();
4598        if (DEBUG_PREFERRED) {
4599            Log.v(TAG, "setLastChosenActivity intent=" + intent
4600                + " resolvedType=" + resolvedType
4601                + " flags=" + flags
4602                + " filter=" + filter
4603                + " match=" + match
4604                + " activity=" + activity);
4605            filter.dump(new PrintStreamPrinter(System.out), "    ");
4606        }
4607        intent.setComponent(null);
4608        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4609        // Find any earlier preferred or last chosen entries and nuke them
4610        findPreferredActivity(intent, resolvedType,
4611                flags, query, 0, false, true, false, userId);
4612        // Add the new activity as the last chosen for this filter
4613        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4614                "Setting last chosen");
4615    }
4616
4617    @Override
4618    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4619        final int userId = UserHandle.getCallingUserId();
4620        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4621        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4622        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4623                false, false, false, userId);
4624    }
4625
4626
4627    private boolean isEphemeralAllowed(
4628            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4629        // Short circuit and return early if possible.
4630        if (DISABLE_EPHEMERAL_APPS) {
4631            return false;
4632        }
4633        final int callingUser = UserHandle.getCallingUserId();
4634        if (callingUser != UserHandle.USER_SYSTEM) {
4635            return false;
4636        }
4637        if (mEphemeralResolverConnection == null) {
4638            return false;
4639        }
4640        if (intent.getComponent() != null) {
4641            return false;
4642        }
4643        if (intent.getPackage() != null) {
4644            return false;
4645        }
4646        final boolean isWebUri = hasWebURI(intent);
4647        if (!isWebUri) {
4648            return false;
4649        }
4650        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4651        synchronized (mPackages) {
4652            final int count = resolvedActivites.size();
4653            for (int n = 0; n < count; n++) {
4654                ResolveInfo info = resolvedActivites.get(n);
4655                String packageName = info.activityInfo.packageName;
4656                PackageSetting ps = mSettings.mPackages.get(packageName);
4657                if (ps != null) {
4658                    // Try to get the status from User settings first
4659                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4660                    int status = (int) (packedStatus >> 32);
4661                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4662                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4663                        if (DEBUG_EPHEMERAL) {
4664                            Slog.v(TAG, "DENY ephemeral apps;"
4665                                + " pkg: " + packageName + ", status: " + status);
4666                        }
4667                        return false;
4668                    }
4669                }
4670            }
4671        }
4672        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4673        return true;
4674    }
4675
4676    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4677            int userId) {
4678        MessageDigest digest = null;
4679        try {
4680            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4681        } catch (NoSuchAlgorithmException e) {
4682            // If we can't create a digest, ignore ephemeral apps.
4683            return null;
4684        }
4685
4686        final byte[] hostBytes = intent.getData().getHost().getBytes();
4687        final byte[] digestBytes = digest.digest(hostBytes);
4688        int shaPrefix =
4689                digestBytes[0] << 24
4690                | digestBytes[1] << 16
4691                | digestBytes[2] << 8
4692                | digestBytes[3] << 0;
4693        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4694                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4695        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4696            // No hash prefix match; there are no ephemeral apps for this domain.
4697            return null;
4698        }
4699        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4700            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4701            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4702                continue;
4703            }
4704            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4705            // No filters; this should never happen.
4706            if (filters.isEmpty()) {
4707                continue;
4708            }
4709            // We have a domain match; resolve the filters to see if anything matches.
4710            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4711            for (int j = filters.size() - 1; j >= 0; --j) {
4712                final EphemeralResolveIntentInfo intentInfo =
4713                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4714                ephemeralResolver.addFilter(intentInfo);
4715            }
4716            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4717                    intent, resolvedType, false /*defaultOnly*/, userId);
4718            if (!matchedResolveInfoList.isEmpty()) {
4719                return matchedResolveInfoList.get(0);
4720            }
4721        }
4722        // Hash or filter mis-match; no ephemeral apps for this domain.
4723        return null;
4724    }
4725
4726    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4727            int flags, List<ResolveInfo> query, int userId) {
4728        if (query != null) {
4729            final int N = query.size();
4730            if (N == 1) {
4731                return query.get(0);
4732            } else if (N > 1) {
4733                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4734                // If there is more than one activity with the same priority,
4735                // then let the user decide between them.
4736                ResolveInfo r0 = query.get(0);
4737                ResolveInfo r1 = query.get(1);
4738                if (DEBUG_INTENT_MATCHING || debug) {
4739                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4740                            + r1.activityInfo.name + "=" + r1.priority);
4741                }
4742                // If the first activity has a higher priority, or a different
4743                // default, then it is always desirable to pick it.
4744                if (r0.priority != r1.priority
4745                        || r0.preferredOrder != r1.preferredOrder
4746                        || r0.isDefault != r1.isDefault) {
4747                    return query.get(0);
4748                }
4749                // If we have saved a preference for a preferred activity for
4750                // this Intent, use that.
4751                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4752                        flags, query, r0.priority, true, false, debug, userId);
4753                if (ri != null) {
4754                    return ri;
4755                }
4756                ri = new ResolveInfo(mResolveInfo);
4757                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4758                ri.activityInfo.applicationInfo = new ApplicationInfo(
4759                        ri.activityInfo.applicationInfo);
4760                if (userId != 0) {
4761                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4762                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4763                }
4764                // Make sure that the resolver is displayable in car mode
4765                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4766                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4767                return ri;
4768            }
4769        }
4770        return null;
4771    }
4772
4773    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4774            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4775        final int N = query.size();
4776        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4777                .get(userId);
4778        // Get the list of persistent preferred activities that handle the intent
4779        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4780        List<PersistentPreferredActivity> pprefs = ppir != null
4781                ? ppir.queryIntent(intent, resolvedType,
4782                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4783                : null;
4784        if (pprefs != null && pprefs.size() > 0) {
4785            final int M = pprefs.size();
4786            for (int i=0; i<M; i++) {
4787                final PersistentPreferredActivity ppa = pprefs.get(i);
4788                if (DEBUG_PREFERRED || debug) {
4789                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4790                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4791                            + "\n  component=" + ppa.mComponent);
4792                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4793                }
4794                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4795                        flags | MATCH_DISABLED_COMPONENTS, userId);
4796                if (DEBUG_PREFERRED || debug) {
4797                    Slog.v(TAG, "Found persistent preferred activity:");
4798                    if (ai != null) {
4799                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4800                    } else {
4801                        Slog.v(TAG, "  null");
4802                    }
4803                }
4804                if (ai == null) {
4805                    // This previously registered persistent preferred activity
4806                    // component is no longer known. Ignore it and do NOT remove it.
4807                    continue;
4808                }
4809                for (int j=0; j<N; j++) {
4810                    final ResolveInfo ri = query.get(j);
4811                    if (!ri.activityInfo.applicationInfo.packageName
4812                            .equals(ai.applicationInfo.packageName)) {
4813                        continue;
4814                    }
4815                    if (!ri.activityInfo.name.equals(ai.name)) {
4816                        continue;
4817                    }
4818                    //  Found a persistent preference that can handle the intent.
4819                    if (DEBUG_PREFERRED || debug) {
4820                        Slog.v(TAG, "Returning persistent preferred activity: " +
4821                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4822                    }
4823                    return ri;
4824                }
4825            }
4826        }
4827        return null;
4828    }
4829
4830    // TODO: handle preferred activities missing while user has amnesia
4831    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4832            List<ResolveInfo> query, int priority, boolean always,
4833            boolean removeMatches, boolean debug, int userId) {
4834        if (!sUserManager.exists(userId)) return null;
4835        flags = updateFlagsForResolve(flags, userId, intent);
4836        // writer
4837        synchronized (mPackages) {
4838            if (intent.getSelector() != null) {
4839                intent = intent.getSelector();
4840            }
4841            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4842
4843            // Try to find a matching persistent preferred activity.
4844            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4845                    debug, userId);
4846
4847            // If a persistent preferred activity matched, use it.
4848            if (pri != null) {
4849                return pri;
4850            }
4851
4852            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4853            // Get the list of preferred activities that handle the intent
4854            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4855            List<PreferredActivity> prefs = pir != null
4856                    ? pir.queryIntent(intent, resolvedType,
4857                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4858                    : null;
4859            if (prefs != null && prefs.size() > 0) {
4860                boolean changed = false;
4861                try {
4862                    // First figure out how good the original match set is.
4863                    // We will only allow preferred activities that came
4864                    // from the same match quality.
4865                    int match = 0;
4866
4867                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4868
4869                    final int N = query.size();
4870                    for (int j=0; j<N; j++) {
4871                        final ResolveInfo ri = query.get(j);
4872                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4873                                + ": 0x" + Integer.toHexString(match));
4874                        if (ri.match > match) {
4875                            match = ri.match;
4876                        }
4877                    }
4878
4879                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4880                            + Integer.toHexString(match));
4881
4882                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4883                    final int M = prefs.size();
4884                    for (int i=0; i<M; i++) {
4885                        final PreferredActivity pa = prefs.get(i);
4886                        if (DEBUG_PREFERRED || debug) {
4887                            Slog.v(TAG, "Checking PreferredActivity ds="
4888                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4889                                    + "\n  component=" + pa.mPref.mComponent);
4890                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4891                        }
4892                        if (pa.mPref.mMatch != match) {
4893                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4894                                    + Integer.toHexString(pa.mPref.mMatch));
4895                            continue;
4896                        }
4897                        // If it's not an "always" type preferred activity and that's what we're
4898                        // looking for, skip it.
4899                        if (always && !pa.mPref.mAlways) {
4900                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4901                            continue;
4902                        }
4903                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4904                                flags | MATCH_DISABLED_COMPONENTS, userId);
4905                        if (DEBUG_PREFERRED || debug) {
4906                            Slog.v(TAG, "Found preferred activity:");
4907                            if (ai != null) {
4908                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4909                            } else {
4910                                Slog.v(TAG, "  null");
4911                            }
4912                        }
4913                        if (ai == null) {
4914                            // This previously registered preferred activity
4915                            // component is no longer known.  Most likely an update
4916                            // to the app was installed and in the new version this
4917                            // component no longer exists.  Clean it up by removing
4918                            // it from the preferred activities list, and skip it.
4919                            Slog.w(TAG, "Removing dangling preferred activity: "
4920                                    + pa.mPref.mComponent);
4921                            pir.removeFilter(pa);
4922                            changed = true;
4923                            continue;
4924                        }
4925                        for (int j=0; j<N; j++) {
4926                            final ResolveInfo ri = query.get(j);
4927                            if (!ri.activityInfo.applicationInfo.packageName
4928                                    .equals(ai.applicationInfo.packageName)) {
4929                                continue;
4930                            }
4931                            if (!ri.activityInfo.name.equals(ai.name)) {
4932                                continue;
4933                            }
4934
4935                            if (removeMatches) {
4936                                pir.removeFilter(pa);
4937                                changed = true;
4938                                if (DEBUG_PREFERRED) {
4939                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4940                                }
4941                                break;
4942                            }
4943
4944                            // Okay we found a previously set preferred or last chosen app.
4945                            // If the result set is different from when this
4946                            // was created, we need to clear it and re-ask the
4947                            // user their preference, if we're looking for an "always" type entry.
4948                            if (always && !pa.mPref.sameSet(query)) {
4949                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4950                                        + intent + " type " + resolvedType);
4951                                if (DEBUG_PREFERRED) {
4952                                    Slog.v(TAG, "Removing preferred activity since set changed "
4953                                            + pa.mPref.mComponent);
4954                                }
4955                                pir.removeFilter(pa);
4956                                // Re-add the filter as a "last chosen" entry (!always)
4957                                PreferredActivity lastChosen = new PreferredActivity(
4958                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4959                                pir.addFilter(lastChosen);
4960                                changed = true;
4961                                return null;
4962                            }
4963
4964                            // Yay! Either the set matched or we're looking for the last chosen
4965                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4966                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4967                            return ri;
4968                        }
4969                    }
4970                } finally {
4971                    if (changed) {
4972                        if (DEBUG_PREFERRED) {
4973                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4974                        }
4975                        scheduleWritePackageRestrictionsLocked(userId);
4976                    }
4977                }
4978            }
4979        }
4980        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4981        return null;
4982    }
4983
4984    /*
4985     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4986     */
4987    @Override
4988    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4989            int targetUserId) {
4990        mContext.enforceCallingOrSelfPermission(
4991                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4992        List<CrossProfileIntentFilter> matches =
4993                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4994        if (matches != null) {
4995            int size = matches.size();
4996            for (int i = 0; i < size; i++) {
4997                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4998            }
4999        }
5000        if (hasWebURI(intent)) {
5001            // cross-profile app linking works only towards the parent.
5002            final UserInfo parent = getProfileParent(sourceUserId);
5003            synchronized(mPackages) {
5004                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5005                        intent, resolvedType, 0, sourceUserId, parent.id);
5006                return xpDomainInfo != null;
5007            }
5008        }
5009        return false;
5010    }
5011
5012    private UserInfo getProfileParent(int userId) {
5013        final long identity = Binder.clearCallingIdentity();
5014        try {
5015            return sUserManager.getProfileParent(userId);
5016        } finally {
5017            Binder.restoreCallingIdentity(identity);
5018        }
5019    }
5020
5021    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5022            String resolvedType, int userId) {
5023        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5024        if (resolver != null) {
5025            return resolver.queryIntent(intent, resolvedType, false, userId);
5026        }
5027        return null;
5028    }
5029
5030    @Override
5031    public List<ResolveInfo> queryIntentActivities(Intent intent,
5032            String resolvedType, int flags, int userId) {
5033        if (!sUserManager.exists(userId)) return Collections.emptyList();
5034        flags = updateFlagsForResolve(flags, userId, intent);
5035        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
5036        ComponentName comp = intent.getComponent();
5037        if (comp == null) {
5038            if (intent.getSelector() != null) {
5039                intent = intent.getSelector();
5040                comp = intent.getComponent();
5041            }
5042        }
5043
5044        if (comp != null) {
5045            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5046            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5047            if (ai != null) {
5048                final ResolveInfo ri = new ResolveInfo();
5049                ri.activityInfo = ai;
5050                list.add(ri);
5051            }
5052            return list;
5053        }
5054
5055        // reader
5056        synchronized (mPackages) {
5057            final String pkgName = intent.getPackage();
5058            if (pkgName == null) {
5059                List<CrossProfileIntentFilter> matchingFilters =
5060                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5061                // Check for results that need to skip the current profile.
5062                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5063                        resolvedType, flags, userId);
5064                if (xpResolveInfo != null) {
5065                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5066                    result.add(xpResolveInfo);
5067                    return filterIfNotSystemUser(result, userId);
5068                }
5069
5070                // Check for results in the current profile.
5071                List<ResolveInfo> result = mActivities.queryIntent(
5072                        intent, resolvedType, flags, userId);
5073                result = filterIfNotSystemUser(result, userId);
5074
5075                // Check for cross profile results.
5076                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5077                xpResolveInfo = queryCrossProfileIntents(
5078                        matchingFilters, intent, resolvedType, flags, userId,
5079                        hasNonNegativePriorityResult);
5080                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5081                    boolean isVisibleToUser = filterIfNotSystemUser(
5082                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5083                    if (isVisibleToUser) {
5084                        result.add(xpResolveInfo);
5085                        Collections.sort(result, mResolvePrioritySorter);
5086                    }
5087                }
5088                if (hasWebURI(intent)) {
5089                    CrossProfileDomainInfo xpDomainInfo = null;
5090                    final UserInfo parent = getProfileParent(userId);
5091                    if (parent != null) {
5092                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5093                                flags, userId, parent.id);
5094                    }
5095                    if (xpDomainInfo != null) {
5096                        if (xpResolveInfo != null) {
5097                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5098                            // in the result.
5099                            result.remove(xpResolveInfo);
5100                        }
5101                        if (result.size() == 0) {
5102                            result.add(xpDomainInfo.resolveInfo);
5103                            return result;
5104                        }
5105                    } else if (result.size() <= 1) {
5106                        return result;
5107                    }
5108                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5109                            xpDomainInfo, userId);
5110                    Collections.sort(result, mResolvePrioritySorter);
5111                }
5112                return result;
5113            }
5114            final PackageParser.Package pkg = mPackages.get(pkgName);
5115            if (pkg != null) {
5116                return filterIfNotSystemUser(
5117                        mActivities.queryIntentForPackage(
5118                                intent, resolvedType, flags, pkg.activities, userId),
5119                        userId);
5120            }
5121            return new ArrayList<ResolveInfo>();
5122        }
5123    }
5124
5125    private static class CrossProfileDomainInfo {
5126        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5127        ResolveInfo resolveInfo;
5128        /* Best domain verification status of the activities found in the other profile */
5129        int bestDomainVerificationStatus;
5130    }
5131
5132    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5133            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5134        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5135                sourceUserId)) {
5136            return null;
5137        }
5138        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5139                resolvedType, flags, parentUserId);
5140
5141        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5142            return null;
5143        }
5144        CrossProfileDomainInfo result = null;
5145        int size = resultTargetUser.size();
5146        for (int i = 0; i < size; i++) {
5147            ResolveInfo riTargetUser = resultTargetUser.get(i);
5148            // Intent filter verification is only for filters that specify a host. So don't return
5149            // those that handle all web uris.
5150            if (riTargetUser.handleAllWebDataURI) {
5151                continue;
5152            }
5153            String packageName = riTargetUser.activityInfo.packageName;
5154            PackageSetting ps = mSettings.mPackages.get(packageName);
5155            if (ps == null) {
5156                continue;
5157            }
5158            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5159            int status = (int)(verificationState >> 32);
5160            if (result == null) {
5161                result = new CrossProfileDomainInfo();
5162                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5163                        sourceUserId, parentUserId);
5164                result.bestDomainVerificationStatus = status;
5165            } else {
5166                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5167                        result.bestDomainVerificationStatus);
5168            }
5169        }
5170        // Don't consider matches with status NEVER across profiles.
5171        if (result != null && result.bestDomainVerificationStatus
5172                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5173            return null;
5174        }
5175        return result;
5176    }
5177
5178    /**
5179     * Verification statuses are ordered from the worse to the best, except for
5180     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5181     */
5182    private int bestDomainVerificationStatus(int status1, int status2) {
5183        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5184            return status2;
5185        }
5186        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5187            return status1;
5188        }
5189        return (int) MathUtils.max(status1, status2);
5190    }
5191
5192    private boolean isUserEnabled(int userId) {
5193        long callingId = Binder.clearCallingIdentity();
5194        try {
5195            UserInfo userInfo = sUserManager.getUserInfo(userId);
5196            return userInfo != null && userInfo.isEnabled();
5197        } finally {
5198            Binder.restoreCallingIdentity(callingId);
5199        }
5200    }
5201
5202    /**
5203     * Filter out activities with systemUserOnly flag set, when current user is not System.
5204     *
5205     * @return filtered list
5206     */
5207    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5208        if (userId == UserHandle.USER_SYSTEM) {
5209            return resolveInfos;
5210        }
5211        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5212            ResolveInfo info = resolveInfos.get(i);
5213            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5214                resolveInfos.remove(i);
5215            }
5216        }
5217        return resolveInfos;
5218    }
5219
5220    /**
5221     * @param resolveInfos list of resolve infos in descending priority order
5222     * @return if the list contains a resolve info with non-negative priority
5223     */
5224    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5225        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5226    }
5227
5228    private static boolean hasWebURI(Intent intent) {
5229        if (intent.getData() == null) {
5230            return false;
5231        }
5232        final String scheme = intent.getScheme();
5233        if (TextUtils.isEmpty(scheme)) {
5234            return false;
5235        }
5236        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5237    }
5238
5239    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5240            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5241            int userId) {
5242        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5243
5244        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5245            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5246                    candidates.size());
5247        }
5248
5249        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5250        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5251        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5252        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5253        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5254        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5255
5256        synchronized (mPackages) {
5257            final int count = candidates.size();
5258            // First, try to use linked apps. Partition the candidates into four lists:
5259            // one for the final results, one for the "do not use ever", one for "undefined status"
5260            // and finally one for "browser app type".
5261            for (int n=0; n<count; n++) {
5262                ResolveInfo info = candidates.get(n);
5263                String packageName = info.activityInfo.packageName;
5264                PackageSetting ps = mSettings.mPackages.get(packageName);
5265                if (ps != null) {
5266                    // Add to the special match all list (Browser use case)
5267                    if (info.handleAllWebDataURI) {
5268                        matchAllList.add(info);
5269                        continue;
5270                    }
5271                    // Try to get the status from User settings first
5272                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5273                    int status = (int)(packedStatus >> 32);
5274                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5275                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5276                        if (DEBUG_DOMAIN_VERIFICATION) {
5277                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5278                                    + " : linkgen=" + linkGeneration);
5279                        }
5280                        // Use link-enabled generation as preferredOrder, i.e.
5281                        // prefer newly-enabled over earlier-enabled.
5282                        info.preferredOrder = linkGeneration;
5283                        alwaysList.add(info);
5284                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5285                        if (DEBUG_DOMAIN_VERIFICATION) {
5286                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5287                        }
5288                        neverList.add(info);
5289                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5290                        if (DEBUG_DOMAIN_VERIFICATION) {
5291                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5292                        }
5293                        alwaysAskList.add(info);
5294                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5295                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5296                        if (DEBUG_DOMAIN_VERIFICATION) {
5297                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5298                        }
5299                        undefinedList.add(info);
5300                    }
5301                }
5302            }
5303
5304            // We'll want to include browser possibilities in a few cases
5305            boolean includeBrowser = false;
5306
5307            // First try to add the "always" resolution(s) for the current user, if any
5308            if (alwaysList.size() > 0) {
5309                result.addAll(alwaysList);
5310            } else {
5311                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5312                result.addAll(undefinedList);
5313                // Maybe add one for the other profile.
5314                if (xpDomainInfo != null && (
5315                        xpDomainInfo.bestDomainVerificationStatus
5316                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5317                    result.add(xpDomainInfo.resolveInfo);
5318                }
5319                includeBrowser = true;
5320            }
5321
5322            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5323            // If there were 'always' entries their preferred order has been set, so we also
5324            // back that off to make the alternatives equivalent
5325            if (alwaysAskList.size() > 0) {
5326                for (ResolveInfo i : result) {
5327                    i.preferredOrder = 0;
5328                }
5329                result.addAll(alwaysAskList);
5330                includeBrowser = true;
5331            }
5332
5333            if (includeBrowser) {
5334                // Also add browsers (all of them or only the default one)
5335                if (DEBUG_DOMAIN_VERIFICATION) {
5336                    Slog.v(TAG, "   ...including browsers in candidate set");
5337                }
5338                if ((matchFlags & MATCH_ALL) != 0) {
5339                    result.addAll(matchAllList);
5340                } else {
5341                    // Browser/generic handling case.  If there's a default browser, go straight
5342                    // to that (but only if there is no other higher-priority match).
5343                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5344                    int maxMatchPrio = 0;
5345                    ResolveInfo defaultBrowserMatch = null;
5346                    final int numCandidates = matchAllList.size();
5347                    for (int n = 0; n < numCandidates; n++) {
5348                        ResolveInfo info = matchAllList.get(n);
5349                        // track the highest overall match priority...
5350                        if (info.priority > maxMatchPrio) {
5351                            maxMatchPrio = info.priority;
5352                        }
5353                        // ...and the highest-priority default browser match
5354                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5355                            if (defaultBrowserMatch == null
5356                                    || (defaultBrowserMatch.priority < info.priority)) {
5357                                if (debug) {
5358                                    Slog.v(TAG, "Considering default browser match " + info);
5359                                }
5360                                defaultBrowserMatch = info;
5361                            }
5362                        }
5363                    }
5364                    if (defaultBrowserMatch != null
5365                            && defaultBrowserMatch.priority >= maxMatchPrio
5366                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5367                    {
5368                        if (debug) {
5369                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5370                        }
5371                        result.add(defaultBrowserMatch);
5372                    } else {
5373                        result.addAll(matchAllList);
5374                    }
5375                }
5376
5377                // If there is nothing selected, add all candidates and remove the ones that the user
5378                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5379                if (result.size() == 0) {
5380                    result.addAll(candidates);
5381                    result.removeAll(neverList);
5382                }
5383            }
5384        }
5385        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5386            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5387                    result.size());
5388            for (ResolveInfo info : result) {
5389                Slog.v(TAG, "  + " + info.activityInfo);
5390            }
5391        }
5392        return result;
5393    }
5394
5395    // Returns a packed value as a long:
5396    //
5397    // high 'int'-sized word: link status: undefined/ask/never/always.
5398    // low 'int'-sized word: relative priority among 'always' results.
5399    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5400        long result = ps.getDomainVerificationStatusForUser(userId);
5401        // if none available, get the master status
5402        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5403            if (ps.getIntentFilterVerificationInfo() != null) {
5404                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5405            }
5406        }
5407        return result;
5408    }
5409
5410    private ResolveInfo querySkipCurrentProfileIntents(
5411            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5412            int flags, int sourceUserId) {
5413        if (matchingFilters != null) {
5414            int size = matchingFilters.size();
5415            for (int i = 0; i < size; i ++) {
5416                CrossProfileIntentFilter filter = matchingFilters.get(i);
5417                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5418                    // Checking if there are activities in the target user that can handle the
5419                    // intent.
5420                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5421                            resolvedType, flags, sourceUserId);
5422                    if (resolveInfo != null) {
5423                        return resolveInfo;
5424                    }
5425                }
5426            }
5427        }
5428        return null;
5429    }
5430
5431    // Return matching ResolveInfo in target user if any.
5432    private ResolveInfo queryCrossProfileIntents(
5433            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5434            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5435        if (matchingFilters != null) {
5436            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5437            // match the same intent. For performance reasons, it is better not to
5438            // run queryIntent twice for the same userId
5439            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5440            int size = matchingFilters.size();
5441            for (int i = 0; i < size; i++) {
5442                CrossProfileIntentFilter filter = matchingFilters.get(i);
5443                int targetUserId = filter.getTargetUserId();
5444                boolean skipCurrentProfile =
5445                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5446                boolean skipCurrentProfileIfNoMatchFound =
5447                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5448                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5449                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5450                    // Checking if there are activities in the target user that can handle the
5451                    // intent.
5452                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5453                            resolvedType, flags, sourceUserId);
5454                    if (resolveInfo != null) return resolveInfo;
5455                    alreadyTriedUserIds.put(targetUserId, true);
5456                }
5457            }
5458        }
5459        return null;
5460    }
5461
5462    /**
5463     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5464     * will forward the intent to the filter's target user.
5465     * Otherwise, returns null.
5466     */
5467    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5468            String resolvedType, int flags, int sourceUserId) {
5469        int targetUserId = filter.getTargetUserId();
5470        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5471                resolvedType, flags, targetUserId);
5472        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5473            // If all the matches in the target profile are suspended, return null.
5474            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5475                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5476                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5477                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5478                            targetUserId);
5479                }
5480            }
5481        }
5482        return null;
5483    }
5484
5485    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5486            int sourceUserId, int targetUserId) {
5487        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5488        long ident = Binder.clearCallingIdentity();
5489        boolean targetIsProfile;
5490        try {
5491            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5492        } finally {
5493            Binder.restoreCallingIdentity(ident);
5494        }
5495        String className;
5496        if (targetIsProfile) {
5497            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5498        } else {
5499            className = FORWARD_INTENT_TO_PARENT;
5500        }
5501        ComponentName forwardingActivityComponentName = new ComponentName(
5502                mAndroidApplication.packageName, className);
5503        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5504                sourceUserId);
5505        if (!targetIsProfile) {
5506            forwardingActivityInfo.showUserIcon = targetUserId;
5507            forwardingResolveInfo.noResourceId = true;
5508        }
5509        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5510        forwardingResolveInfo.priority = 0;
5511        forwardingResolveInfo.preferredOrder = 0;
5512        forwardingResolveInfo.match = 0;
5513        forwardingResolveInfo.isDefault = true;
5514        forwardingResolveInfo.filter = filter;
5515        forwardingResolveInfo.targetUserId = targetUserId;
5516        return forwardingResolveInfo;
5517    }
5518
5519    @Override
5520    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5521            Intent[] specifics, String[] specificTypes, Intent intent,
5522            String resolvedType, int flags, int userId) {
5523        if (!sUserManager.exists(userId)) return Collections.emptyList();
5524        flags = updateFlagsForResolve(flags, userId, intent);
5525        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5526                false, "query intent activity options");
5527        final String resultsAction = intent.getAction();
5528
5529        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5530                | PackageManager.GET_RESOLVED_FILTER, userId);
5531
5532        if (DEBUG_INTENT_MATCHING) {
5533            Log.v(TAG, "Query " + intent + ": " + results);
5534        }
5535
5536        int specificsPos = 0;
5537        int N;
5538
5539        // todo: note that the algorithm used here is O(N^2).  This
5540        // isn't a problem in our current environment, but if we start running
5541        // into situations where we have more than 5 or 10 matches then this
5542        // should probably be changed to something smarter...
5543
5544        // First we go through and resolve each of the specific items
5545        // that were supplied, taking care of removing any corresponding
5546        // duplicate items in the generic resolve list.
5547        if (specifics != null) {
5548            for (int i=0; i<specifics.length; i++) {
5549                final Intent sintent = specifics[i];
5550                if (sintent == null) {
5551                    continue;
5552                }
5553
5554                if (DEBUG_INTENT_MATCHING) {
5555                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5556                }
5557
5558                String action = sintent.getAction();
5559                if (resultsAction != null && resultsAction.equals(action)) {
5560                    // If this action was explicitly requested, then don't
5561                    // remove things that have it.
5562                    action = null;
5563                }
5564
5565                ResolveInfo ri = null;
5566                ActivityInfo ai = null;
5567
5568                ComponentName comp = sintent.getComponent();
5569                if (comp == null) {
5570                    ri = resolveIntent(
5571                        sintent,
5572                        specificTypes != null ? specificTypes[i] : null,
5573                            flags, userId);
5574                    if (ri == null) {
5575                        continue;
5576                    }
5577                    if (ri == mResolveInfo) {
5578                        // ACK!  Must do something better with this.
5579                    }
5580                    ai = ri.activityInfo;
5581                    comp = new ComponentName(ai.applicationInfo.packageName,
5582                            ai.name);
5583                } else {
5584                    ai = getActivityInfo(comp, flags, userId);
5585                    if (ai == null) {
5586                        continue;
5587                    }
5588                }
5589
5590                // Look for any generic query activities that are duplicates
5591                // of this specific one, and remove them from the results.
5592                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5593                N = results.size();
5594                int j;
5595                for (j=specificsPos; j<N; j++) {
5596                    ResolveInfo sri = results.get(j);
5597                    if ((sri.activityInfo.name.equals(comp.getClassName())
5598                            && sri.activityInfo.applicationInfo.packageName.equals(
5599                                    comp.getPackageName()))
5600                        || (action != null && sri.filter.matchAction(action))) {
5601                        results.remove(j);
5602                        if (DEBUG_INTENT_MATCHING) Log.v(
5603                            TAG, "Removing duplicate item from " + j
5604                            + " due to specific " + specificsPos);
5605                        if (ri == null) {
5606                            ri = sri;
5607                        }
5608                        j--;
5609                        N--;
5610                    }
5611                }
5612
5613                // Add this specific item to its proper place.
5614                if (ri == null) {
5615                    ri = new ResolveInfo();
5616                    ri.activityInfo = ai;
5617                }
5618                results.add(specificsPos, ri);
5619                ri.specificIndex = i;
5620                specificsPos++;
5621            }
5622        }
5623
5624        // Now we go through the remaining generic results and remove any
5625        // duplicate actions that are found here.
5626        N = results.size();
5627        for (int i=specificsPos; i<N-1; i++) {
5628            final ResolveInfo rii = results.get(i);
5629            if (rii.filter == null) {
5630                continue;
5631            }
5632
5633            // Iterate over all of the actions of this result's intent
5634            // filter...  typically this should be just one.
5635            final Iterator<String> it = rii.filter.actionsIterator();
5636            if (it == null) {
5637                continue;
5638            }
5639            while (it.hasNext()) {
5640                final String action = it.next();
5641                if (resultsAction != null && resultsAction.equals(action)) {
5642                    // If this action was explicitly requested, then don't
5643                    // remove things that have it.
5644                    continue;
5645                }
5646                for (int j=i+1; j<N; j++) {
5647                    final ResolveInfo rij = results.get(j);
5648                    if (rij.filter != null && rij.filter.hasAction(action)) {
5649                        results.remove(j);
5650                        if (DEBUG_INTENT_MATCHING) Log.v(
5651                            TAG, "Removing duplicate item from " + j
5652                            + " due to action " + action + " at " + i);
5653                        j--;
5654                        N--;
5655                    }
5656                }
5657            }
5658
5659            // If the caller didn't request filter information, drop it now
5660            // so we don't have to marshall/unmarshall it.
5661            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5662                rii.filter = null;
5663            }
5664        }
5665
5666        // Filter out the caller activity if so requested.
5667        if (caller != null) {
5668            N = results.size();
5669            for (int i=0; i<N; i++) {
5670                ActivityInfo ainfo = results.get(i).activityInfo;
5671                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5672                        && caller.getClassName().equals(ainfo.name)) {
5673                    results.remove(i);
5674                    break;
5675                }
5676            }
5677        }
5678
5679        // If the caller didn't request filter information,
5680        // drop them now so we don't have to
5681        // marshall/unmarshall it.
5682        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5683            N = results.size();
5684            for (int i=0; i<N; i++) {
5685                results.get(i).filter = null;
5686            }
5687        }
5688
5689        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5690        return results;
5691    }
5692
5693    @Override
5694    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5695            int userId) {
5696        if (!sUserManager.exists(userId)) return Collections.emptyList();
5697        flags = updateFlagsForResolve(flags, userId, intent);
5698        ComponentName comp = intent.getComponent();
5699        if (comp == null) {
5700            if (intent.getSelector() != null) {
5701                intent = intent.getSelector();
5702                comp = intent.getComponent();
5703            }
5704        }
5705        if (comp != null) {
5706            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5707            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5708            if (ai != null) {
5709                ResolveInfo ri = new ResolveInfo();
5710                ri.activityInfo = ai;
5711                list.add(ri);
5712            }
5713            return list;
5714        }
5715
5716        // reader
5717        synchronized (mPackages) {
5718            String pkgName = intent.getPackage();
5719            if (pkgName == null) {
5720                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5721            }
5722            final PackageParser.Package pkg = mPackages.get(pkgName);
5723            if (pkg != null) {
5724                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5725                        userId);
5726            }
5727            return null;
5728        }
5729    }
5730
5731    @Override
5732    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5733        if (!sUserManager.exists(userId)) return null;
5734        flags = updateFlagsForResolve(flags, userId, intent);
5735        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5736        if (query != null) {
5737            if (query.size() >= 1) {
5738                // If there is more than one service with the same priority,
5739                // just arbitrarily pick the first one.
5740                return query.get(0);
5741            }
5742        }
5743        return null;
5744    }
5745
5746    @Override
5747    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5748            int userId) {
5749        if (!sUserManager.exists(userId)) return Collections.emptyList();
5750        flags = updateFlagsForResolve(flags, userId, intent);
5751        ComponentName comp = intent.getComponent();
5752        if (comp == null) {
5753            if (intent.getSelector() != null) {
5754                intent = intent.getSelector();
5755                comp = intent.getComponent();
5756            }
5757        }
5758        if (comp != null) {
5759            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5760            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5761            if (si != null) {
5762                final ResolveInfo ri = new ResolveInfo();
5763                ri.serviceInfo = si;
5764                list.add(ri);
5765            }
5766            return list;
5767        }
5768
5769        // reader
5770        synchronized (mPackages) {
5771            String pkgName = intent.getPackage();
5772            if (pkgName == null) {
5773                return mServices.queryIntent(intent, resolvedType, flags, userId);
5774            }
5775            final PackageParser.Package pkg = mPackages.get(pkgName);
5776            if (pkg != null) {
5777                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5778                        userId);
5779            }
5780            return null;
5781        }
5782    }
5783
5784    @Override
5785    public List<ResolveInfo> queryIntentContentProviders(
5786            Intent intent, String resolvedType, int flags, int userId) {
5787        if (!sUserManager.exists(userId)) return Collections.emptyList();
5788        flags = updateFlagsForResolve(flags, userId, intent);
5789        ComponentName comp = intent.getComponent();
5790        if (comp == null) {
5791            if (intent.getSelector() != null) {
5792                intent = intent.getSelector();
5793                comp = intent.getComponent();
5794            }
5795        }
5796        if (comp != null) {
5797            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5798            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5799            if (pi != null) {
5800                final ResolveInfo ri = new ResolveInfo();
5801                ri.providerInfo = pi;
5802                list.add(ri);
5803            }
5804            return list;
5805        }
5806
5807        // reader
5808        synchronized (mPackages) {
5809            String pkgName = intent.getPackage();
5810            if (pkgName == null) {
5811                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5812            }
5813            final PackageParser.Package pkg = mPackages.get(pkgName);
5814            if (pkg != null) {
5815                return mProviders.queryIntentForPackage(
5816                        intent, resolvedType, flags, pkg.providers, userId);
5817            }
5818            return null;
5819        }
5820    }
5821
5822    @Override
5823    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5824        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5825        flags = updateFlagsForPackage(flags, userId, null);
5826        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5827        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5828
5829        // writer
5830        synchronized (mPackages) {
5831            ArrayList<PackageInfo> list;
5832            if (listUninstalled) {
5833                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5834                for (PackageSetting ps : mSettings.mPackages.values()) {
5835                    PackageInfo pi;
5836                    if (ps.pkg != null) {
5837                        pi = generatePackageInfo(ps.pkg, flags, userId);
5838                    } else {
5839                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5840                    }
5841                    if (pi != null) {
5842                        list.add(pi);
5843                    }
5844                }
5845            } else {
5846                list = new ArrayList<PackageInfo>(mPackages.size());
5847                for (PackageParser.Package p : mPackages.values()) {
5848                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5849                    if (pi != null) {
5850                        list.add(pi);
5851                    }
5852                }
5853            }
5854
5855            return new ParceledListSlice<PackageInfo>(list);
5856        }
5857    }
5858
5859    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5860            String[] permissions, boolean[] tmp, int flags, int userId) {
5861        int numMatch = 0;
5862        final PermissionsState permissionsState = ps.getPermissionsState();
5863        for (int i=0; i<permissions.length; i++) {
5864            final String permission = permissions[i];
5865            if (permissionsState.hasPermission(permission, userId)) {
5866                tmp[i] = true;
5867                numMatch++;
5868            } else {
5869                tmp[i] = false;
5870            }
5871        }
5872        if (numMatch == 0) {
5873            return;
5874        }
5875        PackageInfo pi;
5876        if (ps.pkg != null) {
5877            pi = generatePackageInfo(ps.pkg, flags, userId);
5878        } else {
5879            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5880        }
5881        // The above might return null in cases of uninstalled apps or install-state
5882        // skew across users/profiles.
5883        if (pi != null) {
5884            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5885                if (numMatch == permissions.length) {
5886                    pi.requestedPermissions = permissions;
5887                } else {
5888                    pi.requestedPermissions = new String[numMatch];
5889                    numMatch = 0;
5890                    for (int i=0; i<permissions.length; i++) {
5891                        if (tmp[i]) {
5892                            pi.requestedPermissions[numMatch] = permissions[i];
5893                            numMatch++;
5894                        }
5895                    }
5896                }
5897            }
5898            list.add(pi);
5899        }
5900    }
5901
5902    @Override
5903    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5904            String[] permissions, int flags, int userId) {
5905        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5906        flags = updateFlagsForPackage(flags, userId, permissions);
5907        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5908
5909        // writer
5910        synchronized (mPackages) {
5911            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5912            boolean[] tmpBools = new boolean[permissions.length];
5913            if (listUninstalled) {
5914                for (PackageSetting ps : mSettings.mPackages.values()) {
5915                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5916                }
5917            } else {
5918                for (PackageParser.Package pkg : mPackages.values()) {
5919                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5920                    if (ps != null) {
5921                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5922                                userId);
5923                    }
5924                }
5925            }
5926
5927            return new ParceledListSlice<PackageInfo>(list);
5928        }
5929    }
5930
5931    @Override
5932    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5933        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5934        flags = updateFlagsForApplication(flags, userId, null);
5935        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5936
5937        // writer
5938        synchronized (mPackages) {
5939            ArrayList<ApplicationInfo> list;
5940            if (listUninstalled) {
5941                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5942                for (PackageSetting ps : mSettings.mPackages.values()) {
5943                    ApplicationInfo ai;
5944                    if (ps.pkg != null) {
5945                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5946                                ps.readUserState(userId), userId);
5947                    } else {
5948                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5949                    }
5950                    if (ai != null) {
5951                        list.add(ai);
5952                    }
5953                }
5954            } else {
5955                list = new ArrayList<ApplicationInfo>(mPackages.size());
5956                for (PackageParser.Package p : mPackages.values()) {
5957                    if (p.mExtras != null) {
5958                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5959                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5960                        if (ai != null) {
5961                            list.add(ai);
5962                        }
5963                    }
5964                }
5965            }
5966
5967            return new ParceledListSlice<ApplicationInfo>(list);
5968        }
5969    }
5970
5971    @Override
5972    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5973        if (DISABLE_EPHEMERAL_APPS) {
5974            return null;
5975        }
5976
5977        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5978                "getEphemeralApplications");
5979        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5980                "getEphemeralApplications");
5981        synchronized (mPackages) {
5982            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5983                    .getEphemeralApplicationsLPw(userId);
5984            if (ephemeralApps != null) {
5985                return new ParceledListSlice<>(ephemeralApps);
5986            }
5987        }
5988        return null;
5989    }
5990
5991    @Override
5992    public boolean isEphemeralApplication(String packageName, int userId) {
5993        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5994                "isEphemeral");
5995        if (DISABLE_EPHEMERAL_APPS) {
5996            return false;
5997        }
5998
5999        if (!isCallerSameApp(packageName)) {
6000            return false;
6001        }
6002        synchronized (mPackages) {
6003            PackageParser.Package pkg = mPackages.get(packageName);
6004            if (pkg != null) {
6005                return pkg.applicationInfo.isEphemeralApp();
6006            }
6007        }
6008        return false;
6009    }
6010
6011    @Override
6012    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6013        if (DISABLE_EPHEMERAL_APPS) {
6014            return null;
6015        }
6016
6017        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6018                "getCookie");
6019        if (!isCallerSameApp(packageName)) {
6020            return null;
6021        }
6022        synchronized (mPackages) {
6023            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6024                    packageName, userId);
6025        }
6026    }
6027
6028    @Override
6029    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6030        if (DISABLE_EPHEMERAL_APPS) {
6031            return true;
6032        }
6033
6034        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6035                "setCookie");
6036        if (!isCallerSameApp(packageName)) {
6037            return false;
6038        }
6039        synchronized (mPackages) {
6040            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6041                    packageName, cookie, userId);
6042        }
6043    }
6044
6045    @Override
6046    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6047        if (DISABLE_EPHEMERAL_APPS) {
6048            return null;
6049        }
6050
6051        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6052                "getEphemeralApplicationIcon");
6053        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6054                "getEphemeralApplicationIcon");
6055        synchronized (mPackages) {
6056            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6057                    packageName, userId);
6058        }
6059    }
6060
6061    private boolean isCallerSameApp(String packageName) {
6062        PackageParser.Package pkg = mPackages.get(packageName);
6063        return pkg != null
6064                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6065    }
6066
6067    public List<ApplicationInfo> getPersistentApplications(int flags) {
6068        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6069
6070        // reader
6071        synchronized (mPackages) {
6072            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6073            final int userId = UserHandle.getCallingUserId();
6074            while (i.hasNext()) {
6075                final PackageParser.Package p = i.next();
6076                if (p.applicationInfo != null
6077                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
6078                        && (!mSafeMode || isSystemApp(p))) {
6079                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6080                    if (ps != null) {
6081                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6082                                ps.readUserState(userId), userId);
6083                        if (ai != null) {
6084                            finalList.add(ai);
6085                        }
6086                    }
6087                }
6088            }
6089        }
6090
6091        return finalList;
6092    }
6093
6094    @Override
6095    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6096        if (!sUserManager.exists(userId)) return null;
6097        flags = updateFlagsForComponent(flags, userId, name);
6098        // reader
6099        synchronized (mPackages) {
6100            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6101            PackageSetting ps = provider != null
6102                    ? mSettings.mPackages.get(provider.owner.packageName)
6103                    : null;
6104            return ps != null
6105                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6106                    ? PackageParser.generateProviderInfo(provider, flags,
6107                            ps.readUserState(userId), userId)
6108                    : null;
6109        }
6110    }
6111
6112    /**
6113     * @deprecated
6114     */
6115    @Deprecated
6116    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6117        // reader
6118        synchronized (mPackages) {
6119            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6120                    .entrySet().iterator();
6121            final int userId = UserHandle.getCallingUserId();
6122            while (i.hasNext()) {
6123                Map.Entry<String, PackageParser.Provider> entry = i.next();
6124                PackageParser.Provider p = entry.getValue();
6125                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6126
6127                if (ps != null && p.syncable
6128                        && (!mSafeMode || (p.info.applicationInfo.flags
6129                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6130                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6131                            ps.readUserState(userId), userId);
6132                    if (info != null) {
6133                        outNames.add(entry.getKey());
6134                        outInfo.add(info);
6135                    }
6136                }
6137            }
6138        }
6139    }
6140
6141    @Override
6142    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6143            int uid, int flags) {
6144        final int userId = processName != null ? UserHandle.getUserId(uid)
6145                : UserHandle.getCallingUserId();
6146        if (!sUserManager.exists(userId)) return null;
6147        flags = updateFlagsForComponent(flags, userId, processName);
6148
6149        ArrayList<ProviderInfo> finalList = null;
6150        // reader
6151        synchronized (mPackages) {
6152            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6153            while (i.hasNext()) {
6154                final PackageParser.Provider p = i.next();
6155                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6156                if (ps != null && p.info.authority != null
6157                        && (processName == null
6158                                || (p.info.processName.equals(processName)
6159                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6160                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6161                    if (finalList == null) {
6162                        finalList = new ArrayList<ProviderInfo>(3);
6163                    }
6164                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6165                            ps.readUserState(userId), userId);
6166                    if (info != null) {
6167                        finalList.add(info);
6168                    }
6169                }
6170            }
6171        }
6172
6173        if (finalList != null) {
6174            Collections.sort(finalList, mProviderInitOrderSorter);
6175            return new ParceledListSlice<ProviderInfo>(finalList);
6176        }
6177
6178        return null;
6179    }
6180
6181    @Override
6182    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6183        // reader
6184        synchronized (mPackages) {
6185            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6186            return PackageParser.generateInstrumentationInfo(i, flags);
6187        }
6188    }
6189
6190    @Override
6191    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6192            int flags) {
6193        ArrayList<InstrumentationInfo> finalList =
6194            new ArrayList<InstrumentationInfo>();
6195
6196        // reader
6197        synchronized (mPackages) {
6198            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6199            while (i.hasNext()) {
6200                final PackageParser.Instrumentation p = i.next();
6201                if (targetPackage == null
6202                        || targetPackage.equals(p.info.targetPackage)) {
6203                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6204                            flags);
6205                    if (ii != null) {
6206                        finalList.add(ii);
6207                    }
6208                }
6209            }
6210        }
6211
6212        return finalList;
6213    }
6214
6215    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6216        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6217        if (overlays == null) {
6218            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6219            return;
6220        }
6221        for (PackageParser.Package opkg : overlays.values()) {
6222            // Not much to do if idmap fails: we already logged the error
6223            // and we certainly don't want to abort installation of pkg simply
6224            // because an overlay didn't fit properly. For these reasons,
6225            // ignore the return value of createIdmapForPackagePairLI.
6226            createIdmapForPackagePairLI(pkg, opkg);
6227        }
6228    }
6229
6230    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6231            PackageParser.Package opkg) {
6232        if (!opkg.mTrustedOverlay) {
6233            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6234                    opkg.baseCodePath + ": overlay not trusted");
6235            return false;
6236        }
6237        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6238        if (overlaySet == null) {
6239            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6240                    opkg.baseCodePath + " but target package has no known overlays");
6241            return false;
6242        }
6243        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6244        // TODO: generate idmap for split APKs
6245        try {
6246            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6247        } catch (InstallerException e) {
6248            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6249                    + opkg.baseCodePath);
6250            return false;
6251        }
6252        PackageParser.Package[] overlayArray =
6253            overlaySet.values().toArray(new PackageParser.Package[0]);
6254        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6255            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6256                return p1.mOverlayPriority - p2.mOverlayPriority;
6257            }
6258        };
6259        Arrays.sort(overlayArray, cmp);
6260
6261        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6262        int i = 0;
6263        for (PackageParser.Package p : overlayArray) {
6264            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6265        }
6266        return true;
6267    }
6268
6269    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6270        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6271        try {
6272            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6273        } finally {
6274            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6275        }
6276    }
6277
6278    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6279        final File[] files = dir.listFiles();
6280        if (ArrayUtils.isEmpty(files)) {
6281            Log.d(TAG, "No files in app dir " + dir);
6282            return;
6283        }
6284
6285        if (DEBUG_PACKAGE_SCANNING) {
6286            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6287                    + " flags=0x" + Integer.toHexString(parseFlags));
6288        }
6289
6290        for (File file : files) {
6291            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6292                    && !PackageInstallerService.isStageName(file.getName());
6293            if (!isPackage) {
6294                // Ignore entries which are not packages
6295                continue;
6296            }
6297            try {
6298                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6299                        scanFlags, currentTime, null);
6300            } catch (PackageManagerException e) {
6301                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6302
6303                // Delete invalid userdata apps
6304                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6305                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6306                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6307                    removeCodePathLI(file);
6308                }
6309            }
6310        }
6311    }
6312
6313    private static File getSettingsProblemFile() {
6314        File dataDir = Environment.getDataDirectory();
6315        File systemDir = new File(dataDir, "system");
6316        File fname = new File(systemDir, "uiderrors.txt");
6317        return fname;
6318    }
6319
6320    static void reportSettingsProblem(int priority, String msg) {
6321        logCriticalInfo(priority, msg);
6322    }
6323
6324    static void logCriticalInfo(int priority, String msg) {
6325        Slog.println(priority, TAG, msg);
6326        EventLogTags.writePmCriticalInfo(msg);
6327        try {
6328            File fname = getSettingsProblemFile();
6329            FileOutputStream out = new FileOutputStream(fname, true);
6330            PrintWriter pw = new FastPrintWriter(out);
6331            SimpleDateFormat formatter = new SimpleDateFormat();
6332            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6333            pw.println(dateString + ": " + msg);
6334            pw.close();
6335            FileUtils.setPermissions(
6336                    fname.toString(),
6337                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6338                    -1, -1);
6339        } catch (java.io.IOException e) {
6340        }
6341    }
6342
6343    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6344            int parseFlags) throws PackageManagerException {
6345        if (ps != null
6346                && ps.codePath.equals(srcFile)
6347                && ps.timeStamp == srcFile.lastModified()
6348                && !isCompatSignatureUpdateNeeded(pkg)
6349                && !isRecoverSignatureUpdateNeeded(pkg)) {
6350            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6351            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6352            ArraySet<PublicKey> signingKs;
6353            synchronized (mPackages) {
6354                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6355            }
6356            if (ps.signatures.mSignatures != null
6357                    && ps.signatures.mSignatures.length != 0
6358                    && signingKs != null) {
6359                // Optimization: reuse the existing cached certificates
6360                // if the package appears to be unchanged.
6361                pkg.mSignatures = ps.signatures.mSignatures;
6362                pkg.mSigningKeys = signingKs;
6363                return;
6364            }
6365
6366            Slog.w(TAG, "PackageSetting for " + ps.name
6367                    + " is missing signatures.  Collecting certs again to recover them.");
6368        } else {
6369            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6370        }
6371
6372        try {
6373            PackageParser.collectCertificates(pkg, parseFlags);
6374        } catch (PackageParserException e) {
6375            throw PackageManagerException.from(e);
6376        }
6377    }
6378
6379    /**
6380     *  Traces a package scan.
6381     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6382     */
6383    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6384            long currentTime, UserHandle user) throws PackageManagerException {
6385        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6386        try {
6387            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6388        } finally {
6389            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6390        }
6391    }
6392
6393    /**
6394     *  Scans a package and returns the newly parsed package.
6395     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6396     */
6397    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6398            long currentTime, UserHandle user) throws PackageManagerException {
6399        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6400        parseFlags |= mDefParseFlags;
6401        PackageParser pp = new PackageParser();
6402        pp.setSeparateProcesses(mSeparateProcesses);
6403        pp.setOnlyCoreApps(mOnlyCore);
6404        pp.setDisplayMetrics(mMetrics);
6405
6406        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6407            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6408        }
6409
6410        final PackageParser.Package pkg;
6411        try {
6412            pkg = pp.parsePackage(scanFile, parseFlags);
6413        } catch (PackageParserException e) {
6414            throw PackageManagerException.from(e);
6415        }
6416
6417        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6418    }
6419
6420    /**
6421     *  Scans a package and returns the newly parsed package.
6422     *  @throws PackageManagerException on a parse error.
6423     */
6424    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6425            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6426            throws PackageManagerException {
6427        // If the package has children and this is the first dive in the function
6428        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6429        // packages (parent and children) would be successfully scanned before the
6430        // actual scan since scanning mutates internal state and we want to atomically
6431        // install the package and its children.
6432        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6433            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6434                scanFlags |= SCAN_CHECK_ONLY;
6435            }
6436        } else {
6437            scanFlags &= ~SCAN_CHECK_ONLY;
6438        }
6439
6440        // Scan the parent
6441        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6442                scanFlags, currentTime, user);
6443
6444        // Scan the children
6445        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6446        for (int i = 0; i < childCount; i++) {
6447            PackageParser.Package childPackage = pkg.childPackages.get(i);
6448            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6449                    currentTime, user);
6450        }
6451
6452
6453        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6454            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6455        }
6456
6457        return scannedPkg;
6458    }
6459
6460    /**
6461     *  Scans a package and returns the newly parsed package.
6462     *  @throws PackageManagerException on a parse error.
6463     */
6464    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6465            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6466            throws PackageManagerException {
6467        PackageSetting ps = null;
6468        PackageSetting updatedPkg;
6469        // reader
6470        synchronized (mPackages) {
6471            // Look to see if we already know about this package.
6472            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6473            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6474                // This package has been renamed to its original name.  Let's
6475                // use that.
6476                ps = mSettings.peekPackageLPr(oldName);
6477            }
6478            // If there was no original package, see one for the real package name.
6479            if (ps == null) {
6480                ps = mSettings.peekPackageLPr(pkg.packageName);
6481            }
6482            // Check to see if this package could be hiding/updating a system
6483            // package.  Must look for it either under the original or real
6484            // package name depending on our state.
6485            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6486            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6487
6488            // If this is a package we don't know about on the system partition, we
6489            // may need to remove disabled child packages on the system partition
6490            // or may need to not add child packages if the parent apk is updated
6491            // on the data partition and no longer defines this child package.
6492            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6493                // If this is a parent package for an updated system app and this system
6494                // app got an OTA update which no longer defines some of the child packages
6495                // we have to prune them from the disabled system packages.
6496                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6497                if (disabledPs != null) {
6498                    final int scannedChildCount = (pkg.childPackages != null)
6499                            ? pkg.childPackages.size() : 0;
6500                    final int disabledChildCount = disabledPs.childPackageNames != null
6501                            ? disabledPs.childPackageNames.size() : 0;
6502                    for (int i = 0; i < disabledChildCount; i++) {
6503                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6504                        boolean disabledPackageAvailable = false;
6505                        for (int j = 0; j < scannedChildCount; j++) {
6506                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6507                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6508                                disabledPackageAvailable = true;
6509                                break;
6510                            }
6511                         }
6512                         if (!disabledPackageAvailable) {
6513                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6514                         }
6515                    }
6516                }
6517            }
6518        }
6519
6520        boolean updatedPkgBetter = false;
6521        // First check if this is a system package that may involve an update
6522        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6523            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6524            // it needs to drop FLAG_PRIVILEGED.
6525            if (locationIsPrivileged(scanFile)) {
6526                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6527            } else {
6528                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6529            }
6530
6531            if (ps != null && !ps.codePath.equals(scanFile)) {
6532                // The path has changed from what was last scanned...  check the
6533                // version of the new path against what we have stored to determine
6534                // what to do.
6535                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6536                if (pkg.mVersionCode <= ps.versionCode) {
6537                    // The system package has been updated and the code path does not match
6538                    // Ignore entry. Skip it.
6539                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6540                            + " ignored: updated version " + ps.versionCode
6541                            + " better than this " + pkg.mVersionCode);
6542                    if (!updatedPkg.codePath.equals(scanFile)) {
6543                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6544                                + ps.name + " changing from " + updatedPkg.codePathString
6545                                + " to " + scanFile);
6546                        updatedPkg.codePath = scanFile;
6547                        updatedPkg.codePathString = scanFile.toString();
6548                        updatedPkg.resourcePath = scanFile;
6549                        updatedPkg.resourcePathString = scanFile.toString();
6550                    }
6551                    updatedPkg.pkg = pkg;
6552                    updatedPkg.versionCode = pkg.mVersionCode;
6553
6554                    // Update the disabled system child packages to point to the package too.
6555                    final int childCount = updatedPkg.childPackageNames != null
6556                            ? updatedPkg.childPackageNames.size() : 0;
6557                    for (int i = 0; i < childCount; i++) {
6558                        String childPackageName = updatedPkg.childPackageNames.get(i);
6559                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6560                                childPackageName);
6561                        if (updatedChildPkg != null) {
6562                            updatedChildPkg.pkg = pkg;
6563                            updatedChildPkg.versionCode = pkg.mVersionCode;
6564                        }
6565                    }
6566
6567                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6568                            + scanFile + " ignored: updated version " + ps.versionCode
6569                            + " better than this " + pkg.mVersionCode);
6570                } else {
6571                    // The current app on the system partition is better than
6572                    // what we have updated to on the data partition; switch
6573                    // back to the system partition version.
6574                    // At this point, its safely assumed that package installation for
6575                    // apps in system partition will go through. If not there won't be a working
6576                    // version of the app
6577                    // writer
6578                    synchronized (mPackages) {
6579                        // Just remove the loaded entries from package lists.
6580                        mPackages.remove(ps.name);
6581                    }
6582
6583                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6584                            + " reverting from " + ps.codePathString
6585                            + ": new version " + pkg.mVersionCode
6586                            + " better than installed " + ps.versionCode);
6587
6588                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6589                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6590                    synchronized (mInstallLock) {
6591                        args.cleanUpResourcesLI();
6592                    }
6593                    synchronized (mPackages) {
6594                        mSettings.enableSystemPackageLPw(ps.name);
6595                    }
6596                    updatedPkgBetter = true;
6597                }
6598            }
6599        }
6600
6601        if (updatedPkg != null) {
6602            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6603            // initially
6604            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6605
6606            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6607            // flag set initially
6608            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6609                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6610            }
6611        }
6612
6613        // Verify certificates against what was last scanned
6614        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6615
6616        /*
6617         * A new system app appeared, but we already had a non-system one of the
6618         * same name installed earlier.
6619         */
6620        boolean shouldHideSystemApp = false;
6621        if (updatedPkg == null && ps != null
6622                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6623            /*
6624             * Check to make sure the signatures match first. If they don't,
6625             * wipe the installed application and its data.
6626             */
6627            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6628                    != PackageManager.SIGNATURE_MATCH) {
6629                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6630                        + " signatures don't match existing userdata copy; removing");
6631                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6632                ps = null;
6633            } else {
6634                /*
6635                 * If the newly-added system app is an older version than the
6636                 * already installed version, hide it. It will be scanned later
6637                 * and re-added like an update.
6638                 */
6639                if (pkg.mVersionCode <= ps.versionCode) {
6640                    shouldHideSystemApp = true;
6641                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6642                            + " but new version " + pkg.mVersionCode + " better than installed "
6643                            + ps.versionCode + "; hiding system");
6644                } else {
6645                    /*
6646                     * The newly found system app is a newer version that the
6647                     * one previously installed. Simply remove the
6648                     * already-installed application and replace it with our own
6649                     * while keeping the application data.
6650                     */
6651                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6652                            + " reverting from " + ps.codePathString + ": new version "
6653                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6654                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6655                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6656                    synchronized (mInstallLock) {
6657                        args.cleanUpResourcesLI();
6658                    }
6659                }
6660            }
6661        }
6662
6663        // The apk is forward locked (not public) if its code and resources
6664        // are kept in different files. (except for app in either system or
6665        // vendor path).
6666        // TODO grab this value from PackageSettings
6667        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6668            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6669                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6670            }
6671        }
6672
6673        // TODO: extend to support forward-locked splits
6674        String resourcePath = null;
6675        String baseResourcePath = null;
6676        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6677            if (ps != null && ps.resourcePathString != null) {
6678                resourcePath = ps.resourcePathString;
6679                baseResourcePath = ps.resourcePathString;
6680            } else {
6681                // Should not happen at all. Just log an error.
6682                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6683            }
6684        } else {
6685            resourcePath = pkg.codePath;
6686            baseResourcePath = pkg.baseCodePath;
6687        }
6688
6689        // Set application objects path explicitly.
6690        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6691        pkg.setApplicationInfoCodePath(pkg.codePath);
6692        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6693        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6694        pkg.setApplicationInfoResourcePath(resourcePath);
6695        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6696        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6697
6698        // Note that we invoke the following method only if we are about to unpack an application
6699        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6700                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6701
6702        /*
6703         * If the system app should be overridden by a previously installed
6704         * data, hide the system app now and let the /data/app scan pick it up
6705         * again.
6706         */
6707        if (shouldHideSystemApp) {
6708            synchronized (mPackages) {
6709                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6710            }
6711        }
6712
6713        return scannedPkg;
6714    }
6715
6716    private static String fixProcessName(String defProcessName,
6717            String processName, int uid) {
6718        if (processName == null) {
6719            return defProcessName;
6720        }
6721        return processName;
6722    }
6723
6724    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6725            throws PackageManagerException {
6726        if (pkgSetting.signatures.mSignatures != null) {
6727            // Already existing package. Make sure signatures match
6728            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6729                    == PackageManager.SIGNATURE_MATCH;
6730            if (!match) {
6731                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6732                        == PackageManager.SIGNATURE_MATCH;
6733            }
6734            if (!match) {
6735                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6736                        == PackageManager.SIGNATURE_MATCH;
6737            }
6738            if (!match) {
6739                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6740                        + pkg.packageName + " signatures do not match the "
6741                        + "previously installed version; ignoring!");
6742            }
6743        }
6744
6745        // Check for shared user signatures
6746        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6747            // Already existing package. Make sure signatures match
6748            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6749                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6750            if (!match) {
6751                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6752                        == PackageManager.SIGNATURE_MATCH;
6753            }
6754            if (!match) {
6755                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6756                        == PackageManager.SIGNATURE_MATCH;
6757            }
6758            if (!match) {
6759                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6760                        "Package " + pkg.packageName
6761                        + " has no signatures that match those in shared user "
6762                        + pkgSetting.sharedUser.name + "; ignoring!");
6763            }
6764        }
6765    }
6766
6767    /**
6768     * Enforces that only the system UID or root's UID can call a method exposed
6769     * via Binder.
6770     *
6771     * @param message used as message if SecurityException is thrown
6772     * @throws SecurityException if the caller is not system or root
6773     */
6774    private static final void enforceSystemOrRoot(String message) {
6775        final int uid = Binder.getCallingUid();
6776        if (uid != Process.SYSTEM_UID && uid != 0) {
6777            throw new SecurityException(message);
6778        }
6779    }
6780
6781    @Override
6782    public void performFstrimIfNeeded() {
6783        enforceSystemOrRoot("Only the system can request fstrim");
6784
6785        // Before everything else, see whether we need to fstrim.
6786        try {
6787            IMountService ms = PackageHelper.getMountService();
6788            if (ms != null) {
6789                final boolean isUpgrade = isUpgrade();
6790                boolean doTrim = isUpgrade;
6791                if (doTrim) {
6792                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6793                } else {
6794                    final long interval = android.provider.Settings.Global.getLong(
6795                            mContext.getContentResolver(),
6796                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6797                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6798                    if (interval > 0) {
6799                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6800                        if (timeSinceLast > interval) {
6801                            doTrim = true;
6802                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6803                                    + "; running immediately");
6804                        }
6805                    }
6806                }
6807                if (doTrim) {
6808                    if (!isFirstBoot()) {
6809                        try {
6810                            ActivityManagerNative.getDefault().showBootMessage(
6811                                    mContext.getResources().getString(
6812                                            R.string.android_upgrading_fstrim), true);
6813                        } catch (RemoteException e) {
6814                        }
6815                    }
6816                    ms.runMaintenance();
6817                }
6818            } else {
6819                Slog.e(TAG, "Mount service unavailable!");
6820            }
6821        } catch (RemoteException e) {
6822            // Can't happen; MountService is local
6823        }
6824    }
6825
6826    @Override
6827    public void extractPackagesIfNeeded() {
6828        enforceSystemOrRoot("Only the system can request package extraction");
6829
6830        // Extract pacakges only if profile-guided compilation is enabled because
6831        // otherwise BackgroundDexOptService will not dexopt them later.
6832        if (mUseJitProfiles) {
6833            List<PackageParser.Package> pkgs;
6834            synchronized (mPackages) {
6835                pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6836            }
6837            for (PackageParser.Package pkg : pkgs) {
6838                if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6839                    performDexOpt(pkg.packageName, null /* instructionSet */,
6840                             false /* useProfiles */, true /* extractOnly */, false /* force */);
6841                }
6842            }
6843        }
6844    }
6845
6846    @Override
6847    public void notifyPackageUse(String packageName) {
6848        synchronized (mPackages) {
6849            PackageParser.Package p = mPackages.get(packageName);
6850            if (p == null) {
6851                return;
6852            }
6853            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6854        }
6855    }
6856
6857    // TODO: this is not used nor needed. Delete it.
6858    @Override
6859    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6860        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6861                false /* extractOnly */, false /* force */);
6862    }
6863
6864    @Override
6865    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6866            boolean extractOnly, boolean force) {
6867        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6868    }
6869
6870    private boolean performDexOptTraced(String packageName, String instructionSet,
6871                boolean useProfiles, boolean extractOnly, boolean force) {
6872        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6873        try {
6874            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6875                    force);
6876        } finally {
6877            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6878        }
6879    }
6880
6881    private boolean performDexOptInternal(String packageName, String instructionSet,
6882                boolean useProfiles, boolean extractOnly, boolean force) {
6883        PackageParser.Package p;
6884        final String targetInstructionSet;
6885        synchronized (mPackages) {
6886            p = mPackages.get(packageName);
6887            if (p == null) {
6888                return false;
6889            }
6890            mPackageUsage.write(false);
6891
6892            targetInstructionSet = instructionSet != null ? instructionSet :
6893                    getPrimaryInstructionSet(p.applicationInfo);
6894            if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6895                // Skip only if we do not use profiles since they might trigger a recompilation.
6896                return false;
6897            }
6898        }
6899        long callingId = Binder.clearCallingIdentity();
6900        try {
6901            synchronized (mInstallLock) {
6902                final String[] instructionSets = new String[] { targetInstructionSet };
6903                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6904                        useProfiles, extractOnly, force);
6905                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6906            }
6907        } finally {
6908            Binder.restoreCallingIdentity(callingId);
6909        }
6910    }
6911
6912    public ArraySet<String> getOptimizablePackages() {
6913        ArraySet<String> pkgs = new ArraySet<String>();
6914        synchronized (mPackages) {
6915            for (PackageParser.Package p : mPackages.values()) {
6916                if (PackageDexOptimizer.canOptimizePackage(p)) {
6917                    pkgs.add(p.packageName);
6918                }
6919            }
6920        }
6921        return pkgs;
6922    }
6923
6924    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6925            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6926        // Select the dex optimizer based on the force parameter.
6927        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6928        //       allocate an object here.
6929        PackageDexOptimizer pdo = force
6930                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6931                : mPackageDexOptimizer;
6932
6933        // Optimize all dependencies first. Note: we ignore the return value and march on
6934        // on errors.
6935        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6936        if (!deps.isEmpty()) {
6937            for (PackageParser.Package depPackage : deps) {
6938                // TODO: Analyze and investigate if we (should) profile libraries.
6939                // Currently this will do a full compilation of the library.
6940                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6941                        false /* extractOnly */);
6942            }
6943        }
6944
6945        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6946    }
6947
6948    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6949        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6950            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6951            Set<String> collectedNames = new HashSet<>();
6952            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6953
6954            retValue.remove(p);
6955
6956            return retValue;
6957        } else {
6958            return Collections.emptyList();
6959        }
6960    }
6961
6962    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6963            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6964        if (!collectedNames.contains(p.packageName)) {
6965            collectedNames.add(p.packageName);
6966            collected.add(p);
6967
6968            if (p.usesLibraries != null) {
6969                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6970            }
6971            if (p.usesOptionalLibraries != null) {
6972                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6973                        collectedNames);
6974            }
6975        }
6976    }
6977
6978    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
6979            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6980        for (String libName : libs) {
6981            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
6982            if (libPkg != null) {
6983                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
6984            }
6985        }
6986    }
6987
6988    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
6989        synchronized (mPackages) {
6990            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
6991            if (lib != null && lib.apk != null) {
6992                return mPackages.get(lib.apk);
6993            }
6994        }
6995        return null;
6996    }
6997
6998    public void shutdown() {
6999        mPackageUsage.write(true);
7000    }
7001
7002    @Override
7003    public void forceDexOpt(String packageName) {
7004        enforceSystemOrRoot("forceDexOpt");
7005
7006        PackageParser.Package pkg;
7007        synchronized (mPackages) {
7008            pkg = mPackages.get(packageName);
7009            if (pkg == null) {
7010                throw new IllegalArgumentException("Unknown package: " + packageName);
7011            }
7012        }
7013
7014        synchronized (mInstallLock) {
7015            final String[] instructionSets = new String[] {
7016                    getPrimaryInstructionSet(pkg.applicationInfo) };
7017
7018            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7019
7020            // Whoever is calling forceDexOpt wants a fully compiled package.
7021            // Don't use profiles since that may cause compilation to be skipped.
7022            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7023                    false /* useProfiles */, false /* extractOnly */, true /* force */);
7024
7025            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7026            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7027                throw new IllegalStateException("Failed to dexopt: " + res);
7028            }
7029        }
7030    }
7031
7032    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7033        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7034            Slog.w(TAG, "Unable to update from " + oldPkg.name
7035                    + " to " + newPkg.packageName
7036                    + ": old package not in system partition");
7037            return false;
7038        } else if (mPackages.get(oldPkg.name) != null) {
7039            Slog.w(TAG, "Unable to update from " + oldPkg.name
7040                    + " to " + newPkg.packageName
7041                    + ": old package still exists");
7042            return false;
7043        }
7044        return true;
7045    }
7046
7047    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7048        // TODO: triage flags as part of 26466827
7049        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7050
7051        boolean res = true;
7052        final int[] users = sUserManager.getUserIds();
7053        for (int user : users) {
7054            try {
7055                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7056            } catch (InstallerException e) {
7057                Slog.w(TAG, "Failed to delete data directory", e);
7058                res = false;
7059            }
7060        }
7061        return res;
7062    }
7063
7064    void removeCodePathLI(File codePath) {
7065        if (codePath.isDirectory()) {
7066            try {
7067                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7068            } catch (InstallerException e) {
7069                Slog.w(TAG, "Failed to remove code path", e);
7070            }
7071        } else {
7072            codePath.delete();
7073        }
7074    }
7075
7076    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7077        try {
7078            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7079        } catch (InstallerException e) {
7080            Slog.w(TAG, "Failed to destroy app data", e);
7081        }
7082    }
7083
7084    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7085            int appId, String seinfo) {
7086        try {
7087            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7088        } catch (InstallerException e) {
7089            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7090        }
7091    }
7092
7093    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7094        final PackageParser.Package pkg;
7095        synchronized (mPackages) {
7096            pkg = mPackages.get(packageName);
7097        }
7098        if (pkg == null) {
7099            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7100            return;
7101        }
7102        deleteCodeCacheDirsLI(pkg);
7103    }
7104
7105    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7106        // TODO: triage flags as part of 26466827
7107        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7108
7109        int[] users = sUserManager.getUserIds();
7110        int res = 0;
7111        for (int user : users) {
7112            // Remove the parent code cache
7113            try {
7114                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7115                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7116            } catch (InstallerException e) {
7117                Slog.w(TAG, "Failed to delete code cache directory", e);
7118            }
7119            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7120            for (int i = 0; i < childCount; i++) {
7121                PackageParser.Package childPkg = pkg.childPackages.get(i);
7122                // Remove the child code cache
7123                try {
7124                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7125                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7126                } catch (InstallerException e) {
7127                    Slog.w(TAG, "Failed to delete code cache directory", e);
7128                }
7129            }
7130        }
7131    }
7132
7133    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7134            long lastUpdateTime) {
7135        // Set parent install/update time
7136        PackageSetting ps = (PackageSetting) pkg.mExtras;
7137        if (ps != null) {
7138            ps.firstInstallTime = firstInstallTime;
7139            ps.lastUpdateTime = lastUpdateTime;
7140        }
7141        // Set children install/update time
7142        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7143        for (int i = 0; i < childCount; i++) {
7144            PackageParser.Package childPkg = pkg.childPackages.get(i);
7145            ps = (PackageSetting) childPkg.mExtras;
7146            if (ps != null) {
7147                ps.firstInstallTime = firstInstallTime;
7148                ps.lastUpdateTime = lastUpdateTime;
7149            }
7150        }
7151    }
7152
7153    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7154            PackageParser.Package changingLib) {
7155        if (file.path != null) {
7156            usesLibraryFiles.add(file.path);
7157            return;
7158        }
7159        PackageParser.Package p = mPackages.get(file.apk);
7160        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7161            // If we are doing this while in the middle of updating a library apk,
7162            // then we need to make sure to use that new apk for determining the
7163            // dependencies here.  (We haven't yet finished committing the new apk
7164            // to the package manager state.)
7165            if (p == null || p.packageName.equals(changingLib.packageName)) {
7166                p = changingLib;
7167            }
7168        }
7169        if (p != null) {
7170            usesLibraryFiles.addAll(p.getAllCodePaths());
7171        }
7172    }
7173
7174    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7175            PackageParser.Package changingLib) throws PackageManagerException {
7176        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7177            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7178            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7179            for (int i=0; i<N; i++) {
7180                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7181                if (file == null) {
7182                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7183                            "Package " + pkg.packageName + " requires unavailable shared library "
7184                            + pkg.usesLibraries.get(i) + "; failing!");
7185                }
7186                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7187            }
7188            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7189            for (int i=0; i<N; i++) {
7190                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7191                if (file == null) {
7192                    Slog.w(TAG, "Package " + pkg.packageName
7193                            + " desires unavailable shared library "
7194                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7195                } else {
7196                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7197                }
7198            }
7199            N = usesLibraryFiles.size();
7200            if (N > 0) {
7201                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7202            } else {
7203                pkg.usesLibraryFiles = null;
7204            }
7205        }
7206    }
7207
7208    private static boolean hasString(List<String> list, List<String> which) {
7209        if (list == null) {
7210            return false;
7211        }
7212        for (int i=list.size()-1; i>=0; i--) {
7213            for (int j=which.size()-1; j>=0; j--) {
7214                if (which.get(j).equals(list.get(i))) {
7215                    return true;
7216                }
7217            }
7218        }
7219        return false;
7220    }
7221
7222    private void updateAllSharedLibrariesLPw() {
7223        for (PackageParser.Package pkg : mPackages.values()) {
7224            try {
7225                updateSharedLibrariesLPw(pkg, null);
7226            } catch (PackageManagerException e) {
7227                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7228            }
7229        }
7230    }
7231
7232    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7233            PackageParser.Package changingPkg) {
7234        ArrayList<PackageParser.Package> res = null;
7235        for (PackageParser.Package pkg : mPackages.values()) {
7236            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7237                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7238                if (res == null) {
7239                    res = new ArrayList<PackageParser.Package>();
7240                }
7241                res.add(pkg);
7242                try {
7243                    updateSharedLibrariesLPw(pkg, changingPkg);
7244                } catch (PackageManagerException e) {
7245                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7246                }
7247            }
7248        }
7249        return res;
7250    }
7251
7252    /**
7253     * Derive the value of the {@code cpuAbiOverride} based on the provided
7254     * value and an optional stored value from the package settings.
7255     */
7256    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7257        String cpuAbiOverride = null;
7258
7259        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7260            cpuAbiOverride = null;
7261        } else if (abiOverride != null) {
7262            cpuAbiOverride = abiOverride;
7263        } else if (settings != null) {
7264            cpuAbiOverride = settings.cpuAbiOverrideString;
7265        }
7266
7267        return cpuAbiOverride;
7268    }
7269
7270    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7271            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7272        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7273        // If the package has children and this is the first dive in the function
7274        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7275        // whether all packages (parent and children) would be successfully scanned
7276        // before the actual scan since scanning mutates internal state and we want
7277        // to atomically install the package and its children.
7278        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7279            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7280                scanFlags |= SCAN_CHECK_ONLY;
7281            }
7282        } else {
7283            scanFlags &= ~SCAN_CHECK_ONLY;
7284        }
7285
7286        final PackageParser.Package scannedPkg;
7287        try {
7288            // Scan the parent
7289            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7290            // Scan the children
7291            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7292            for (int i = 0; i < childCount; i++) {
7293                PackageParser.Package childPkg = pkg.childPackages.get(i);
7294                scanPackageLI(childPkg, parseFlags,
7295                        scanFlags, currentTime, user);
7296            }
7297        } finally {
7298            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7299        }
7300
7301        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7302            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7303        }
7304
7305        return scannedPkg;
7306    }
7307
7308    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7309            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7310        boolean success = false;
7311        try {
7312            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7313                    currentTime, user);
7314            success = true;
7315            return res;
7316        } finally {
7317            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7318                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7319            }
7320        }
7321    }
7322
7323    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7324            int scanFlags, long currentTime, UserHandle user)
7325            throws PackageManagerException {
7326        final File scanFile = new File(pkg.codePath);
7327        if (pkg.applicationInfo.getCodePath() == null ||
7328                pkg.applicationInfo.getResourcePath() == null) {
7329            // Bail out. The resource and code paths haven't been set.
7330            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7331                    "Code and resource paths haven't been set correctly");
7332        }
7333
7334        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7335            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7336        } else {
7337            // Only allow system apps to be flagged as core apps.
7338            pkg.coreApp = false;
7339        }
7340
7341        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7342            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7343        }
7344
7345        if (mCustomResolverComponentName != null &&
7346                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7347            setUpCustomResolverActivity(pkg);
7348        }
7349
7350        if (pkg.packageName.equals("android")) {
7351            synchronized (mPackages) {
7352                if (mAndroidApplication != null) {
7353                    Slog.w(TAG, "*************************************************");
7354                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7355                    Slog.w(TAG, " file=" + scanFile);
7356                    Slog.w(TAG, "*************************************************");
7357                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7358                            "Core android package being redefined.  Skipping.");
7359                }
7360
7361                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7362                    // Set up information for our fall-back user intent resolution activity.
7363                    mPlatformPackage = pkg;
7364                    pkg.mVersionCode = mSdkVersion;
7365                    mAndroidApplication = pkg.applicationInfo;
7366
7367                    if (!mResolverReplaced) {
7368                        mResolveActivity.applicationInfo = mAndroidApplication;
7369                        mResolveActivity.name = ResolverActivity.class.getName();
7370                        mResolveActivity.packageName = mAndroidApplication.packageName;
7371                        mResolveActivity.processName = "system:ui";
7372                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7373                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7374                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7375                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7376                        mResolveActivity.exported = true;
7377                        mResolveActivity.enabled = true;
7378                        mResolveInfo.activityInfo = mResolveActivity;
7379                        mResolveInfo.priority = 0;
7380                        mResolveInfo.preferredOrder = 0;
7381                        mResolveInfo.match = 0;
7382                        mResolveComponentName = new ComponentName(
7383                                mAndroidApplication.packageName, mResolveActivity.name);
7384                    }
7385                }
7386            }
7387        }
7388
7389        if (DEBUG_PACKAGE_SCANNING) {
7390            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7391                Log.d(TAG, "Scanning package " + pkg.packageName);
7392        }
7393
7394        synchronized (mPackages) {
7395            if (mPackages.containsKey(pkg.packageName)
7396                    || mSharedLibraries.containsKey(pkg.packageName)) {
7397                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7398                        "Application package " + pkg.packageName
7399                                + " already installed.  Skipping duplicate.");
7400            }
7401
7402            // If we're only installing presumed-existing packages, require that the
7403            // scanned APK is both already known and at the path previously established
7404            // for it.  Previously unknown packages we pick up normally, but if we have an
7405            // a priori expectation about this package's install presence, enforce it.
7406            // With a singular exception for new system packages. When an OTA contains
7407            // a new system package, we allow the codepath to change from a system location
7408            // to the user-installed location. If we don't allow this change, any newer,
7409            // user-installed version of the application will be ignored.
7410            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7411                if (mExpectingBetter.containsKey(pkg.packageName)) {
7412                    logCriticalInfo(Log.WARN,
7413                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7414                } else {
7415                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7416                    if (known != null) {
7417                        if (DEBUG_PACKAGE_SCANNING) {
7418                            Log.d(TAG, "Examining " + pkg.codePath
7419                                    + " and requiring known paths " + known.codePathString
7420                                    + " & " + known.resourcePathString);
7421                        }
7422                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7423                                || !pkg.applicationInfo.getResourcePath().equals(
7424                                known.resourcePathString)) {
7425                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7426                                    "Application package " + pkg.packageName
7427                                            + " found at " + pkg.applicationInfo.getCodePath()
7428                                            + " but expected at " + known.codePathString
7429                                            + "; ignoring.");
7430                        }
7431                    }
7432                }
7433            }
7434        }
7435
7436        // Initialize package source and resource directories
7437        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7438        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7439
7440        SharedUserSetting suid = null;
7441        PackageSetting pkgSetting = null;
7442
7443        if (!isSystemApp(pkg)) {
7444            // Only system apps can use these features.
7445            pkg.mOriginalPackages = null;
7446            pkg.mRealPackage = null;
7447            pkg.mAdoptPermissions = null;
7448        }
7449
7450        // Getting the package setting may have a side-effect, so if we
7451        // are only checking if scan would succeed, stash a copy of the
7452        // old setting to restore at the end.
7453        PackageSetting nonMutatedPs = null;
7454
7455        // writer
7456        synchronized (mPackages) {
7457            if (pkg.mSharedUserId != null) {
7458                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7459                if (suid == null) {
7460                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7461                            "Creating application package " + pkg.packageName
7462                            + " for shared user failed");
7463                }
7464                if (DEBUG_PACKAGE_SCANNING) {
7465                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7466                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7467                                + "): packages=" + suid.packages);
7468                }
7469            }
7470
7471            // Check if we are renaming from an original package name.
7472            PackageSetting origPackage = null;
7473            String realName = null;
7474            if (pkg.mOriginalPackages != null) {
7475                // This package may need to be renamed to a previously
7476                // installed name.  Let's check on that...
7477                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7478                if (pkg.mOriginalPackages.contains(renamed)) {
7479                    // This package had originally been installed as the
7480                    // original name, and we have already taken care of
7481                    // transitioning to the new one.  Just update the new
7482                    // one to continue using the old name.
7483                    realName = pkg.mRealPackage;
7484                    if (!pkg.packageName.equals(renamed)) {
7485                        // Callers into this function may have already taken
7486                        // care of renaming the package; only do it here if
7487                        // it is not already done.
7488                        pkg.setPackageName(renamed);
7489                    }
7490
7491                } else {
7492                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7493                        if ((origPackage = mSettings.peekPackageLPr(
7494                                pkg.mOriginalPackages.get(i))) != null) {
7495                            // We do have the package already installed under its
7496                            // original name...  should we use it?
7497                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7498                                // New package is not compatible with original.
7499                                origPackage = null;
7500                                continue;
7501                            } else if (origPackage.sharedUser != null) {
7502                                // Make sure uid is compatible between packages.
7503                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7504                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7505                                            + " to " + pkg.packageName + ": old uid "
7506                                            + origPackage.sharedUser.name
7507                                            + " differs from " + pkg.mSharedUserId);
7508                                    origPackage = null;
7509                                    continue;
7510                                }
7511                            } else {
7512                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7513                                        + pkg.packageName + " to old name " + origPackage.name);
7514                            }
7515                            break;
7516                        }
7517                    }
7518                }
7519            }
7520
7521            if (mTransferedPackages.contains(pkg.packageName)) {
7522                Slog.w(TAG, "Package " + pkg.packageName
7523                        + " was transferred to another, but its .apk remains");
7524            }
7525
7526            // See comments in nonMutatedPs declaration
7527            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7528                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7529                if (foundPs != null) {
7530                    nonMutatedPs = new PackageSetting(foundPs);
7531                }
7532            }
7533
7534            // Just create the setting, don't add it yet. For already existing packages
7535            // the PkgSetting exists already and doesn't have to be created.
7536            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7537                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7538                    pkg.applicationInfo.primaryCpuAbi,
7539                    pkg.applicationInfo.secondaryCpuAbi,
7540                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7541                    user, false);
7542            if (pkgSetting == null) {
7543                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7544                        "Creating application package " + pkg.packageName + " failed");
7545            }
7546
7547            if (pkgSetting.origPackage != null) {
7548                // If we are first transitioning from an original package,
7549                // fix up the new package's name now.  We need to do this after
7550                // looking up the package under its new name, so getPackageLP
7551                // can take care of fiddling things correctly.
7552                pkg.setPackageName(origPackage.name);
7553
7554                // File a report about this.
7555                String msg = "New package " + pkgSetting.realName
7556                        + " renamed to replace old package " + pkgSetting.name;
7557                reportSettingsProblem(Log.WARN, msg);
7558
7559                // Make a note of it.
7560                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7561                    mTransferedPackages.add(origPackage.name);
7562                }
7563
7564                // No longer need to retain this.
7565                pkgSetting.origPackage = null;
7566            }
7567
7568            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7569                // Make a note of it.
7570                mTransferedPackages.add(pkg.packageName);
7571            }
7572
7573            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7574                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7575            }
7576
7577            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7578                // Check all shared libraries and map to their actual file path.
7579                // We only do this here for apps not on a system dir, because those
7580                // are the only ones that can fail an install due to this.  We
7581                // will take care of the system apps by updating all of their
7582                // library paths after the scan is done.
7583                updateSharedLibrariesLPw(pkg, null);
7584            }
7585
7586            if (mFoundPolicyFile) {
7587                SELinuxMMAC.assignSeinfoValue(pkg);
7588            }
7589
7590            pkg.applicationInfo.uid = pkgSetting.appId;
7591            pkg.mExtras = pkgSetting;
7592            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7593                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7594                    // We just determined the app is signed correctly, so bring
7595                    // over the latest parsed certs.
7596                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7597                } else {
7598                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7599                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7600                                "Package " + pkg.packageName + " upgrade keys do not match the "
7601                                + "previously installed version");
7602                    } else {
7603                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7604                        String msg = "System package " + pkg.packageName
7605                            + " signature changed; retaining data.";
7606                        reportSettingsProblem(Log.WARN, msg);
7607                    }
7608                }
7609            } else {
7610                try {
7611                    verifySignaturesLP(pkgSetting, pkg);
7612                    // We just determined the app is signed correctly, so bring
7613                    // over the latest parsed certs.
7614                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7615                } catch (PackageManagerException e) {
7616                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7617                        throw e;
7618                    }
7619                    // The signature has changed, but this package is in the system
7620                    // image...  let's recover!
7621                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7622                    // However...  if this package is part of a shared user, but it
7623                    // doesn't match the signature of the shared user, let's fail.
7624                    // What this means is that you can't change the signatures
7625                    // associated with an overall shared user, which doesn't seem all
7626                    // that unreasonable.
7627                    if (pkgSetting.sharedUser != null) {
7628                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7629                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7630                            throw new PackageManagerException(
7631                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7632                                            "Signature mismatch for shared user: "
7633                                            + pkgSetting.sharedUser);
7634                        }
7635                    }
7636                    // File a report about this.
7637                    String msg = "System package " + pkg.packageName
7638                        + " signature changed; retaining data.";
7639                    reportSettingsProblem(Log.WARN, msg);
7640                }
7641            }
7642            // Verify that this new package doesn't have any content providers
7643            // that conflict with existing packages.  Only do this if the
7644            // package isn't already installed, since we don't want to break
7645            // things that are installed.
7646            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7647                final int N = pkg.providers.size();
7648                int i;
7649                for (i=0; i<N; i++) {
7650                    PackageParser.Provider p = pkg.providers.get(i);
7651                    if (p.info.authority != null) {
7652                        String names[] = p.info.authority.split(";");
7653                        for (int j = 0; j < names.length; j++) {
7654                            if (mProvidersByAuthority.containsKey(names[j])) {
7655                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7656                                final String otherPackageName =
7657                                        ((other != null && other.getComponentName() != null) ?
7658                                                other.getComponentName().getPackageName() : "?");
7659                                throw new PackageManagerException(
7660                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7661                                                "Can't install because provider name " + names[j]
7662                                                + " (in package " + pkg.applicationInfo.packageName
7663                                                + ") is already used by " + otherPackageName);
7664                            }
7665                        }
7666                    }
7667                }
7668            }
7669
7670            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7671                // This package wants to adopt ownership of permissions from
7672                // another package.
7673                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7674                    final String origName = pkg.mAdoptPermissions.get(i);
7675                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7676                    if (orig != null) {
7677                        if (verifyPackageUpdateLPr(orig, pkg)) {
7678                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7679                                    + pkg.packageName);
7680                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7681                        }
7682                    }
7683                }
7684            }
7685        }
7686
7687        final String pkgName = pkg.packageName;
7688
7689        final long scanFileTime = scanFile.lastModified();
7690        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7691        pkg.applicationInfo.processName = fixProcessName(
7692                pkg.applicationInfo.packageName,
7693                pkg.applicationInfo.processName,
7694                pkg.applicationInfo.uid);
7695
7696        if (pkg != mPlatformPackage) {
7697            // Get all of our default paths setup
7698            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7699        }
7700
7701        final String path = scanFile.getPath();
7702        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7703
7704        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7705            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7706
7707            // Some system apps still use directory structure for native libraries
7708            // in which case we might end up not detecting abi solely based on apk
7709            // structure. Try to detect abi based on directory structure.
7710            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7711                    pkg.applicationInfo.primaryCpuAbi == null) {
7712                setBundledAppAbisAndRoots(pkg, pkgSetting);
7713                setNativeLibraryPaths(pkg);
7714            }
7715
7716        } else {
7717            if ((scanFlags & SCAN_MOVE) != 0) {
7718                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7719                // but we already have this packages package info in the PackageSetting. We just
7720                // use that and derive the native library path based on the new codepath.
7721                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7722                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7723            }
7724
7725            // Set native library paths again. For moves, the path will be updated based on the
7726            // ABIs we've determined above. For non-moves, the path will be updated based on the
7727            // ABIs we determined during compilation, but the path will depend on the final
7728            // package path (after the rename away from the stage path).
7729            setNativeLibraryPaths(pkg);
7730        }
7731
7732        // This is a special case for the "system" package, where the ABI is
7733        // dictated by the zygote configuration (and init.rc). We should keep track
7734        // of this ABI so that we can deal with "normal" applications that run under
7735        // the same UID correctly.
7736        if (mPlatformPackage == pkg) {
7737            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7738                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7739        }
7740
7741        // If there's a mismatch between the abi-override in the package setting
7742        // and the abiOverride specified for the install. Warn about this because we
7743        // would've already compiled the app without taking the package setting into
7744        // account.
7745        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7746            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7747                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7748                        " for package " + pkg.packageName);
7749            }
7750        }
7751
7752        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7753        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7754        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7755
7756        // Copy the derived override back to the parsed package, so that we can
7757        // update the package settings accordingly.
7758        pkg.cpuAbiOverride = cpuAbiOverride;
7759
7760        if (DEBUG_ABI_SELECTION) {
7761            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7762                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7763                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7764        }
7765
7766        // Push the derived path down into PackageSettings so we know what to
7767        // clean up at uninstall time.
7768        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7769
7770        if (DEBUG_ABI_SELECTION) {
7771            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7772                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7773                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7774        }
7775
7776        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7777            // We don't do this here during boot because we can do it all
7778            // at once after scanning all existing packages.
7779            //
7780            // We also do this *before* we perform dexopt on this package, so that
7781            // we can avoid redundant dexopts, and also to make sure we've got the
7782            // code and package path correct.
7783            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7784                    pkg, true /* boot complete */);
7785        }
7786
7787        if (mFactoryTest && pkg.requestedPermissions.contains(
7788                android.Manifest.permission.FACTORY_TEST)) {
7789            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7790        }
7791
7792        ArrayList<PackageParser.Package> clientLibPkgs = null;
7793
7794        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7795            if (nonMutatedPs != null) {
7796                synchronized (mPackages) {
7797                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7798                }
7799            }
7800            return pkg;
7801        }
7802
7803        // Only privileged apps and updated privileged apps can add child packages.
7804        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7805            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7806                throw new PackageManagerException("Only privileged apps and updated "
7807                        + "privileged apps can add child packages. Ignoring package "
7808                        + pkg.packageName);
7809            }
7810            final int childCount = pkg.childPackages.size();
7811            for (int i = 0; i < childCount; i++) {
7812                PackageParser.Package childPkg = pkg.childPackages.get(i);
7813                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7814                        childPkg.packageName)) {
7815                    throw new PackageManagerException("Cannot override a child package of "
7816                            + "another disabled system app. Ignoring package " + pkg.packageName);
7817                }
7818            }
7819        }
7820
7821        // writer
7822        synchronized (mPackages) {
7823            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7824                // Only system apps can add new shared libraries.
7825                if (pkg.libraryNames != null) {
7826                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7827                        String name = pkg.libraryNames.get(i);
7828                        boolean allowed = false;
7829                        if (pkg.isUpdatedSystemApp()) {
7830                            // New library entries can only be added through the
7831                            // system image.  This is important to get rid of a lot
7832                            // of nasty edge cases: for example if we allowed a non-
7833                            // system update of the app to add a library, then uninstalling
7834                            // the update would make the library go away, and assumptions
7835                            // we made such as through app install filtering would now
7836                            // have allowed apps on the device which aren't compatible
7837                            // with it.  Better to just have the restriction here, be
7838                            // conservative, and create many fewer cases that can negatively
7839                            // impact the user experience.
7840                            final PackageSetting sysPs = mSettings
7841                                    .getDisabledSystemPkgLPr(pkg.packageName);
7842                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7843                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7844                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7845                                        allowed = true;
7846                                        break;
7847                                    }
7848                                }
7849                            }
7850                        } else {
7851                            allowed = true;
7852                        }
7853                        if (allowed) {
7854                            if (!mSharedLibraries.containsKey(name)) {
7855                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7856                            } else if (!name.equals(pkg.packageName)) {
7857                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7858                                        + name + " already exists; skipping");
7859                            }
7860                        } else {
7861                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7862                                    + name + " that is not declared on system image; skipping");
7863                        }
7864                    }
7865                    if ((scanFlags & SCAN_BOOTING) == 0) {
7866                        // If we are not booting, we need to update any applications
7867                        // that are clients of our shared library.  If we are booting,
7868                        // this will all be done once the scan is complete.
7869                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7870                    }
7871                }
7872            }
7873        }
7874
7875        // Request the ActivityManager to kill the process(only for existing packages)
7876        // so that we do not end up in a confused state while the user is still using the older
7877        // version of the application while the new one gets installed.
7878        if ((scanFlags & SCAN_REPLACING) != 0) {
7879            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7880
7881            killApplication(pkg.applicationInfo.packageName,
7882                        pkg.applicationInfo.uid, "replace pkg");
7883
7884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7885        }
7886
7887        // Also need to kill any apps that are dependent on the library.
7888        if (clientLibPkgs != null) {
7889            for (int i=0; i<clientLibPkgs.size(); i++) {
7890                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7891                killApplication(clientPkg.applicationInfo.packageName,
7892                        clientPkg.applicationInfo.uid, "update lib");
7893            }
7894        }
7895
7896        // Make sure we're not adding any bogus keyset info
7897        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7898        ksms.assertScannedPackageValid(pkg);
7899
7900        // writer
7901        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7902
7903        boolean createIdmapFailed = false;
7904        synchronized (mPackages) {
7905            // We don't expect installation to fail beyond this point
7906
7907            // Add the new setting to mSettings
7908            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7909            // Add the new setting to mPackages
7910            mPackages.put(pkg.applicationInfo.packageName, pkg);
7911            // Make sure we don't accidentally delete its data.
7912            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7913            while (iter.hasNext()) {
7914                PackageCleanItem item = iter.next();
7915                if (pkgName.equals(item.packageName)) {
7916                    iter.remove();
7917                }
7918            }
7919
7920            // Take care of first install / last update times.
7921            if (currentTime != 0) {
7922                if (pkgSetting.firstInstallTime == 0) {
7923                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7924                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7925                    pkgSetting.lastUpdateTime = currentTime;
7926                }
7927            } else if (pkgSetting.firstInstallTime == 0) {
7928                // We need *something*.  Take time time stamp of the file.
7929                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7930            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7931                if (scanFileTime != pkgSetting.timeStamp) {
7932                    // A package on the system image has changed; consider this
7933                    // to be an update.
7934                    pkgSetting.lastUpdateTime = scanFileTime;
7935                }
7936            }
7937
7938            // Add the package's KeySets to the global KeySetManagerService
7939            ksms.addScannedPackageLPw(pkg);
7940
7941            int N = pkg.providers.size();
7942            StringBuilder r = null;
7943            int i;
7944            for (i=0; i<N; i++) {
7945                PackageParser.Provider p = pkg.providers.get(i);
7946                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7947                        p.info.processName, pkg.applicationInfo.uid);
7948                mProviders.addProvider(p);
7949                p.syncable = p.info.isSyncable;
7950                if (p.info.authority != null) {
7951                    String names[] = p.info.authority.split(";");
7952                    p.info.authority = null;
7953                    for (int j = 0; j < names.length; j++) {
7954                        if (j == 1 && p.syncable) {
7955                            // We only want the first authority for a provider to possibly be
7956                            // syncable, so if we already added this provider using a different
7957                            // authority clear the syncable flag. We copy the provider before
7958                            // changing it because the mProviders object contains a reference
7959                            // to a provider that we don't want to change.
7960                            // Only do this for the second authority since the resulting provider
7961                            // object can be the same for all future authorities for this provider.
7962                            p = new PackageParser.Provider(p);
7963                            p.syncable = false;
7964                        }
7965                        if (!mProvidersByAuthority.containsKey(names[j])) {
7966                            mProvidersByAuthority.put(names[j], p);
7967                            if (p.info.authority == null) {
7968                                p.info.authority = names[j];
7969                            } else {
7970                                p.info.authority = p.info.authority + ";" + names[j];
7971                            }
7972                            if (DEBUG_PACKAGE_SCANNING) {
7973                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7974                                    Log.d(TAG, "Registered content provider: " + names[j]
7975                                            + ", className = " + p.info.name + ", isSyncable = "
7976                                            + p.info.isSyncable);
7977                            }
7978                        } else {
7979                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7980                            Slog.w(TAG, "Skipping provider name " + names[j] +
7981                                    " (in package " + pkg.applicationInfo.packageName +
7982                                    "): name already used by "
7983                                    + ((other != null && other.getComponentName() != null)
7984                                            ? other.getComponentName().getPackageName() : "?"));
7985                        }
7986                    }
7987                }
7988                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7989                    if (r == null) {
7990                        r = new StringBuilder(256);
7991                    } else {
7992                        r.append(' ');
7993                    }
7994                    r.append(p.info.name);
7995                }
7996            }
7997            if (r != null) {
7998                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7999            }
8000
8001            N = pkg.services.size();
8002            r = null;
8003            for (i=0; i<N; i++) {
8004                PackageParser.Service s = pkg.services.get(i);
8005                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8006                        s.info.processName, pkg.applicationInfo.uid);
8007                mServices.addService(s);
8008                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8009                    if (r == null) {
8010                        r = new StringBuilder(256);
8011                    } else {
8012                        r.append(' ');
8013                    }
8014                    r.append(s.info.name);
8015                }
8016            }
8017            if (r != null) {
8018                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8019            }
8020
8021            N = pkg.receivers.size();
8022            r = null;
8023            for (i=0; i<N; i++) {
8024                PackageParser.Activity a = pkg.receivers.get(i);
8025                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8026                        a.info.processName, pkg.applicationInfo.uid);
8027                mReceivers.addActivity(a, "receiver");
8028                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8029                    if (r == null) {
8030                        r = new StringBuilder(256);
8031                    } else {
8032                        r.append(' ');
8033                    }
8034                    r.append(a.info.name);
8035                }
8036            }
8037            if (r != null) {
8038                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8039            }
8040
8041            N = pkg.activities.size();
8042            r = null;
8043            for (i=0; i<N; i++) {
8044                PackageParser.Activity a = pkg.activities.get(i);
8045                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8046                        a.info.processName, pkg.applicationInfo.uid);
8047                mActivities.addActivity(a, "activity");
8048                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8049                    if (r == null) {
8050                        r = new StringBuilder(256);
8051                    } else {
8052                        r.append(' ');
8053                    }
8054                    r.append(a.info.name);
8055                }
8056            }
8057            if (r != null) {
8058                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8059            }
8060
8061            N = pkg.permissionGroups.size();
8062            r = null;
8063            for (i=0; i<N; i++) {
8064                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8065                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8066                if (cur == null) {
8067                    mPermissionGroups.put(pg.info.name, pg);
8068                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8069                        if (r == null) {
8070                            r = new StringBuilder(256);
8071                        } else {
8072                            r.append(' ');
8073                        }
8074                        r.append(pg.info.name);
8075                    }
8076                } else {
8077                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8078                            + pg.info.packageName + " ignored: original from "
8079                            + cur.info.packageName);
8080                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8081                        if (r == null) {
8082                            r = new StringBuilder(256);
8083                        } else {
8084                            r.append(' ');
8085                        }
8086                        r.append("DUP:");
8087                        r.append(pg.info.name);
8088                    }
8089                }
8090            }
8091            if (r != null) {
8092                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8093            }
8094
8095            N = pkg.permissions.size();
8096            r = null;
8097            for (i=0; i<N; i++) {
8098                PackageParser.Permission p = pkg.permissions.get(i);
8099
8100                // Assume by default that we did not install this permission into the system.
8101                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8102
8103                // Now that permission groups have a special meaning, we ignore permission
8104                // groups for legacy apps to prevent unexpected behavior. In particular,
8105                // permissions for one app being granted to someone just becase they happen
8106                // to be in a group defined by another app (before this had no implications).
8107                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8108                    p.group = mPermissionGroups.get(p.info.group);
8109                    // Warn for a permission in an unknown group.
8110                    if (p.info.group != null && p.group == null) {
8111                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8112                                + p.info.packageName + " in an unknown group " + p.info.group);
8113                    }
8114                }
8115
8116                ArrayMap<String, BasePermission> permissionMap =
8117                        p.tree ? mSettings.mPermissionTrees
8118                                : mSettings.mPermissions;
8119                BasePermission bp = permissionMap.get(p.info.name);
8120
8121                // Allow system apps to redefine non-system permissions
8122                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8123                    final boolean currentOwnerIsSystem = (bp.perm != null
8124                            && isSystemApp(bp.perm.owner));
8125                    if (isSystemApp(p.owner)) {
8126                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8127                            // It's a built-in permission and no owner, take ownership now
8128                            bp.packageSetting = pkgSetting;
8129                            bp.perm = p;
8130                            bp.uid = pkg.applicationInfo.uid;
8131                            bp.sourcePackage = p.info.packageName;
8132                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8133                        } else if (!currentOwnerIsSystem) {
8134                            String msg = "New decl " + p.owner + " of permission  "
8135                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8136                            reportSettingsProblem(Log.WARN, msg);
8137                            bp = null;
8138                        }
8139                    }
8140                }
8141
8142                if (bp == null) {
8143                    bp = new BasePermission(p.info.name, p.info.packageName,
8144                            BasePermission.TYPE_NORMAL);
8145                    permissionMap.put(p.info.name, bp);
8146                }
8147
8148                if (bp.perm == null) {
8149                    if (bp.sourcePackage == null
8150                            || bp.sourcePackage.equals(p.info.packageName)) {
8151                        BasePermission tree = findPermissionTreeLP(p.info.name);
8152                        if (tree == null
8153                                || tree.sourcePackage.equals(p.info.packageName)) {
8154                            bp.packageSetting = pkgSetting;
8155                            bp.perm = p;
8156                            bp.uid = pkg.applicationInfo.uid;
8157                            bp.sourcePackage = p.info.packageName;
8158                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8159                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8160                                if (r == null) {
8161                                    r = new StringBuilder(256);
8162                                } else {
8163                                    r.append(' ');
8164                                }
8165                                r.append(p.info.name);
8166                            }
8167                        } else {
8168                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8169                                    + p.info.packageName + " ignored: base tree "
8170                                    + tree.name + " is from package "
8171                                    + tree.sourcePackage);
8172                        }
8173                    } else {
8174                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8175                                + p.info.packageName + " ignored: original from "
8176                                + bp.sourcePackage);
8177                    }
8178                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8179                    if (r == null) {
8180                        r = new StringBuilder(256);
8181                    } else {
8182                        r.append(' ');
8183                    }
8184                    r.append("DUP:");
8185                    r.append(p.info.name);
8186                }
8187                if (bp.perm == p) {
8188                    bp.protectionLevel = p.info.protectionLevel;
8189                }
8190            }
8191
8192            if (r != null) {
8193                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8194            }
8195
8196            N = pkg.instrumentation.size();
8197            r = null;
8198            for (i=0; i<N; i++) {
8199                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8200                a.info.packageName = pkg.applicationInfo.packageName;
8201                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8202                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8203                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8204                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8205                a.info.dataDir = pkg.applicationInfo.dataDir;
8206                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
8207                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
8208
8209                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8210                // need other information about the application, like the ABI and what not ?
8211                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8212                mInstrumentation.put(a.getComponentName(), a);
8213                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8214                    if (r == null) {
8215                        r = new StringBuilder(256);
8216                    } else {
8217                        r.append(' ');
8218                    }
8219                    r.append(a.info.name);
8220                }
8221            }
8222            if (r != null) {
8223                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8224            }
8225
8226            if (pkg.protectedBroadcasts != null) {
8227                N = pkg.protectedBroadcasts.size();
8228                for (i=0; i<N; i++) {
8229                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8230                }
8231            }
8232
8233            pkgSetting.setTimeStamp(scanFileTime);
8234
8235            // Create idmap files for pairs of (packages, overlay packages).
8236            // Note: "android", ie framework-res.apk, is handled by native layers.
8237            if (pkg.mOverlayTarget != null) {
8238                // This is an overlay package.
8239                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8240                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8241                        mOverlays.put(pkg.mOverlayTarget,
8242                                new ArrayMap<String, PackageParser.Package>());
8243                    }
8244                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8245                    map.put(pkg.packageName, pkg);
8246                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8247                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8248                        createIdmapFailed = true;
8249                    }
8250                }
8251            } else if (mOverlays.containsKey(pkg.packageName) &&
8252                    !pkg.packageName.equals("android")) {
8253                // This is a regular package, with one or more known overlay packages.
8254                createIdmapsForPackageLI(pkg);
8255            }
8256        }
8257
8258        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8259
8260        if (createIdmapFailed) {
8261            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8262                    "scanPackageLI failed to createIdmap");
8263        }
8264        return pkg;
8265    }
8266
8267    /**
8268     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8269     * is derived purely on the basis of the contents of {@code scanFile} and
8270     * {@code cpuAbiOverride}.
8271     *
8272     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8273     */
8274    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8275                                 String cpuAbiOverride, boolean extractLibs)
8276            throws PackageManagerException {
8277        // TODO: We can probably be smarter about this stuff. For installed apps,
8278        // we can calculate this information at install time once and for all. For
8279        // system apps, we can probably assume that this information doesn't change
8280        // after the first boot scan. As things stand, we do lots of unnecessary work.
8281
8282        // Give ourselves some initial paths; we'll come back for another
8283        // pass once we've determined ABI below.
8284        setNativeLibraryPaths(pkg);
8285
8286        // We would never need to extract libs for forward-locked and external packages,
8287        // since the container service will do it for us. We shouldn't attempt to
8288        // extract libs from system app when it was not updated.
8289        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8290                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8291            extractLibs = false;
8292        }
8293
8294        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8295        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8296
8297        NativeLibraryHelper.Handle handle = null;
8298        try {
8299            handle = NativeLibraryHelper.Handle.create(pkg);
8300            // TODO(multiArch): This can be null for apps that didn't go through the
8301            // usual installation process. We can calculate it again, like we
8302            // do during install time.
8303            //
8304            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8305            // unnecessary.
8306            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8307
8308            // Null out the abis so that they can be recalculated.
8309            pkg.applicationInfo.primaryCpuAbi = null;
8310            pkg.applicationInfo.secondaryCpuAbi = null;
8311            if (isMultiArch(pkg.applicationInfo)) {
8312                // Warn if we've set an abiOverride for multi-lib packages..
8313                // By definition, we need to copy both 32 and 64 bit libraries for
8314                // such packages.
8315                if (pkg.cpuAbiOverride != null
8316                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8317                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8318                }
8319
8320                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8321                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8322                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8323                    if (extractLibs) {
8324                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8325                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8326                                useIsaSpecificSubdirs);
8327                    } else {
8328                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8329                    }
8330                }
8331
8332                maybeThrowExceptionForMultiArchCopy(
8333                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8334
8335                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8336                    if (extractLibs) {
8337                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8338                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8339                                useIsaSpecificSubdirs);
8340                    } else {
8341                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8342                    }
8343                }
8344
8345                maybeThrowExceptionForMultiArchCopy(
8346                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8347
8348                if (abi64 >= 0) {
8349                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8350                }
8351
8352                if (abi32 >= 0) {
8353                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8354                    if (abi64 >= 0) {
8355                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8356                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8357                            pkg.applicationInfo.primaryCpuAbi = abi;
8358                        } else {
8359                            pkg.applicationInfo.secondaryCpuAbi = abi;
8360                        }
8361                    } else {
8362                        pkg.applicationInfo.primaryCpuAbi = abi;
8363                    }
8364                }
8365
8366            } else {
8367                String[] abiList = (cpuAbiOverride != null) ?
8368                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8369
8370                // Enable gross and lame hacks for apps that are built with old
8371                // SDK tools. We must scan their APKs for renderscript bitcode and
8372                // not launch them if it's present. Don't bother checking on devices
8373                // that don't have 64 bit support.
8374                boolean needsRenderScriptOverride = false;
8375                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8376                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8377                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8378                    needsRenderScriptOverride = true;
8379                }
8380
8381                final int copyRet;
8382                if (extractLibs) {
8383                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8384                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8385                } else {
8386                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8387                }
8388
8389                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8390                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8391                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8392                }
8393
8394                if (copyRet >= 0) {
8395                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8396                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8397                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8398                } else if (needsRenderScriptOverride) {
8399                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8400                }
8401            }
8402        } catch (IOException ioe) {
8403            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8404        } finally {
8405            IoUtils.closeQuietly(handle);
8406        }
8407
8408        // Now that we've calculated the ABIs and determined if it's an internal app,
8409        // we will go ahead and populate the nativeLibraryPath.
8410        setNativeLibraryPaths(pkg);
8411    }
8412
8413    /**
8414     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8415     * i.e, so that all packages can be run inside a single process if required.
8416     *
8417     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8418     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8419     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8420     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8421     * updating a package that belongs to a shared user.
8422     *
8423     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8424     * adds unnecessary complexity.
8425     */
8426    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8427            PackageParser.Package scannedPackage, boolean bootComplete) {
8428        String requiredInstructionSet = null;
8429        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8430            requiredInstructionSet = VMRuntime.getInstructionSet(
8431                     scannedPackage.applicationInfo.primaryCpuAbi);
8432        }
8433
8434        PackageSetting requirer = null;
8435        for (PackageSetting ps : packagesForUser) {
8436            // If packagesForUser contains scannedPackage, we skip it. This will happen
8437            // when scannedPackage is an update of an existing package. Without this check,
8438            // we will never be able to change the ABI of any package belonging to a shared
8439            // user, even if it's compatible with other packages.
8440            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8441                if (ps.primaryCpuAbiString == null) {
8442                    continue;
8443                }
8444
8445                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8446                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8447                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8448                    // this but there's not much we can do.
8449                    String errorMessage = "Instruction set mismatch, "
8450                            + ((requirer == null) ? "[caller]" : requirer)
8451                            + " requires " + requiredInstructionSet + " whereas " + ps
8452                            + " requires " + instructionSet;
8453                    Slog.w(TAG, errorMessage);
8454                }
8455
8456                if (requiredInstructionSet == null) {
8457                    requiredInstructionSet = instructionSet;
8458                    requirer = ps;
8459                }
8460            }
8461        }
8462
8463        if (requiredInstructionSet != null) {
8464            String adjustedAbi;
8465            if (requirer != null) {
8466                // requirer != null implies that either scannedPackage was null or that scannedPackage
8467                // did not require an ABI, in which case we have to adjust scannedPackage to match
8468                // the ABI of the set (which is the same as requirer's ABI)
8469                adjustedAbi = requirer.primaryCpuAbiString;
8470                if (scannedPackage != null) {
8471                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8472                }
8473            } else {
8474                // requirer == null implies that we're updating all ABIs in the set to
8475                // match scannedPackage.
8476                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8477            }
8478
8479            for (PackageSetting ps : packagesForUser) {
8480                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8481                    if (ps.primaryCpuAbiString != null) {
8482                        continue;
8483                    }
8484
8485                    ps.primaryCpuAbiString = adjustedAbi;
8486                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8487                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8488                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8489                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8490                                + " (requirer="
8491                                + (requirer == null ? "null" : requirer.pkg.packageName)
8492                                + ", scannedPackage="
8493                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8494                                + ")");
8495                        try {
8496                            mInstaller.rmdex(ps.codePathString,
8497                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8498                        } catch (InstallerException ignored) {
8499                        }
8500                    }
8501                }
8502            }
8503        }
8504    }
8505
8506    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8507        synchronized (mPackages) {
8508            mResolverReplaced = true;
8509            // Set up information for custom user intent resolution activity.
8510            mResolveActivity.applicationInfo = pkg.applicationInfo;
8511            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8512            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8513            mResolveActivity.processName = pkg.applicationInfo.packageName;
8514            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8515            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8516                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8517            mResolveActivity.theme = 0;
8518            mResolveActivity.exported = true;
8519            mResolveActivity.enabled = true;
8520            mResolveInfo.activityInfo = mResolveActivity;
8521            mResolveInfo.priority = 0;
8522            mResolveInfo.preferredOrder = 0;
8523            mResolveInfo.match = 0;
8524            mResolveComponentName = mCustomResolverComponentName;
8525            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8526                    mResolveComponentName);
8527        }
8528    }
8529
8530    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8531        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8532
8533        // Set up information for ephemeral installer activity
8534        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8535        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8536        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8537        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8538        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8539        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8540                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8541        mEphemeralInstallerActivity.theme = 0;
8542        mEphemeralInstallerActivity.exported = true;
8543        mEphemeralInstallerActivity.enabled = true;
8544        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8545        mEphemeralInstallerInfo.priority = 0;
8546        mEphemeralInstallerInfo.preferredOrder = 0;
8547        mEphemeralInstallerInfo.match = 0;
8548
8549        if (DEBUG_EPHEMERAL) {
8550            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8551        }
8552    }
8553
8554    private static String calculateBundledApkRoot(final String codePathString) {
8555        final File codePath = new File(codePathString);
8556        final File codeRoot;
8557        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8558            codeRoot = Environment.getRootDirectory();
8559        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8560            codeRoot = Environment.getOemDirectory();
8561        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8562            codeRoot = Environment.getVendorDirectory();
8563        } else {
8564            // Unrecognized code path; take its top real segment as the apk root:
8565            // e.g. /something/app/blah.apk => /something
8566            try {
8567                File f = codePath.getCanonicalFile();
8568                File parent = f.getParentFile();    // non-null because codePath is a file
8569                File tmp;
8570                while ((tmp = parent.getParentFile()) != null) {
8571                    f = parent;
8572                    parent = tmp;
8573                }
8574                codeRoot = f;
8575                Slog.w(TAG, "Unrecognized code path "
8576                        + codePath + " - using " + codeRoot);
8577            } catch (IOException e) {
8578                // Can't canonicalize the code path -- shenanigans?
8579                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8580                return Environment.getRootDirectory().getPath();
8581            }
8582        }
8583        return codeRoot.getPath();
8584    }
8585
8586    /**
8587     * Derive and set the location of native libraries for the given package,
8588     * which varies depending on where and how the package was installed.
8589     */
8590    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8591        final ApplicationInfo info = pkg.applicationInfo;
8592        final String codePath = pkg.codePath;
8593        final File codeFile = new File(codePath);
8594        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8595        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8596
8597        info.nativeLibraryRootDir = null;
8598        info.nativeLibraryRootRequiresIsa = false;
8599        info.nativeLibraryDir = null;
8600        info.secondaryNativeLibraryDir = null;
8601
8602        if (isApkFile(codeFile)) {
8603            // Monolithic install
8604            if (bundledApp) {
8605                // If "/system/lib64/apkname" exists, assume that is the per-package
8606                // native library directory to use; otherwise use "/system/lib/apkname".
8607                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8608                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8609                        getPrimaryInstructionSet(info));
8610
8611                // This is a bundled system app so choose the path based on the ABI.
8612                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8613                // is just the default path.
8614                final String apkName = deriveCodePathName(codePath);
8615                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8616                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8617                        apkName).getAbsolutePath();
8618
8619                if (info.secondaryCpuAbi != null) {
8620                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8621                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8622                            secondaryLibDir, apkName).getAbsolutePath();
8623                }
8624            } else if (asecApp) {
8625                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8626                        .getAbsolutePath();
8627            } else {
8628                final String apkName = deriveCodePathName(codePath);
8629                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8630                        .getAbsolutePath();
8631            }
8632
8633            info.nativeLibraryRootRequiresIsa = false;
8634            info.nativeLibraryDir = info.nativeLibraryRootDir;
8635        } else {
8636            // Cluster install
8637            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8638            info.nativeLibraryRootRequiresIsa = true;
8639
8640            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8641                    getPrimaryInstructionSet(info)).getAbsolutePath();
8642
8643            if (info.secondaryCpuAbi != null) {
8644                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8645                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8646            }
8647        }
8648    }
8649
8650    /**
8651     * Calculate the abis and roots for a bundled app. These can uniquely
8652     * be determined from the contents of the system partition, i.e whether
8653     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8654     * of this information, and instead assume that the system was built
8655     * sensibly.
8656     */
8657    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8658                                           PackageSetting pkgSetting) {
8659        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8660
8661        // If "/system/lib64/apkname" exists, assume that is the per-package
8662        // native library directory to use; otherwise use "/system/lib/apkname".
8663        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8664        setBundledAppAbi(pkg, apkRoot, apkName);
8665        // pkgSetting might be null during rescan following uninstall of updates
8666        // to a bundled app, so accommodate that possibility.  The settings in
8667        // that case will be established later from the parsed package.
8668        //
8669        // If the settings aren't null, sync them up with what we've just derived.
8670        // note that apkRoot isn't stored in the package settings.
8671        if (pkgSetting != null) {
8672            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8673            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8674        }
8675    }
8676
8677    /**
8678     * Deduces the ABI of a bundled app and sets the relevant fields on the
8679     * parsed pkg object.
8680     *
8681     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8682     *        under which system libraries are installed.
8683     * @param apkName the name of the installed package.
8684     */
8685    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8686        final File codeFile = new File(pkg.codePath);
8687
8688        final boolean has64BitLibs;
8689        final boolean has32BitLibs;
8690        if (isApkFile(codeFile)) {
8691            // Monolithic install
8692            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8693            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8694        } else {
8695            // Cluster install
8696            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8697            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8698                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8699                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8700                has64BitLibs = (new File(rootDir, isa)).exists();
8701            } else {
8702                has64BitLibs = false;
8703            }
8704            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8705                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8706                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8707                has32BitLibs = (new File(rootDir, isa)).exists();
8708            } else {
8709                has32BitLibs = false;
8710            }
8711        }
8712
8713        if (has64BitLibs && !has32BitLibs) {
8714            // The package has 64 bit libs, but not 32 bit libs. Its primary
8715            // ABI should be 64 bit. We can safely assume here that the bundled
8716            // native libraries correspond to the most preferred ABI in the list.
8717
8718            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8719            pkg.applicationInfo.secondaryCpuAbi = null;
8720        } else if (has32BitLibs && !has64BitLibs) {
8721            // The package has 32 bit libs but not 64 bit libs. Its primary
8722            // ABI should be 32 bit.
8723
8724            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8725            pkg.applicationInfo.secondaryCpuAbi = null;
8726        } else if (has32BitLibs && has64BitLibs) {
8727            // The application has both 64 and 32 bit bundled libraries. We check
8728            // here that the app declares multiArch support, and warn if it doesn't.
8729            //
8730            // We will be lenient here and record both ABIs. The primary will be the
8731            // ABI that's higher on the list, i.e, a device that's configured to prefer
8732            // 64 bit apps will see a 64 bit primary ABI,
8733
8734            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8735                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8736            }
8737
8738            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8739                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8740                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8741            } else {
8742                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8743                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8744            }
8745        } else {
8746            pkg.applicationInfo.primaryCpuAbi = null;
8747            pkg.applicationInfo.secondaryCpuAbi = null;
8748        }
8749    }
8750
8751    private void killPackage(PackageParser.Package pkg, String reason) {
8752        // Kill the parent package
8753        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8754        // Kill the child packages
8755        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8756        for (int i = 0; i < childCount; i++) {
8757            PackageParser.Package childPkg = pkg.childPackages.get(i);
8758            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8759        }
8760    }
8761
8762    private void killApplication(String pkgName, int appId, String reason) {
8763        // Request the ActivityManager to kill the process(only for existing packages)
8764        // so that we do not end up in a confused state while the user is still using the older
8765        // version of the application while the new one gets installed.
8766        IActivityManager am = ActivityManagerNative.getDefault();
8767        if (am != null) {
8768            try {
8769                am.killApplicationWithAppId(pkgName, appId, reason);
8770            } catch (RemoteException e) {
8771            }
8772        }
8773    }
8774
8775    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8776        // Remove the parent package setting
8777        PackageSetting ps = (PackageSetting) pkg.mExtras;
8778        if (ps != null) {
8779            removePackageLI(ps, chatty);
8780        }
8781        // Remove the child package setting
8782        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8783        for (int i = 0; i < childCount; i++) {
8784            PackageParser.Package childPkg = pkg.childPackages.get(i);
8785            ps = (PackageSetting) childPkg.mExtras;
8786            if (ps != null) {
8787                removePackageLI(ps, chatty);
8788            }
8789        }
8790    }
8791
8792    void removePackageLI(PackageSetting ps, boolean chatty) {
8793        if (DEBUG_INSTALL) {
8794            if (chatty)
8795                Log.d(TAG, "Removing package " + ps.name);
8796        }
8797
8798        // writer
8799        synchronized (mPackages) {
8800            mPackages.remove(ps.name);
8801            final PackageParser.Package pkg = ps.pkg;
8802            if (pkg != null) {
8803                cleanPackageDataStructuresLILPw(pkg, chatty);
8804            }
8805        }
8806    }
8807
8808    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8809        if (DEBUG_INSTALL) {
8810            if (chatty)
8811                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8812        }
8813
8814        // writer
8815        synchronized (mPackages) {
8816            // Remove the parent package
8817            mPackages.remove(pkg.applicationInfo.packageName);
8818            cleanPackageDataStructuresLILPw(pkg, chatty);
8819
8820            // Remove the child packages
8821            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8822            for (int i = 0; i < childCount; i++) {
8823                PackageParser.Package childPkg = pkg.childPackages.get(i);
8824                mPackages.remove(childPkg.applicationInfo.packageName);
8825                cleanPackageDataStructuresLILPw(childPkg, chatty);
8826            }
8827        }
8828    }
8829
8830    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8831        int N = pkg.providers.size();
8832        StringBuilder r = null;
8833        int i;
8834        for (i=0; i<N; i++) {
8835            PackageParser.Provider p = pkg.providers.get(i);
8836            mProviders.removeProvider(p);
8837            if (p.info.authority == null) {
8838
8839                /* There was another ContentProvider with this authority when
8840                 * this app was installed so this authority is null,
8841                 * Ignore it as we don't have to unregister the provider.
8842                 */
8843                continue;
8844            }
8845            String names[] = p.info.authority.split(";");
8846            for (int j = 0; j < names.length; j++) {
8847                if (mProvidersByAuthority.get(names[j]) == p) {
8848                    mProvidersByAuthority.remove(names[j]);
8849                    if (DEBUG_REMOVE) {
8850                        if (chatty)
8851                            Log.d(TAG, "Unregistered content provider: " + names[j]
8852                                    + ", className = " + p.info.name + ", isSyncable = "
8853                                    + p.info.isSyncable);
8854                    }
8855                }
8856            }
8857            if (DEBUG_REMOVE && chatty) {
8858                if (r == null) {
8859                    r = new StringBuilder(256);
8860                } else {
8861                    r.append(' ');
8862                }
8863                r.append(p.info.name);
8864            }
8865        }
8866        if (r != null) {
8867            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8868        }
8869
8870        N = pkg.services.size();
8871        r = null;
8872        for (i=0; i<N; i++) {
8873            PackageParser.Service s = pkg.services.get(i);
8874            mServices.removeService(s);
8875            if (chatty) {
8876                if (r == null) {
8877                    r = new StringBuilder(256);
8878                } else {
8879                    r.append(' ');
8880                }
8881                r.append(s.info.name);
8882            }
8883        }
8884        if (r != null) {
8885            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8886        }
8887
8888        N = pkg.receivers.size();
8889        r = null;
8890        for (i=0; i<N; i++) {
8891            PackageParser.Activity a = pkg.receivers.get(i);
8892            mReceivers.removeActivity(a, "receiver");
8893            if (DEBUG_REMOVE && chatty) {
8894                if (r == null) {
8895                    r = new StringBuilder(256);
8896                } else {
8897                    r.append(' ');
8898                }
8899                r.append(a.info.name);
8900            }
8901        }
8902        if (r != null) {
8903            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8904        }
8905
8906        N = pkg.activities.size();
8907        r = null;
8908        for (i=0; i<N; i++) {
8909            PackageParser.Activity a = pkg.activities.get(i);
8910            mActivities.removeActivity(a, "activity");
8911            if (DEBUG_REMOVE && chatty) {
8912                if (r == null) {
8913                    r = new StringBuilder(256);
8914                } else {
8915                    r.append(' ');
8916                }
8917                r.append(a.info.name);
8918            }
8919        }
8920        if (r != null) {
8921            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8922        }
8923
8924        N = pkg.permissions.size();
8925        r = null;
8926        for (i=0; i<N; i++) {
8927            PackageParser.Permission p = pkg.permissions.get(i);
8928            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8929            if (bp == null) {
8930                bp = mSettings.mPermissionTrees.get(p.info.name);
8931            }
8932            if (bp != null && bp.perm == p) {
8933                bp.perm = null;
8934                if (DEBUG_REMOVE && chatty) {
8935                    if (r == null) {
8936                        r = new StringBuilder(256);
8937                    } else {
8938                        r.append(' ');
8939                    }
8940                    r.append(p.info.name);
8941                }
8942            }
8943            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8944                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8945                if (appOpPkgs != null) {
8946                    appOpPkgs.remove(pkg.packageName);
8947                }
8948            }
8949        }
8950        if (r != null) {
8951            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8952        }
8953
8954        N = pkg.requestedPermissions.size();
8955        r = null;
8956        for (i=0; i<N; i++) {
8957            String perm = pkg.requestedPermissions.get(i);
8958            BasePermission bp = mSettings.mPermissions.get(perm);
8959            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8960                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8961                if (appOpPkgs != null) {
8962                    appOpPkgs.remove(pkg.packageName);
8963                    if (appOpPkgs.isEmpty()) {
8964                        mAppOpPermissionPackages.remove(perm);
8965                    }
8966                }
8967            }
8968        }
8969        if (r != null) {
8970            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8971        }
8972
8973        N = pkg.instrumentation.size();
8974        r = null;
8975        for (i=0; i<N; i++) {
8976            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8977            mInstrumentation.remove(a.getComponentName());
8978            if (DEBUG_REMOVE && chatty) {
8979                if (r == null) {
8980                    r = new StringBuilder(256);
8981                } else {
8982                    r.append(' ');
8983                }
8984                r.append(a.info.name);
8985            }
8986        }
8987        if (r != null) {
8988            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8989        }
8990
8991        r = null;
8992        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8993            // Only system apps can hold shared libraries.
8994            if (pkg.libraryNames != null) {
8995                for (i=0; i<pkg.libraryNames.size(); i++) {
8996                    String name = pkg.libraryNames.get(i);
8997                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8998                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8999                        mSharedLibraries.remove(name);
9000                        if (DEBUG_REMOVE && chatty) {
9001                            if (r == null) {
9002                                r = new StringBuilder(256);
9003                            } else {
9004                                r.append(' ');
9005                            }
9006                            r.append(name);
9007                        }
9008                    }
9009                }
9010            }
9011        }
9012        if (r != null) {
9013            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9014        }
9015    }
9016
9017    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9018        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9019            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9020                return true;
9021            }
9022        }
9023        return false;
9024    }
9025
9026    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9027    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9028    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9029
9030    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9031        // Update the parent permissions
9032        updatePermissionsLPw(pkg.packageName, pkg, flags);
9033        // Update the child permissions
9034        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9035        for (int i = 0; i < childCount; i++) {
9036            PackageParser.Package childPkg = pkg.childPackages.get(i);
9037            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9038        }
9039    }
9040
9041    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9042            int flags) {
9043        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9044        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9045    }
9046
9047    private void updatePermissionsLPw(String changingPkg,
9048            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9049        // Make sure there are no dangling permission trees.
9050        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9051        while (it.hasNext()) {
9052            final BasePermission bp = it.next();
9053            if (bp.packageSetting == null) {
9054                // We may not yet have parsed the package, so just see if
9055                // we still know about its settings.
9056                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9057            }
9058            if (bp.packageSetting == null) {
9059                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9060                        + " from package " + bp.sourcePackage);
9061                it.remove();
9062            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9063                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9064                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9065                            + " from package " + bp.sourcePackage);
9066                    flags |= UPDATE_PERMISSIONS_ALL;
9067                    it.remove();
9068                }
9069            }
9070        }
9071
9072        // Make sure all dynamic permissions have been assigned to a package,
9073        // and make sure there are no dangling permissions.
9074        it = mSettings.mPermissions.values().iterator();
9075        while (it.hasNext()) {
9076            final BasePermission bp = it.next();
9077            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9078                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9079                        + bp.name + " pkg=" + bp.sourcePackage
9080                        + " info=" + bp.pendingInfo);
9081                if (bp.packageSetting == null && bp.pendingInfo != null) {
9082                    final BasePermission tree = findPermissionTreeLP(bp.name);
9083                    if (tree != null && tree.perm != null) {
9084                        bp.packageSetting = tree.packageSetting;
9085                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9086                                new PermissionInfo(bp.pendingInfo));
9087                        bp.perm.info.packageName = tree.perm.info.packageName;
9088                        bp.perm.info.name = bp.name;
9089                        bp.uid = tree.uid;
9090                    }
9091                }
9092            }
9093            if (bp.packageSetting == null) {
9094                // We may not yet have parsed the package, so just see if
9095                // we still know about its settings.
9096                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9097            }
9098            if (bp.packageSetting == null) {
9099                Slog.w(TAG, "Removing dangling permission: " + bp.name
9100                        + " from package " + bp.sourcePackage);
9101                it.remove();
9102            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9103                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9104                    Slog.i(TAG, "Removing old permission: " + bp.name
9105                            + " from package " + bp.sourcePackage);
9106                    flags |= UPDATE_PERMISSIONS_ALL;
9107                    it.remove();
9108                }
9109            }
9110        }
9111
9112        // Now update the permissions for all packages, in particular
9113        // replace the granted permissions of the system packages.
9114        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9115            for (PackageParser.Package pkg : mPackages.values()) {
9116                if (pkg != pkgInfo) {
9117                    // Only replace for packages on requested volume
9118                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9119                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9120                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9121                    grantPermissionsLPw(pkg, replace, changingPkg);
9122                }
9123            }
9124        }
9125
9126        if (pkgInfo != null) {
9127            // Only replace for packages on requested volume
9128            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9129            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9130                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9131            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9132        }
9133    }
9134
9135    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9136            String packageOfInterest) {
9137        // IMPORTANT: There are two types of permissions: install and runtime.
9138        // Install time permissions are granted when the app is installed to
9139        // all device users and users added in the future. Runtime permissions
9140        // are granted at runtime explicitly to specific users. Normal and signature
9141        // protected permissions are install time permissions. Dangerous permissions
9142        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9143        // otherwise they are runtime permissions. This function does not manage
9144        // runtime permissions except for the case an app targeting Lollipop MR1
9145        // being upgraded to target a newer SDK, in which case dangerous permissions
9146        // are transformed from install time to runtime ones.
9147
9148        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9149        if (ps == null) {
9150            return;
9151        }
9152
9153        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9154
9155        PermissionsState permissionsState = ps.getPermissionsState();
9156        PermissionsState origPermissions = permissionsState;
9157
9158        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9159
9160        boolean runtimePermissionsRevoked = false;
9161        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9162
9163        boolean changedInstallPermission = false;
9164
9165        if (replace) {
9166            ps.installPermissionsFixed = false;
9167            if (!ps.isSharedUser()) {
9168                origPermissions = new PermissionsState(permissionsState);
9169                permissionsState.reset();
9170            } else {
9171                // We need to know only about runtime permission changes since the
9172                // calling code always writes the install permissions state but
9173                // the runtime ones are written only if changed. The only cases of
9174                // changed runtime permissions here are promotion of an install to
9175                // runtime and revocation of a runtime from a shared user.
9176                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9177                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9178                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9179                    runtimePermissionsRevoked = true;
9180                }
9181            }
9182        }
9183
9184        permissionsState.setGlobalGids(mGlobalGids);
9185
9186        final int N = pkg.requestedPermissions.size();
9187        for (int i=0; i<N; i++) {
9188            final String name = pkg.requestedPermissions.get(i);
9189            final BasePermission bp = mSettings.mPermissions.get(name);
9190
9191            if (DEBUG_INSTALL) {
9192                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9193            }
9194
9195            if (bp == null || bp.packageSetting == null) {
9196                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9197                    Slog.w(TAG, "Unknown permission " + name
9198                            + " in package " + pkg.packageName);
9199                }
9200                continue;
9201            }
9202
9203            final String perm = bp.name;
9204            boolean allowedSig = false;
9205            int grant = GRANT_DENIED;
9206
9207            // Keep track of app op permissions.
9208            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9209                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9210                if (pkgs == null) {
9211                    pkgs = new ArraySet<>();
9212                    mAppOpPermissionPackages.put(bp.name, pkgs);
9213                }
9214                pkgs.add(pkg.packageName);
9215            }
9216
9217            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9218            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9219                    >= Build.VERSION_CODES.M;
9220            switch (level) {
9221                case PermissionInfo.PROTECTION_NORMAL: {
9222                    // For all apps normal permissions are install time ones.
9223                    grant = GRANT_INSTALL;
9224                } break;
9225
9226                case PermissionInfo.PROTECTION_DANGEROUS: {
9227                    // If a permission review is required for legacy apps we represent
9228                    // their permissions as always granted runtime ones since we need
9229                    // to keep the review required permission flag per user while an
9230                    // install permission's state is shared across all users.
9231                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9232                        // For legacy apps dangerous permissions are install time ones.
9233                        grant = GRANT_INSTALL;
9234                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9235                        // For legacy apps that became modern, install becomes runtime.
9236                        grant = GRANT_UPGRADE;
9237                    } else if (mPromoteSystemApps
9238                            && isSystemApp(ps)
9239                            && mExistingSystemPackages.contains(ps.name)) {
9240                        // For legacy system apps, install becomes runtime.
9241                        // We cannot check hasInstallPermission() for system apps since those
9242                        // permissions were granted implicitly and not persisted pre-M.
9243                        grant = GRANT_UPGRADE;
9244                    } else {
9245                        // For modern apps keep runtime permissions unchanged.
9246                        grant = GRANT_RUNTIME;
9247                    }
9248                } break;
9249
9250                case PermissionInfo.PROTECTION_SIGNATURE: {
9251                    // For all apps signature permissions are install time ones.
9252                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9253                    if (allowedSig) {
9254                        grant = GRANT_INSTALL;
9255                    }
9256                } break;
9257            }
9258
9259            if (DEBUG_INSTALL) {
9260                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9261            }
9262
9263            if (grant != GRANT_DENIED) {
9264                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9265                    // If this is an existing, non-system package, then
9266                    // we can't add any new permissions to it.
9267                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9268                        // Except...  if this is a permission that was added
9269                        // to the platform (note: need to only do this when
9270                        // updating the platform).
9271                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9272                            grant = GRANT_DENIED;
9273                        }
9274                    }
9275                }
9276
9277                switch (grant) {
9278                    case GRANT_INSTALL: {
9279                        // Revoke this as runtime permission to handle the case of
9280                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9281                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9282                            if (origPermissions.getRuntimePermissionState(
9283                                    bp.name, userId) != null) {
9284                                // Revoke the runtime permission and clear the flags.
9285                                origPermissions.revokeRuntimePermission(bp, userId);
9286                                origPermissions.updatePermissionFlags(bp, userId,
9287                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9288                                // If we revoked a permission permission, we have to write.
9289                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9290                                        changedRuntimePermissionUserIds, userId);
9291                            }
9292                        }
9293                        // Grant an install permission.
9294                        if (permissionsState.grantInstallPermission(bp) !=
9295                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9296                            changedInstallPermission = true;
9297                        }
9298                    } break;
9299
9300                    case GRANT_RUNTIME: {
9301                        // Grant previously granted runtime permissions.
9302                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9303                            PermissionState permissionState = origPermissions
9304                                    .getRuntimePermissionState(bp.name, userId);
9305                            int flags = permissionState != null
9306                                    ? permissionState.getFlags() : 0;
9307                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9308                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9309                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9310                                    // If we cannot put the permission as it was, we have to write.
9311                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9312                                            changedRuntimePermissionUserIds, userId);
9313                                }
9314                                // If the app supports runtime permissions no need for a review.
9315                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9316                                        && appSupportsRuntimePermissions
9317                                        && (flags & PackageManager
9318                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9319                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9320                                    // Since we changed the flags, we have to write.
9321                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9322                                            changedRuntimePermissionUserIds, userId);
9323                                }
9324                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9325                                    && !appSupportsRuntimePermissions) {
9326                                // For legacy apps that need a permission review, every new
9327                                // runtime permission is granted but it is pending a review.
9328                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9329                                    permissionsState.grantRuntimePermission(bp, userId);
9330                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9331                                    // We changed the permission and flags, hence have to write.
9332                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9333                                            changedRuntimePermissionUserIds, userId);
9334                                }
9335                            }
9336                            // Propagate the permission flags.
9337                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9338                        }
9339                    } break;
9340
9341                    case GRANT_UPGRADE: {
9342                        // Grant runtime permissions for a previously held install permission.
9343                        PermissionState permissionState = origPermissions
9344                                .getInstallPermissionState(bp.name);
9345                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9346
9347                        if (origPermissions.revokeInstallPermission(bp)
9348                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9349                            // We will be transferring the permission flags, so clear them.
9350                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9351                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9352                            changedInstallPermission = true;
9353                        }
9354
9355                        // If the permission is not to be promoted to runtime we ignore it and
9356                        // also its other flags as they are not applicable to install permissions.
9357                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9358                            for (int userId : currentUserIds) {
9359                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9360                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9361                                    // Transfer the permission flags.
9362                                    permissionsState.updatePermissionFlags(bp, userId,
9363                                            flags, flags);
9364                                    // If we granted the permission, we have to write.
9365                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9366                                            changedRuntimePermissionUserIds, userId);
9367                                }
9368                            }
9369                        }
9370                    } break;
9371
9372                    default: {
9373                        if (packageOfInterest == null
9374                                || packageOfInterest.equals(pkg.packageName)) {
9375                            Slog.w(TAG, "Not granting permission " + perm
9376                                    + " to package " + pkg.packageName
9377                                    + " because it was previously installed without");
9378                        }
9379                    } break;
9380                }
9381            } else {
9382                if (permissionsState.revokeInstallPermission(bp) !=
9383                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9384                    // Also drop the permission flags.
9385                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9386                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9387                    changedInstallPermission = true;
9388                    Slog.i(TAG, "Un-granting permission " + perm
9389                            + " from package " + pkg.packageName
9390                            + " (protectionLevel=" + bp.protectionLevel
9391                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9392                            + ")");
9393                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9394                    // Don't print warning for app op permissions, since it is fine for them
9395                    // not to be granted, there is a UI for the user to decide.
9396                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9397                        Slog.w(TAG, "Not granting permission " + perm
9398                                + " to package " + pkg.packageName
9399                                + " (protectionLevel=" + bp.protectionLevel
9400                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9401                                + ")");
9402                    }
9403                }
9404            }
9405        }
9406
9407        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9408                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9409            // This is the first that we have heard about this package, so the
9410            // permissions we have now selected are fixed until explicitly
9411            // changed.
9412            ps.installPermissionsFixed = true;
9413        }
9414
9415        // Persist the runtime permissions state for users with changes. If permissions
9416        // were revoked because no app in the shared user declares them we have to
9417        // write synchronously to avoid losing runtime permissions state.
9418        for (int userId : changedRuntimePermissionUserIds) {
9419            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9420        }
9421
9422        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9423    }
9424
9425    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9426        boolean allowed = false;
9427        final int NP = PackageParser.NEW_PERMISSIONS.length;
9428        for (int ip=0; ip<NP; ip++) {
9429            final PackageParser.NewPermissionInfo npi
9430                    = PackageParser.NEW_PERMISSIONS[ip];
9431            if (npi.name.equals(perm)
9432                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9433                allowed = true;
9434                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9435                        + pkg.packageName);
9436                break;
9437            }
9438        }
9439        return allowed;
9440    }
9441
9442    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9443            BasePermission bp, PermissionsState origPermissions) {
9444        boolean allowed;
9445        allowed = (compareSignatures(
9446                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9447                        == PackageManager.SIGNATURE_MATCH)
9448                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9449                        == PackageManager.SIGNATURE_MATCH);
9450        if (!allowed && (bp.protectionLevel
9451                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9452            if (isSystemApp(pkg)) {
9453                // For updated system applications, a system permission
9454                // is granted only if it had been defined by the original application.
9455                if (pkg.isUpdatedSystemApp()) {
9456                    final PackageSetting sysPs = mSettings
9457                            .getDisabledSystemPkgLPr(pkg.packageName);
9458                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9459                        // If the original was granted this permission, we take
9460                        // that grant decision as read and propagate it to the
9461                        // update.
9462                        if (sysPs.isPrivileged()) {
9463                            allowed = true;
9464                        }
9465                    } else {
9466                        // The system apk may have been updated with an older
9467                        // version of the one on the data partition, but which
9468                        // granted a new system permission that it didn't have
9469                        // before.  In this case we do want to allow the app to
9470                        // now get the new permission if the ancestral apk is
9471                        // privileged to get it.
9472                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9473                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9474                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9475                                    allowed = true;
9476                                    break;
9477                                }
9478                            }
9479                        }
9480                        // Also if a privileged parent package on the system image or any of
9481                        // its children requested a privileged permission, the updated child
9482                        // packages can also get the permission.
9483                        if (pkg.parentPackage != null) {
9484                            final PackageSetting disabledSysParentPs = mSettings
9485                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9486                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9487                                    && disabledSysParentPs.isPrivileged()) {
9488                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9489                                    allowed = true;
9490                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9491                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9492                                    for (int i = 0; i < count; i++) {
9493                                        PackageParser.Package disabledSysChildPkg =
9494                                                disabledSysParentPs.pkg.childPackages.get(i);
9495                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9496                                                perm)) {
9497                                            allowed = true;
9498                                            break;
9499                                        }
9500                                    }
9501                                }
9502                            }
9503                        }
9504                    }
9505                } else {
9506                    allowed = isPrivilegedApp(pkg);
9507                }
9508            }
9509        }
9510        if (!allowed) {
9511            if (!allowed && (bp.protectionLevel
9512                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9513                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9514                // If this was a previously normal/dangerous permission that got moved
9515                // to a system permission as part of the runtime permission redesign, then
9516                // we still want to blindly grant it to old apps.
9517                allowed = true;
9518            }
9519            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9520                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9521                // If this permission is to be granted to the system installer and
9522                // this app is an installer, then it gets the permission.
9523                allowed = true;
9524            }
9525            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9526                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9527                // If this permission is to be granted to the system verifier and
9528                // this app is a verifier, then it gets the permission.
9529                allowed = true;
9530            }
9531            if (!allowed && (bp.protectionLevel
9532                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9533                    && isSystemApp(pkg)) {
9534                // Any pre-installed system app is allowed to get this permission.
9535                allowed = true;
9536            }
9537            if (!allowed && (bp.protectionLevel
9538                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9539                // For development permissions, a development permission
9540                // is granted only if it was already granted.
9541                allowed = origPermissions.hasInstallPermission(perm);
9542            }
9543        }
9544        return allowed;
9545    }
9546
9547    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9548        final int permCount = pkg.requestedPermissions.size();
9549        for (int j = 0; j < permCount; j++) {
9550            String requestedPermission = pkg.requestedPermissions.get(j);
9551            if (permission.equals(requestedPermission)) {
9552                return true;
9553            }
9554        }
9555        return false;
9556    }
9557
9558    final class ActivityIntentResolver
9559            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9560        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9561                boolean defaultOnly, int userId) {
9562            if (!sUserManager.exists(userId)) return null;
9563            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9564            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9565        }
9566
9567        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9568                int userId) {
9569            if (!sUserManager.exists(userId)) return null;
9570            mFlags = flags;
9571            return super.queryIntent(intent, resolvedType,
9572                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9573        }
9574
9575        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9576                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9577            if (!sUserManager.exists(userId)) return null;
9578            if (packageActivities == null) {
9579                return null;
9580            }
9581            mFlags = flags;
9582            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9583            final int N = packageActivities.size();
9584            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9585                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9586
9587            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9588            for (int i = 0; i < N; ++i) {
9589                intentFilters = packageActivities.get(i).intents;
9590                if (intentFilters != null && intentFilters.size() > 0) {
9591                    PackageParser.ActivityIntentInfo[] array =
9592                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9593                    intentFilters.toArray(array);
9594                    listCut.add(array);
9595                }
9596            }
9597            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9598        }
9599
9600        public final void addActivity(PackageParser.Activity a, String type) {
9601            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9602            mActivities.put(a.getComponentName(), a);
9603            if (DEBUG_SHOW_INFO)
9604                Log.v(
9605                TAG, "  " + type + " " +
9606                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9607            if (DEBUG_SHOW_INFO)
9608                Log.v(TAG, "    Class=" + a.info.name);
9609            final int NI = a.intents.size();
9610            for (int j=0; j<NI; j++) {
9611                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9612                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9613                    intent.setPriority(0);
9614                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9615                            + a.className + " with priority > 0, forcing to 0");
9616                }
9617                if (DEBUG_SHOW_INFO) {
9618                    Log.v(TAG, "    IntentFilter:");
9619                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9620                }
9621                if (!intent.debugCheck()) {
9622                    Log.w(TAG, "==> For Activity " + a.info.name);
9623                }
9624                addFilter(intent);
9625            }
9626        }
9627
9628        public final void removeActivity(PackageParser.Activity a, String type) {
9629            mActivities.remove(a.getComponentName());
9630            if (DEBUG_SHOW_INFO) {
9631                Log.v(TAG, "  " + type + " "
9632                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9633                                : a.info.name) + ":");
9634                Log.v(TAG, "    Class=" + a.info.name);
9635            }
9636            final int NI = a.intents.size();
9637            for (int j=0; j<NI; j++) {
9638                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9639                if (DEBUG_SHOW_INFO) {
9640                    Log.v(TAG, "    IntentFilter:");
9641                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9642                }
9643                removeFilter(intent);
9644            }
9645        }
9646
9647        @Override
9648        protected boolean allowFilterResult(
9649                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9650            ActivityInfo filterAi = filter.activity.info;
9651            for (int i=dest.size()-1; i>=0; i--) {
9652                ActivityInfo destAi = dest.get(i).activityInfo;
9653                if (destAi.name == filterAi.name
9654                        && destAi.packageName == filterAi.packageName) {
9655                    return false;
9656                }
9657            }
9658            return true;
9659        }
9660
9661        @Override
9662        protected ActivityIntentInfo[] newArray(int size) {
9663            return new ActivityIntentInfo[size];
9664        }
9665
9666        @Override
9667        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9668            if (!sUserManager.exists(userId)) return true;
9669            PackageParser.Package p = filter.activity.owner;
9670            if (p != null) {
9671                PackageSetting ps = (PackageSetting)p.mExtras;
9672                if (ps != null) {
9673                    // System apps are never considered stopped for purposes of
9674                    // filtering, because there may be no way for the user to
9675                    // actually re-launch them.
9676                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9677                            && ps.getStopped(userId);
9678                }
9679            }
9680            return false;
9681        }
9682
9683        @Override
9684        protected boolean isPackageForFilter(String packageName,
9685                PackageParser.ActivityIntentInfo info) {
9686            return packageName.equals(info.activity.owner.packageName);
9687        }
9688
9689        @Override
9690        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9691                int match, int userId) {
9692            if (!sUserManager.exists(userId)) return null;
9693            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9694                return null;
9695            }
9696            final PackageParser.Activity activity = info.activity;
9697            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9698            if (ps == null) {
9699                return null;
9700            }
9701            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9702                    ps.readUserState(userId), userId);
9703            if (ai == null) {
9704                return null;
9705            }
9706            final ResolveInfo res = new ResolveInfo();
9707            res.activityInfo = ai;
9708            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9709                res.filter = info;
9710            }
9711            if (info != null) {
9712                res.handleAllWebDataURI = info.handleAllWebDataURI();
9713            }
9714            res.priority = info.getPriority();
9715            res.preferredOrder = activity.owner.mPreferredOrder;
9716            //System.out.println("Result: " + res.activityInfo.className +
9717            //                   " = " + res.priority);
9718            res.match = match;
9719            res.isDefault = info.hasDefault;
9720            res.labelRes = info.labelRes;
9721            res.nonLocalizedLabel = info.nonLocalizedLabel;
9722            if (userNeedsBadging(userId)) {
9723                res.noResourceId = true;
9724            } else {
9725                res.icon = info.icon;
9726            }
9727            res.iconResourceId = info.icon;
9728            res.system = res.activityInfo.applicationInfo.isSystemApp();
9729            return res;
9730        }
9731
9732        @Override
9733        protected void sortResults(List<ResolveInfo> results) {
9734            Collections.sort(results, mResolvePrioritySorter);
9735        }
9736
9737        @Override
9738        protected void dumpFilter(PrintWriter out, String prefix,
9739                PackageParser.ActivityIntentInfo filter) {
9740            out.print(prefix); out.print(
9741                    Integer.toHexString(System.identityHashCode(filter.activity)));
9742                    out.print(' ');
9743                    filter.activity.printComponentShortName(out);
9744                    out.print(" filter ");
9745                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9746        }
9747
9748        @Override
9749        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9750            return filter.activity;
9751        }
9752
9753        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9754            PackageParser.Activity activity = (PackageParser.Activity)label;
9755            out.print(prefix); out.print(
9756                    Integer.toHexString(System.identityHashCode(activity)));
9757                    out.print(' ');
9758                    activity.printComponentShortName(out);
9759            if (count > 1) {
9760                out.print(" ("); out.print(count); out.print(" filters)");
9761            }
9762            out.println();
9763        }
9764
9765//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9766//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9767//            final List<ResolveInfo> retList = Lists.newArrayList();
9768//            while (i.hasNext()) {
9769//                final ResolveInfo resolveInfo = i.next();
9770//                if (isEnabledLP(resolveInfo.activityInfo)) {
9771//                    retList.add(resolveInfo);
9772//                }
9773//            }
9774//            return retList;
9775//        }
9776
9777        // Keys are String (activity class name), values are Activity.
9778        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9779                = new ArrayMap<ComponentName, PackageParser.Activity>();
9780        private int mFlags;
9781    }
9782
9783    private final class ServiceIntentResolver
9784            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9785        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9786                boolean defaultOnly, int userId) {
9787            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9788            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9789        }
9790
9791        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9792                int userId) {
9793            if (!sUserManager.exists(userId)) return null;
9794            mFlags = flags;
9795            return super.queryIntent(intent, resolvedType,
9796                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9797        }
9798
9799        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9800                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9801            if (!sUserManager.exists(userId)) return null;
9802            if (packageServices == null) {
9803                return null;
9804            }
9805            mFlags = flags;
9806            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9807            final int N = packageServices.size();
9808            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9809                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9810
9811            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9812            for (int i = 0; i < N; ++i) {
9813                intentFilters = packageServices.get(i).intents;
9814                if (intentFilters != null && intentFilters.size() > 0) {
9815                    PackageParser.ServiceIntentInfo[] array =
9816                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9817                    intentFilters.toArray(array);
9818                    listCut.add(array);
9819                }
9820            }
9821            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9822        }
9823
9824        public final void addService(PackageParser.Service s) {
9825            mServices.put(s.getComponentName(), s);
9826            if (DEBUG_SHOW_INFO) {
9827                Log.v(TAG, "  "
9828                        + (s.info.nonLocalizedLabel != null
9829                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9830                Log.v(TAG, "    Class=" + s.info.name);
9831            }
9832            final int NI = s.intents.size();
9833            int j;
9834            for (j=0; j<NI; j++) {
9835                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9836                if (DEBUG_SHOW_INFO) {
9837                    Log.v(TAG, "    IntentFilter:");
9838                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9839                }
9840                if (!intent.debugCheck()) {
9841                    Log.w(TAG, "==> For Service " + s.info.name);
9842                }
9843                addFilter(intent);
9844            }
9845        }
9846
9847        public final void removeService(PackageParser.Service s) {
9848            mServices.remove(s.getComponentName());
9849            if (DEBUG_SHOW_INFO) {
9850                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9851                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9852                Log.v(TAG, "    Class=" + s.info.name);
9853            }
9854            final int NI = s.intents.size();
9855            int j;
9856            for (j=0; j<NI; j++) {
9857                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9858                if (DEBUG_SHOW_INFO) {
9859                    Log.v(TAG, "    IntentFilter:");
9860                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9861                }
9862                removeFilter(intent);
9863            }
9864        }
9865
9866        @Override
9867        protected boolean allowFilterResult(
9868                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9869            ServiceInfo filterSi = filter.service.info;
9870            for (int i=dest.size()-1; i>=0; i--) {
9871                ServiceInfo destAi = dest.get(i).serviceInfo;
9872                if (destAi.name == filterSi.name
9873                        && destAi.packageName == filterSi.packageName) {
9874                    return false;
9875                }
9876            }
9877            return true;
9878        }
9879
9880        @Override
9881        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9882            return new PackageParser.ServiceIntentInfo[size];
9883        }
9884
9885        @Override
9886        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9887            if (!sUserManager.exists(userId)) return true;
9888            PackageParser.Package p = filter.service.owner;
9889            if (p != null) {
9890                PackageSetting ps = (PackageSetting)p.mExtras;
9891                if (ps != null) {
9892                    // System apps are never considered stopped for purposes of
9893                    // filtering, because there may be no way for the user to
9894                    // actually re-launch them.
9895                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9896                            && ps.getStopped(userId);
9897                }
9898            }
9899            return false;
9900        }
9901
9902        @Override
9903        protected boolean isPackageForFilter(String packageName,
9904                PackageParser.ServiceIntentInfo info) {
9905            return packageName.equals(info.service.owner.packageName);
9906        }
9907
9908        @Override
9909        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9910                int match, int userId) {
9911            if (!sUserManager.exists(userId)) return null;
9912            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9913            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9914                return null;
9915            }
9916            final PackageParser.Service service = info.service;
9917            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9918            if (ps == null) {
9919                return null;
9920            }
9921            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9922                    ps.readUserState(userId), userId);
9923            if (si == null) {
9924                return null;
9925            }
9926            final ResolveInfo res = new ResolveInfo();
9927            res.serviceInfo = si;
9928            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9929                res.filter = filter;
9930            }
9931            res.priority = info.getPriority();
9932            res.preferredOrder = service.owner.mPreferredOrder;
9933            res.match = match;
9934            res.isDefault = info.hasDefault;
9935            res.labelRes = info.labelRes;
9936            res.nonLocalizedLabel = info.nonLocalizedLabel;
9937            res.icon = info.icon;
9938            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9939            return res;
9940        }
9941
9942        @Override
9943        protected void sortResults(List<ResolveInfo> results) {
9944            Collections.sort(results, mResolvePrioritySorter);
9945        }
9946
9947        @Override
9948        protected void dumpFilter(PrintWriter out, String prefix,
9949                PackageParser.ServiceIntentInfo filter) {
9950            out.print(prefix); out.print(
9951                    Integer.toHexString(System.identityHashCode(filter.service)));
9952                    out.print(' ');
9953                    filter.service.printComponentShortName(out);
9954                    out.print(" filter ");
9955                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9956        }
9957
9958        @Override
9959        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9960            return filter.service;
9961        }
9962
9963        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9964            PackageParser.Service service = (PackageParser.Service)label;
9965            out.print(prefix); out.print(
9966                    Integer.toHexString(System.identityHashCode(service)));
9967                    out.print(' ');
9968                    service.printComponentShortName(out);
9969            if (count > 1) {
9970                out.print(" ("); out.print(count); out.print(" filters)");
9971            }
9972            out.println();
9973        }
9974
9975//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9976//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9977//            final List<ResolveInfo> retList = Lists.newArrayList();
9978//            while (i.hasNext()) {
9979//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9980//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9981//                    retList.add(resolveInfo);
9982//                }
9983//            }
9984//            return retList;
9985//        }
9986
9987        // Keys are String (activity class name), values are Activity.
9988        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9989                = new ArrayMap<ComponentName, PackageParser.Service>();
9990        private int mFlags;
9991    };
9992
9993    private final class ProviderIntentResolver
9994            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9995        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9996                boolean defaultOnly, int userId) {
9997            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9998            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9999        }
10000
10001        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10002                int userId) {
10003            if (!sUserManager.exists(userId))
10004                return null;
10005            mFlags = flags;
10006            return super.queryIntent(intent, resolvedType,
10007                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10008        }
10009
10010        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10011                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10012            if (!sUserManager.exists(userId))
10013                return null;
10014            if (packageProviders == null) {
10015                return null;
10016            }
10017            mFlags = flags;
10018            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10019            final int N = packageProviders.size();
10020            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10021                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10022
10023            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10024            for (int i = 0; i < N; ++i) {
10025                intentFilters = packageProviders.get(i).intents;
10026                if (intentFilters != null && intentFilters.size() > 0) {
10027                    PackageParser.ProviderIntentInfo[] array =
10028                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10029                    intentFilters.toArray(array);
10030                    listCut.add(array);
10031                }
10032            }
10033            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10034        }
10035
10036        public final void addProvider(PackageParser.Provider p) {
10037            if (mProviders.containsKey(p.getComponentName())) {
10038                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10039                return;
10040            }
10041
10042            mProviders.put(p.getComponentName(), p);
10043            if (DEBUG_SHOW_INFO) {
10044                Log.v(TAG, "  "
10045                        + (p.info.nonLocalizedLabel != null
10046                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10047                Log.v(TAG, "    Class=" + p.info.name);
10048            }
10049            final int NI = p.intents.size();
10050            int j;
10051            for (j = 0; j < NI; j++) {
10052                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10053                if (DEBUG_SHOW_INFO) {
10054                    Log.v(TAG, "    IntentFilter:");
10055                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10056                }
10057                if (!intent.debugCheck()) {
10058                    Log.w(TAG, "==> For Provider " + p.info.name);
10059                }
10060                addFilter(intent);
10061            }
10062        }
10063
10064        public final void removeProvider(PackageParser.Provider p) {
10065            mProviders.remove(p.getComponentName());
10066            if (DEBUG_SHOW_INFO) {
10067                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10068                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10069                Log.v(TAG, "    Class=" + p.info.name);
10070            }
10071            final int NI = p.intents.size();
10072            int j;
10073            for (j = 0; j < NI; j++) {
10074                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10075                if (DEBUG_SHOW_INFO) {
10076                    Log.v(TAG, "    IntentFilter:");
10077                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10078                }
10079                removeFilter(intent);
10080            }
10081        }
10082
10083        @Override
10084        protected boolean allowFilterResult(
10085                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10086            ProviderInfo filterPi = filter.provider.info;
10087            for (int i = dest.size() - 1; i >= 0; i--) {
10088                ProviderInfo destPi = dest.get(i).providerInfo;
10089                if (destPi.name == filterPi.name
10090                        && destPi.packageName == filterPi.packageName) {
10091                    return false;
10092                }
10093            }
10094            return true;
10095        }
10096
10097        @Override
10098        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10099            return new PackageParser.ProviderIntentInfo[size];
10100        }
10101
10102        @Override
10103        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10104            if (!sUserManager.exists(userId))
10105                return true;
10106            PackageParser.Package p = filter.provider.owner;
10107            if (p != null) {
10108                PackageSetting ps = (PackageSetting) p.mExtras;
10109                if (ps != null) {
10110                    // System apps are never considered stopped for purposes of
10111                    // filtering, because there may be no way for the user to
10112                    // actually re-launch them.
10113                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10114                            && ps.getStopped(userId);
10115                }
10116            }
10117            return false;
10118        }
10119
10120        @Override
10121        protected boolean isPackageForFilter(String packageName,
10122                PackageParser.ProviderIntentInfo info) {
10123            return packageName.equals(info.provider.owner.packageName);
10124        }
10125
10126        @Override
10127        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10128                int match, int userId) {
10129            if (!sUserManager.exists(userId))
10130                return null;
10131            final PackageParser.ProviderIntentInfo info = filter;
10132            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10133                return null;
10134            }
10135            final PackageParser.Provider provider = info.provider;
10136            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10137            if (ps == null) {
10138                return null;
10139            }
10140            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10141                    ps.readUserState(userId), userId);
10142            if (pi == null) {
10143                return null;
10144            }
10145            final ResolveInfo res = new ResolveInfo();
10146            res.providerInfo = pi;
10147            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10148                res.filter = filter;
10149            }
10150            res.priority = info.getPriority();
10151            res.preferredOrder = provider.owner.mPreferredOrder;
10152            res.match = match;
10153            res.isDefault = info.hasDefault;
10154            res.labelRes = info.labelRes;
10155            res.nonLocalizedLabel = info.nonLocalizedLabel;
10156            res.icon = info.icon;
10157            res.system = res.providerInfo.applicationInfo.isSystemApp();
10158            return res;
10159        }
10160
10161        @Override
10162        protected void sortResults(List<ResolveInfo> results) {
10163            Collections.sort(results, mResolvePrioritySorter);
10164        }
10165
10166        @Override
10167        protected void dumpFilter(PrintWriter out, String prefix,
10168                PackageParser.ProviderIntentInfo filter) {
10169            out.print(prefix);
10170            out.print(
10171                    Integer.toHexString(System.identityHashCode(filter.provider)));
10172            out.print(' ');
10173            filter.provider.printComponentShortName(out);
10174            out.print(" filter ");
10175            out.println(Integer.toHexString(System.identityHashCode(filter)));
10176        }
10177
10178        @Override
10179        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10180            return filter.provider;
10181        }
10182
10183        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10184            PackageParser.Provider provider = (PackageParser.Provider)label;
10185            out.print(prefix); out.print(
10186                    Integer.toHexString(System.identityHashCode(provider)));
10187                    out.print(' ');
10188                    provider.printComponentShortName(out);
10189            if (count > 1) {
10190                out.print(" ("); out.print(count); out.print(" filters)");
10191            }
10192            out.println();
10193        }
10194
10195        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10196                = new ArrayMap<ComponentName, PackageParser.Provider>();
10197        private int mFlags;
10198    }
10199
10200    private static final class EphemeralIntentResolver
10201            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10202        @Override
10203        protected EphemeralResolveIntentInfo[] newArray(int size) {
10204            return new EphemeralResolveIntentInfo[size];
10205        }
10206
10207        @Override
10208        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10209            return true;
10210        }
10211
10212        @Override
10213        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10214                int userId) {
10215            if (!sUserManager.exists(userId)) {
10216                return null;
10217            }
10218            return info.getEphemeralResolveInfo();
10219        }
10220    }
10221
10222    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10223            new Comparator<ResolveInfo>() {
10224        public int compare(ResolveInfo r1, ResolveInfo r2) {
10225            int v1 = r1.priority;
10226            int v2 = r2.priority;
10227            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10228            if (v1 != v2) {
10229                return (v1 > v2) ? -1 : 1;
10230            }
10231            v1 = r1.preferredOrder;
10232            v2 = r2.preferredOrder;
10233            if (v1 != v2) {
10234                return (v1 > v2) ? -1 : 1;
10235            }
10236            if (r1.isDefault != r2.isDefault) {
10237                return r1.isDefault ? -1 : 1;
10238            }
10239            v1 = r1.match;
10240            v2 = r2.match;
10241            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10242            if (v1 != v2) {
10243                return (v1 > v2) ? -1 : 1;
10244            }
10245            if (r1.system != r2.system) {
10246                return r1.system ? -1 : 1;
10247            }
10248            if (r1.activityInfo != null) {
10249                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10250            }
10251            if (r1.serviceInfo != null) {
10252                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10253            }
10254            if (r1.providerInfo != null) {
10255                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10256            }
10257            return 0;
10258        }
10259    };
10260
10261    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10262            new Comparator<ProviderInfo>() {
10263        public int compare(ProviderInfo p1, ProviderInfo p2) {
10264            final int v1 = p1.initOrder;
10265            final int v2 = p2.initOrder;
10266            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10267        }
10268    };
10269
10270    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10271            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10272            final int[] userIds) {
10273        mHandler.post(new Runnable() {
10274            @Override
10275            public void run() {
10276                try {
10277                    final IActivityManager am = ActivityManagerNative.getDefault();
10278                    if (am == null) return;
10279                    final int[] resolvedUserIds;
10280                    if (userIds == null) {
10281                        resolvedUserIds = am.getRunningUserIds();
10282                    } else {
10283                        resolvedUserIds = userIds;
10284                    }
10285                    for (int id : resolvedUserIds) {
10286                        final Intent intent = new Intent(action,
10287                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10288                        if (extras != null) {
10289                            intent.putExtras(extras);
10290                        }
10291                        if (targetPkg != null) {
10292                            intent.setPackage(targetPkg);
10293                        }
10294                        // Modify the UID when posting to other users
10295                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10296                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10297                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10298                            intent.putExtra(Intent.EXTRA_UID, uid);
10299                        }
10300                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10301                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10302                        if (DEBUG_BROADCASTS) {
10303                            RuntimeException here = new RuntimeException("here");
10304                            here.fillInStackTrace();
10305                            Slog.d(TAG, "Sending to user " + id + ": "
10306                                    + intent.toShortString(false, true, false, false)
10307                                    + " " + intent.getExtras(), here);
10308                        }
10309                        am.broadcastIntent(null, intent, null, finishedReceiver,
10310                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10311                                null, finishedReceiver != null, false, id);
10312                    }
10313                } catch (RemoteException ex) {
10314                }
10315            }
10316        });
10317    }
10318
10319    /**
10320     * Check if the external storage media is available. This is true if there
10321     * is a mounted external storage medium or if the external storage is
10322     * emulated.
10323     */
10324    private boolean isExternalMediaAvailable() {
10325        return mMediaMounted || Environment.isExternalStorageEmulated();
10326    }
10327
10328    @Override
10329    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10330        // writer
10331        synchronized (mPackages) {
10332            if (!isExternalMediaAvailable()) {
10333                // If the external storage is no longer mounted at this point,
10334                // the caller may not have been able to delete all of this
10335                // packages files and can not delete any more.  Bail.
10336                return null;
10337            }
10338            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10339            if (lastPackage != null) {
10340                pkgs.remove(lastPackage);
10341            }
10342            if (pkgs.size() > 0) {
10343                return pkgs.get(0);
10344            }
10345        }
10346        return null;
10347    }
10348
10349    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10350        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10351                userId, andCode ? 1 : 0, packageName);
10352        if (mSystemReady) {
10353            msg.sendToTarget();
10354        } else {
10355            if (mPostSystemReadyMessages == null) {
10356                mPostSystemReadyMessages = new ArrayList<>();
10357            }
10358            mPostSystemReadyMessages.add(msg);
10359        }
10360    }
10361
10362    void startCleaningPackages() {
10363        // reader
10364        synchronized (mPackages) {
10365            if (!isExternalMediaAvailable()) {
10366                return;
10367            }
10368            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10369                return;
10370            }
10371        }
10372        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10373        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10374        IActivityManager am = ActivityManagerNative.getDefault();
10375        if (am != null) {
10376            try {
10377                am.startService(null, intent, null, mContext.getOpPackageName(),
10378                        UserHandle.USER_SYSTEM);
10379            } catch (RemoteException e) {
10380            }
10381        }
10382    }
10383
10384    @Override
10385    public void installPackage(String originPath, IPackageInstallObserver2 observer,
10386            int installFlags, String installerPackageName, VerificationParams verificationParams,
10387            String packageAbiOverride) {
10388        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
10389                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
10390    }
10391
10392    @Override
10393    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10394            int installFlags, String installerPackageName, VerificationParams verificationParams,
10395            String packageAbiOverride, int userId) {
10396        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10397
10398        final int callingUid = Binder.getCallingUid();
10399        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10400
10401        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10402            try {
10403                if (observer != null) {
10404                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10405                }
10406            } catch (RemoteException re) {
10407            }
10408            return;
10409        }
10410
10411        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10412            installFlags |= PackageManager.INSTALL_FROM_ADB;
10413
10414        } else {
10415            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10416            // about installerPackageName.
10417
10418            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10419            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10420        }
10421
10422        UserHandle user;
10423        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10424            user = UserHandle.ALL;
10425        } else {
10426            user = new UserHandle(userId);
10427        }
10428
10429        // Only system components can circumvent runtime permissions when installing.
10430        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10431                && mContext.checkCallingOrSelfPermission(Manifest.permission
10432                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10433            throw new SecurityException("You need the "
10434                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10435                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10436        }
10437
10438        verificationParams.setInstallerUid(callingUid);
10439
10440        final File originFile = new File(originPath);
10441        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10442
10443        final Message msg = mHandler.obtainMessage(INIT_COPY);
10444        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10445                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10446        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10447        msg.obj = params;
10448
10449        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10450                System.identityHashCode(msg.obj));
10451        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10452                System.identityHashCode(msg.obj));
10453
10454        mHandler.sendMessage(msg);
10455    }
10456
10457    void installStage(String packageName, File stagedDir, String stagedCid,
10458            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10459            String installerPackageName, int installerUid, UserHandle user) {
10460        if (DEBUG_EPHEMERAL) {
10461            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10462                Slog.d(TAG, "Ephemeral install of " + packageName);
10463            }
10464        }
10465        final VerificationParams verifParams = new VerificationParams(
10466                null, sessionParams.originatingUri, sessionParams.referrerUri,
10467                sessionParams.originatingUid);
10468        verifParams.setInstallerUid(installerUid);
10469
10470        final OriginInfo origin;
10471        if (stagedDir != null) {
10472            origin = OriginInfo.fromStagedFile(stagedDir);
10473        } else {
10474            origin = OriginInfo.fromStagedContainer(stagedCid);
10475        }
10476
10477        final Message msg = mHandler.obtainMessage(INIT_COPY);
10478        final InstallParams params = new InstallParams(origin, null, observer,
10479                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10480                verifParams, user, sessionParams.abiOverride,
10481                sessionParams.grantedRuntimePermissions);
10482        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10483        msg.obj = params;
10484
10485        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10486                System.identityHashCode(msg.obj));
10487        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10488                System.identityHashCode(msg.obj));
10489
10490        mHandler.sendMessage(msg);
10491    }
10492
10493    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10494            int userId) {
10495        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10496        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10497    }
10498
10499    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10500            int appId, int userId) {
10501        Bundle extras = new Bundle(1);
10502        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10503
10504        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10505                packageName, extras, 0, null, null, new int[] {userId});
10506        try {
10507            IActivityManager am = ActivityManagerNative.getDefault();
10508            if (isSystem && am.isUserRunning(userId, 0)) {
10509                // The just-installed/enabled app is bundled on the system, so presumed
10510                // to be able to run automatically without needing an explicit launch.
10511                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10512                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10513                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10514                        .setPackage(packageName);
10515                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10516                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10517            }
10518        } catch (RemoteException e) {
10519            // shouldn't happen
10520            Slog.w(TAG, "Unable to bootstrap installed package", e);
10521        }
10522    }
10523
10524    @Override
10525    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10526            int userId) {
10527        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10528        PackageSetting pkgSetting;
10529        final int uid = Binder.getCallingUid();
10530        enforceCrossUserPermission(uid, userId, true, true,
10531                "setApplicationHiddenSetting for user " + userId);
10532
10533        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10534            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10535            return false;
10536        }
10537
10538        long callingId = Binder.clearCallingIdentity();
10539        try {
10540            boolean sendAdded = false;
10541            boolean sendRemoved = false;
10542            // writer
10543            synchronized (mPackages) {
10544                pkgSetting = mSettings.mPackages.get(packageName);
10545                if (pkgSetting == null) {
10546                    return false;
10547                }
10548                if (pkgSetting.getHidden(userId) != hidden) {
10549                    pkgSetting.setHidden(hidden, userId);
10550                    mSettings.writePackageRestrictionsLPr(userId);
10551                    if (hidden) {
10552                        sendRemoved = true;
10553                    } else {
10554                        sendAdded = true;
10555                    }
10556                }
10557            }
10558            if (sendAdded) {
10559                sendPackageAddedForUser(packageName, pkgSetting, userId);
10560                return true;
10561            }
10562            if (sendRemoved) {
10563                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10564                        "hiding pkg");
10565                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10566                return true;
10567            }
10568        } finally {
10569            Binder.restoreCallingIdentity(callingId);
10570        }
10571        return false;
10572    }
10573
10574    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10575            int userId) {
10576        final PackageRemovedInfo info = new PackageRemovedInfo();
10577        info.removedPackage = packageName;
10578        info.removedUsers = new int[] {userId};
10579        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10580        info.sendPackageRemovedBroadcasts();
10581    }
10582
10583    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10584        if (pkgList.length > 0) {
10585            Bundle extras = new Bundle(1);
10586            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10587
10588            sendPackageBroadcast(
10589                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10590                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10591                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10592                    new int[] {userId});
10593        }
10594    }
10595
10596    /**
10597     * Returns true if application is not found or there was an error. Otherwise it returns
10598     * the hidden state of the package for the given user.
10599     */
10600    @Override
10601    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10602        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10603        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10604                false, "getApplicationHidden for user " + userId);
10605        PackageSetting pkgSetting;
10606        long callingId = Binder.clearCallingIdentity();
10607        try {
10608            // writer
10609            synchronized (mPackages) {
10610                pkgSetting = mSettings.mPackages.get(packageName);
10611                if (pkgSetting == null) {
10612                    return true;
10613                }
10614                return pkgSetting.getHidden(userId);
10615            }
10616        } finally {
10617            Binder.restoreCallingIdentity(callingId);
10618        }
10619    }
10620
10621    /**
10622     * @hide
10623     */
10624    @Override
10625    public int installExistingPackageAsUser(String packageName, int userId) {
10626        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10627                null);
10628        PackageSetting pkgSetting;
10629        final int uid = Binder.getCallingUid();
10630        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10631                + userId);
10632        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10633            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10634        }
10635
10636        long callingId = Binder.clearCallingIdentity();
10637        try {
10638            boolean installed = false;
10639
10640            // writer
10641            synchronized (mPackages) {
10642                pkgSetting = mSettings.mPackages.get(packageName);
10643                if (pkgSetting == null) {
10644                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10645                }
10646                if (!pkgSetting.getInstalled(userId)) {
10647                    pkgSetting.setInstalled(true, userId);
10648                    pkgSetting.setHidden(false, userId);
10649                    mSettings.writePackageRestrictionsLPr(userId);
10650                    if (pkgSetting.pkg != null) {
10651                        prepareAppDataAfterInstall(pkgSetting.pkg);
10652                    }
10653                    installed = true;
10654                }
10655            }
10656
10657            if (installed) {
10658                sendPackageAddedForUser(packageName, pkgSetting, userId);
10659            }
10660        } finally {
10661            Binder.restoreCallingIdentity(callingId);
10662        }
10663
10664        return PackageManager.INSTALL_SUCCEEDED;
10665    }
10666
10667    boolean isUserRestricted(int userId, String restrictionKey) {
10668        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10669        if (restrictions.getBoolean(restrictionKey, false)) {
10670            Log.w(TAG, "User is restricted: " + restrictionKey);
10671            return true;
10672        }
10673        return false;
10674    }
10675
10676    @Override
10677    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
10678            int userId) {
10679        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10680        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10681                "setPackagesSuspended for user " + userId);
10682
10683        if (ArrayUtils.isEmpty(packageNames)) {
10684            return packageNames;
10685        }
10686
10687        // List of package names for whom the suspended state has changed.
10688        List<String> changedPackages = new ArrayList<>(packageNames.length);
10689        // List of package names for whom the suspended state is not set as requested in this
10690        // method.
10691        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
10692        for (int i = 0; i < packageNames.length; i++) {
10693            String packageName = packageNames[i];
10694            long callingId = Binder.clearCallingIdentity();
10695            try {
10696                boolean changed = false;
10697                final int appId;
10698                synchronized (mPackages) {
10699                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10700                    if (pkgSetting == null) {
10701                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
10702                                + "\". Skipping suspending/un-suspending.");
10703                        unactionedPackages.add(packageName);
10704                        continue;
10705                    }
10706                    appId = pkgSetting.appId;
10707                    if (pkgSetting.getSuspended(userId) != suspended) {
10708                        if (!canSuspendPackageForUser(packageName, userId)) {
10709                            unactionedPackages.add(packageName);
10710                            continue;
10711                        }
10712                        pkgSetting.setSuspended(suspended, userId);
10713                        mSettings.writePackageRestrictionsLPr(userId);
10714                        changed = true;
10715                        changedPackages.add(packageName);
10716                    }
10717                }
10718
10719                if (changed && suspended) {
10720                    killApplication(packageName, UserHandle.getUid(userId, appId),
10721                            "suspending package");
10722                }
10723            } finally {
10724                Binder.restoreCallingIdentity(callingId);
10725            }
10726        }
10727
10728        if (!changedPackages.isEmpty()) {
10729            sendPackagesSuspendedForUser(changedPackages.toArray(
10730                    new String[changedPackages.size()]), userId, suspended);
10731        }
10732
10733        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
10734    }
10735
10736    @Override
10737    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10738        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10739                false, "isPackageSuspendedForUser for user " + userId);
10740        synchronized (mPackages) {
10741            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10742            return pkgSetting != null && pkgSetting.getSuspended(userId);
10743        }
10744    }
10745
10746    // TODO: investigate and add more restrictions for suspending crucial packages.
10747    private boolean canSuspendPackageForUser(String packageName, int userId) {
10748        if (isPackageDeviceAdmin(packageName, userId)) {
10749            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10750                    + "\": has active device admin");
10751            return false;
10752        }
10753
10754        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10755        if (packageName.equals(activeLauncherPackageName)) {
10756            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10757                    + "\" because it is set as the active launcher");
10758            return false;
10759        }
10760
10761        return true;
10762    }
10763
10764    private String getActiveLauncherPackageName(int userId) {
10765        Intent intent = new Intent(Intent.ACTION_MAIN);
10766        intent.addCategory(Intent.CATEGORY_HOME);
10767        ResolveInfo resolveInfo = resolveIntent(
10768                intent,
10769                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10770                PackageManager.MATCH_DEFAULT_ONLY,
10771                userId);
10772
10773        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10774    }
10775
10776    @Override
10777    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10778        mContext.enforceCallingOrSelfPermission(
10779                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10780                "Only package verification agents can verify applications");
10781
10782        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10783        final PackageVerificationResponse response = new PackageVerificationResponse(
10784                verificationCode, Binder.getCallingUid());
10785        msg.arg1 = id;
10786        msg.obj = response;
10787        mHandler.sendMessage(msg);
10788    }
10789
10790    @Override
10791    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10792            long millisecondsToDelay) {
10793        mContext.enforceCallingOrSelfPermission(
10794                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10795                "Only package verification agents can extend verification timeouts");
10796
10797        final PackageVerificationState state = mPendingVerification.get(id);
10798        final PackageVerificationResponse response = new PackageVerificationResponse(
10799                verificationCodeAtTimeout, Binder.getCallingUid());
10800
10801        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10802            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10803        }
10804        if (millisecondsToDelay < 0) {
10805            millisecondsToDelay = 0;
10806        }
10807        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10808                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10809            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10810        }
10811
10812        if ((state != null) && !state.timeoutExtended()) {
10813            state.extendTimeout();
10814
10815            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10816            msg.arg1 = id;
10817            msg.obj = response;
10818            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10819        }
10820    }
10821
10822    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10823            int verificationCode, UserHandle user) {
10824        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10825        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10826        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10827        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10828        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10829
10830        mContext.sendBroadcastAsUser(intent, user,
10831                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10832    }
10833
10834    private ComponentName matchComponentForVerifier(String packageName,
10835            List<ResolveInfo> receivers) {
10836        ActivityInfo targetReceiver = null;
10837
10838        final int NR = receivers.size();
10839        for (int i = 0; i < NR; i++) {
10840            final ResolveInfo info = receivers.get(i);
10841            if (info.activityInfo == null) {
10842                continue;
10843            }
10844
10845            if (packageName.equals(info.activityInfo.packageName)) {
10846                targetReceiver = info.activityInfo;
10847                break;
10848            }
10849        }
10850
10851        if (targetReceiver == null) {
10852            return null;
10853        }
10854
10855        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10856    }
10857
10858    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10859            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10860        if (pkgInfo.verifiers.length == 0) {
10861            return null;
10862        }
10863
10864        final int N = pkgInfo.verifiers.length;
10865        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10866        for (int i = 0; i < N; i++) {
10867            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10868
10869            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10870                    receivers);
10871            if (comp == null) {
10872                continue;
10873            }
10874
10875            final int verifierUid = getUidForVerifier(verifierInfo);
10876            if (verifierUid == -1) {
10877                continue;
10878            }
10879
10880            if (DEBUG_VERIFY) {
10881                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10882                        + " with the correct signature");
10883            }
10884            sufficientVerifiers.add(comp);
10885            verificationState.addSufficientVerifier(verifierUid);
10886        }
10887
10888        return sufficientVerifiers;
10889    }
10890
10891    private int getUidForVerifier(VerifierInfo verifierInfo) {
10892        synchronized (mPackages) {
10893            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10894            if (pkg == null) {
10895                return -1;
10896            } else if (pkg.mSignatures.length != 1) {
10897                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10898                        + " has more than one signature; ignoring");
10899                return -1;
10900            }
10901
10902            /*
10903             * If the public key of the package's signature does not match
10904             * our expected public key, then this is a different package and
10905             * we should skip.
10906             */
10907
10908            final byte[] expectedPublicKey;
10909            try {
10910                final Signature verifierSig = pkg.mSignatures[0];
10911                final PublicKey publicKey = verifierSig.getPublicKey();
10912                expectedPublicKey = publicKey.getEncoded();
10913            } catch (CertificateException e) {
10914                return -1;
10915            }
10916
10917            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10918
10919            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10920                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10921                        + " does not have the expected public key; ignoring");
10922                return -1;
10923            }
10924
10925            return pkg.applicationInfo.uid;
10926        }
10927    }
10928
10929    @Override
10930    public void finishPackageInstall(int token) {
10931        enforceSystemOrRoot("Only the system is allowed to finish installs");
10932
10933        if (DEBUG_INSTALL) {
10934            Slog.v(TAG, "BM finishing package install for " + token);
10935        }
10936        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10937
10938        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10939        mHandler.sendMessage(msg);
10940    }
10941
10942    /**
10943     * Get the verification agent timeout.
10944     *
10945     * @return verification timeout in milliseconds
10946     */
10947    private long getVerificationTimeout() {
10948        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10949                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10950                DEFAULT_VERIFICATION_TIMEOUT);
10951    }
10952
10953    /**
10954     * Get the default verification agent response code.
10955     *
10956     * @return default verification response code
10957     */
10958    private int getDefaultVerificationResponse() {
10959        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10960                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10961                DEFAULT_VERIFICATION_RESPONSE);
10962    }
10963
10964    /**
10965     * Check whether or not package verification has been enabled.
10966     *
10967     * @return true if verification should be performed
10968     */
10969    private boolean isVerificationEnabled(int userId, int installFlags) {
10970        if (!DEFAULT_VERIFY_ENABLE) {
10971            return false;
10972        }
10973        // Ephemeral apps don't get the full verification treatment
10974        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10975            if (DEBUG_EPHEMERAL) {
10976                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10977            }
10978            return false;
10979        }
10980
10981        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10982
10983        // Check if installing from ADB
10984        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10985            // Do not run verification in a test harness environment
10986            if (ActivityManager.isRunningInTestHarness()) {
10987                return false;
10988            }
10989            if (ensureVerifyAppsEnabled) {
10990                return true;
10991            }
10992            // Check if the developer does not want package verification for ADB installs
10993            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10994                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10995                return false;
10996            }
10997        }
10998
10999        if (ensureVerifyAppsEnabled) {
11000            return true;
11001        }
11002
11003        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11004                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11005    }
11006
11007    @Override
11008    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11009            throws RemoteException {
11010        mContext.enforceCallingOrSelfPermission(
11011                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11012                "Only intentfilter verification agents can verify applications");
11013
11014        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11015        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11016                Binder.getCallingUid(), verificationCode, failedDomains);
11017        msg.arg1 = id;
11018        msg.obj = response;
11019        mHandler.sendMessage(msg);
11020    }
11021
11022    @Override
11023    public int getIntentVerificationStatus(String packageName, int userId) {
11024        synchronized (mPackages) {
11025            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11026        }
11027    }
11028
11029    @Override
11030    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11031        mContext.enforceCallingOrSelfPermission(
11032                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11033
11034        boolean result = false;
11035        synchronized (mPackages) {
11036            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11037        }
11038        if (result) {
11039            scheduleWritePackageRestrictionsLocked(userId);
11040        }
11041        return result;
11042    }
11043
11044    @Override
11045    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
11046        synchronized (mPackages) {
11047            return mSettings.getIntentFilterVerificationsLPr(packageName);
11048        }
11049    }
11050
11051    @Override
11052    public List<IntentFilter> getAllIntentFilters(String packageName) {
11053        if (TextUtils.isEmpty(packageName)) {
11054            return Collections.<IntentFilter>emptyList();
11055        }
11056        synchronized (mPackages) {
11057            PackageParser.Package pkg = mPackages.get(packageName);
11058            if (pkg == null || pkg.activities == null) {
11059                return Collections.<IntentFilter>emptyList();
11060            }
11061            final int count = pkg.activities.size();
11062            ArrayList<IntentFilter> result = new ArrayList<>();
11063            for (int n=0; n<count; n++) {
11064                PackageParser.Activity activity = pkg.activities.get(n);
11065                if (activity.intents != null && activity.intents.size() > 0) {
11066                    result.addAll(activity.intents);
11067                }
11068            }
11069            return result;
11070        }
11071    }
11072
11073    @Override
11074    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11075        mContext.enforceCallingOrSelfPermission(
11076                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11077
11078        synchronized (mPackages) {
11079            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11080            if (packageName != null) {
11081                result |= updateIntentVerificationStatus(packageName,
11082                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11083                        userId);
11084                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11085                        packageName, userId);
11086            }
11087            return result;
11088        }
11089    }
11090
11091    @Override
11092    public String getDefaultBrowserPackageName(int userId) {
11093        synchronized (mPackages) {
11094            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11095        }
11096    }
11097
11098    /**
11099     * Get the "allow unknown sources" setting.
11100     *
11101     * @return the current "allow unknown sources" setting
11102     */
11103    private int getUnknownSourcesSettings() {
11104        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11105                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11106                -1);
11107    }
11108
11109    @Override
11110    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11111        final int uid = Binder.getCallingUid();
11112        // writer
11113        synchronized (mPackages) {
11114            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11115            if (targetPackageSetting == null) {
11116                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11117            }
11118
11119            PackageSetting installerPackageSetting;
11120            if (installerPackageName != null) {
11121                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11122                if (installerPackageSetting == null) {
11123                    throw new IllegalArgumentException("Unknown installer package: "
11124                            + installerPackageName);
11125                }
11126            } else {
11127                installerPackageSetting = null;
11128            }
11129
11130            Signature[] callerSignature;
11131            Object obj = mSettings.getUserIdLPr(uid);
11132            if (obj != null) {
11133                if (obj instanceof SharedUserSetting) {
11134                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11135                } else if (obj instanceof PackageSetting) {
11136                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11137                } else {
11138                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11139                }
11140            } else {
11141                throw new SecurityException("Unknown calling UID: " + uid);
11142            }
11143
11144            // Verify: can't set installerPackageName to a package that is
11145            // not signed with the same cert as the caller.
11146            if (installerPackageSetting != null) {
11147                if (compareSignatures(callerSignature,
11148                        installerPackageSetting.signatures.mSignatures)
11149                        != PackageManager.SIGNATURE_MATCH) {
11150                    throw new SecurityException(
11151                            "Caller does not have same cert as new installer package "
11152                            + installerPackageName);
11153                }
11154            }
11155
11156            // Verify: if target already has an installer package, it must
11157            // be signed with the same cert as the caller.
11158            if (targetPackageSetting.installerPackageName != null) {
11159                PackageSetting setting = mSettings.mPackages.get(
11160                        targetPackageSetting.installerPackageName);
11161                // If the currently set package isn't valid, then it's always
11162                // okay to change it.
11163                if (setting != null) {
11164                    if (compareSignatures(callerSignature,
11165                            setting.signatures.mSignatures)
11166                            != PackageManager.SIGNATURE_MATCH) {
11167                        throw new SecurityException(
11168                                "Caller does not have same cert as old installer package "
11169                                + targetPackageSetting.installerPackageName);
11170                    }
11171                }
11172            }
11173
11174            // Okay!
11175            targetPackageSetting.installerPackageName = installerPackageName;
11176            scheduleWriteSettingsLocked();
11177        }
11178    }
11179
11180    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11181        // Queue up an async operation since the package installation may take a little while.
11182        mHandler.post(new Runnable() {
11183            public void run() {
11184                mHandler.removeCallbacks(this);
11185                 // Result object to be returned
11186                PackageInstalledInfo res = new PackageInstalledInfo();
11187                res.setReturnCode(currentStatus);
11188                res.uid = -1;
11189                res.pkg = null;
11190                res.removedInfo = null;
11191                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11192                    args.doPreInstall(res.returnCode);
11193                    synchronized (mInstallLock) {
11194                        installPackageTracedLI(args, res);
11195                    }
11196                    args.doPostInstall(res.returnCode, res.uid);
11197                }
11198
11199                // A restore should be performed at this point if (a) the install
11200                // succeeded, (b) the operation is not an update, and (c) the new
11201                // package has not opted out of backup participation.
11202                final boolean update = res.removedInfo != null
11203                        && res.removedInfo.removedPackage != null;
11204                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11205                boolean doRestore = !update
11206                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11207
11208                // Set up the post-install work request bookkeeping.  This will be used
11209                // and cleaned up by the post-install event handling regardless of whether
11210                // there's a restore pass performed.  Token values are >= 1.
11211                int token;
11212                if (mNextInstallToken < 0) mNextInstallToken = 1;
11213                token = mNextInstallToken++;
11214
11215                PostInstallData data = new PostInstallData(args, res);
11216                mRunningInstalls.put(token, data);
11217                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11218
11219                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11220                    // Pass responsibility to the Backup Manager.  It will perform a
11221                    // restore if appropriate, then pass responsibility back to the
11222                    // Package Manager to run the post-install observer callbacks
11223                    // and broadcasts.
11224                    IBackupManager bm = IBackupManager.Stub.asInterface(
11225                            ServiceManager.getService(Context.BACKUP_SERVICE));
11226                    if (bm != null) {
11227                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11228                                + " to BM for possible restore");
11229                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11230                        try {
11231                            // TODO: http://b/22388012
11232                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11233                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11234                            } else {
11235                                doRestore = false;
11236                            }
11237                        } catch (RemoteException e) {
11238                            // can't happen; the backup manager is local
11239                        } catch (Exception e) {
11240                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11241                            doRestore = false;
11242                        }
11243                    } else {
11244                        Slog.e(TAG, "Backup Manager not found!");
11245                        doRestore = false;
11246                    }
11247                }
11248
11249                if (!doRestore) {
11250                    // No restore possible, or the Backup Manager was mysteriously not
11251                    // available -- just fire the post-install work request directly.
11252                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11253
11254                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11255
11256                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11257                    mHandler.sendMessage(msg);
11258                }
11259            }
11260        });
11261    }
11262
11263    private abstract class HandlerParams {
11264        private static final int MAX_RETRIES = 4;
11265
11266        /**
11267         * Number of times startCopy() has been attempted and had a non-fatal
11268         * error.
11269         */
11270        private int mRetries = 0;
11271
11272        /** User handle for the user requesting the information or installation. */
11273        private final UserHandle mUser;
11274        String traceMethod;
11275        int traceCookie;
11276
11277        HandlerParams(UserHandle user) {
11278            mUser = user;
11279        }
11280
11281        UserHandle getUser() {
11282            return mUser;
11283        }
11284
11285        HandlerParams setTraceMethod(String traceMethod) {
11286            this.traceMethod = traceMethod;
11287            return this;
11288        }
11289
11290        HandlerParams setTraceCookie(int traceCookie) {
11291            this.traceCookie = traceCookie;
11292            return this;
11293        }
11294
11295        final boolean startCopy() {
11296            boolean res;
11297            try {
11298                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11299
11300                if (++mRetries > MAX_RETRIES) {
11301                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11302                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11303                    handleServiceError();
11304                    return false;
11305                } else {
11306                    handleStartCopy();
11307                    res = true;
11308                }
11309            } catch (RemoteException e) {
11310                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11311                mHandler.sendEmptyMessage(MCS_RECONNECT);
11312                res = false;
11313            }
11314            handleReturnCode();
11315            return res;
11316        }
11317
11318        final void serviceError() {
11319            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11320            handleServiceError();
11321            handleReturnCode();
11322        }
11323
11324        abstract void handleStartCopy() throws RemoteException;
11325        abstract void handleServiceError();
11326        abstract void handleReturnCode();
11327    }
11328
11329    class MeasureParams extends HandlerParams {
11330        private final PackageStats mStats;
11331        private boolean mSuccess;
11332
11333        private final IPackageStatsObserver mObserver;
11334
11335        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11336            super(new UserHandle(stats.userHandle));
11337            mObserver = observer;
11338            mStats = stats;
11339        }
11340
11341        @Override
11342        public String toString() {
11343            return "MeasureParams{"
11344                + Integer.toHexString(System.identityHashCode(this))
11345                + " " + mStats.packageName + "}";
11346        }
11347
11348        @Override
11349        void handleStartCopy() throws RemoteException {
11350            synchronized (mInstallLock) {
11351                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11352            }
11353
11354            if (mSuccess) {
11355                final boolean mounted;
11356                if (Environment.isExternalStorageEmulated()) {
11357                    mounted = true;
11358                } else {
11359                    final String status = Environment.getExternalStorageState();
11360                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11361                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11362                }
11363
11364                if (mounted) {
11365                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11366
11367                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11368                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11369
11370                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11371                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11372
11373                    // Always subtract cache size, since it's a subdirectory
11374                    mStats.externalDataSize -= mStats.externalCacheSize;
11375
11376                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11377                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11378
11379                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11380                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11381                }
11382            }
11383        }
11384
11385        @Override
11386        void handleReturnCode() {
11387            if (mObserver != null) {
11388                try {
11389                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11390                } catch (RemoteException e) {
11391                    Slog.i(TAG, "Observer no longer exists.");
11392                }
11393            }
11394        }
11395
11396        @Override
11397        void handleServiceError() {
11398            Slog.e(TAG, "Could not measure application " + mStats.packageName
11399                            + " external storage");
11400        }
11401    }
11402
11403    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11404            throws RemoteException {
11405        long result = 0;
11406        for (File path : paths) {
11407            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11408        }
11409        return result;
11410    }
11411
11412    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11413        for (File path : paths) {
11414            try {
11415                mcs.clearDirectory(path.getAbsolutePath());
11416            } catch (RemoteException e) {
11417            }
11418        }
11419    }
11420
11421    static class OriginInfo {
11422        /**
11423         * Location where install is coming from, before it has been
11424         * copied/renamed into place. This could be a single monolithic APK
11425         * file, or a cluster directory. This location may be untrusted.
11426         */
11427        final File file;
11428        final String cid;
11429
11430        /**
11431         * Flag indicating that {@link #file} or {@link #cid} has already been
11432         * staged, meaning downstream users don't need to defensively copy the
11433         * contents.
11434         */
11435        final boolean staged;
11436
11437        /**
11438         * Flag indicating that {@link #file} or {@link #cid} is an already
11439         * installed app that is being moved.
11440         */
11441        final boolean existing;
11442
11443        final String resolvedPath;
11444        final File resolvedFile;
11445
11446        static OriginInfo fromNothing() {
11447            return new OriginInfo(null, null, false, false);
11448        }
11449
11450        static OriginInfo fromUntrustedFile(File file) {
11451            return new OriginInfo(file, null, false, false);
11452        }
11453
11454        static OriginInfo fromExistingFile(File file) {
11455            return new OriginInfo(file, null, false, true);
11456        }
11457
11458        static OriginInfo fromStagedFile(File file) {
11459            return new OriginInfo(file, null, true, false);
11460        }
11461
11462        static OriginInfo fromStagedContainer(String cid) {
11463            return new OriginInfo(null, cid, true, false);
11464        }
11465
11466        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11467            this.file = file;
11468            this.cid = cid;
11469            this.staged = staged;
11470            this.existing = existing;
11471
11472            if (cid != null) {
11473                resolvedPath = PackageHelper.getSdDir(cid);
11474                resolvedFile = new File(resolvedPath);
11475            } else if (file != null) {
11476                resolvedPath = file.getAbsolutePath();
11477                resolvedFile = file;
11478            } else {
11479                resolvedPath = null;
11480                resolvedFile = null;
11481            }
11482        }
11483    }
11484
11485    static class MoveInfo {
11486        final int moveId;
11487        final String fromUuid;
11488        final String toUuid;
11489        final String packageName;
11490        final String dataAppName;
11491        final int appId;
11492        final String seinfo;
11493        final int targetSdkVersion;
11494
11495        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11496                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11497            this.moveId = moveId;
11498            this.fromUuid = fromUuid;
11499            this.toUuid = toUuid;
11500            this.packageName = packageName;
11501            this.dataAppName = dataAppName;
11502            this.appId = appId;
11503            this.seinfo = seinfo;
11504            this.targetSdkVersion = targetSdkVersion;
11505        }
11506    }
11507
11508    class InstallParams extends HandlerParams {
11509        final OriginInfo origin;
11510        final MoveInfo move;
11511        final IPackageInstallObserver2 observer;
11512        int installFlags;
11513        final String installerPackageName;
11514        final String volumeUuid;
11515        final VerificationParams verificationParams;
11516        private InstallArgs mArgs;
11517        private int mRet;
11518        final String packageAbiOverride;
11519        final String[] grantedRuntimePermissions;
11520
11521        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11522                int installFlags, String installerPackageName, String volumeUuid,
11523                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11524                String[] grantedPermissions) {
11525            super(user);
11526            this.origin = origin;
11527            this.move = move;
11528            this.observer = observer;
11529            this.installFlags = installFlags;
11530            this.installerPackageName = installerPackageName;
11531            this.volumeUuid = volumeUuid;
11532            this.verificationParams = verificationParams;
11533            this.packageAbiOverride = packageAbiOverride;
11534            this.grantedRuntimePermissions = grantedPermissions;
11535        }
11536
11537        @Override
11538        public String toString() {
11539            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11540                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11541        }
11542
11543        private int installLocationPolicy(PackageInfoLite pkgLite) {
11544            String packageName = pkgLite.packageName;
11545            int installLocation = pkgLite.installLocation;
11546            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11547            // reader
11548            synchronized (mPackages) {
11549                PackageParser.Package pkg = mPackages.get(packageName);
11550                if (pkg != null) {
11551                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11552                        // Check for downgrading.
11553                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11554                            try {
11555                                checkDowngrade(pkg, pkgLite);
11556                            } catch (PackageManagerException e) {
11557                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11558                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11559                            }
11560                        }
11561                        // Check for updated system application.
11562                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11563                            if (onSd) {
11564                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11565                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11566                            }
11567                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11568                        } else {
11569                            if (onSd) {
11570                                // Install flag overrides everything.
11571                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11572                            }
11573                            // If current upgrade specifies particular preference
11574                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11575                                // Application explicitly specified internal.
11576                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11577                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11578                                // App explictly prefers external. Let policy decide
11579                            } else {
11580                                // Prefer previous location
11581                                if (isExternal(pkg)) {
11582                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11583                                }
11584                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11585                            }
11586                        }
11587                    } else {
11588                        // Invalid install. Return error code
11589                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11590                    }
11591                }
11592            }
11593            // All the special cases have been taken care of.
11594            // Return result based on recommended install location.
11595            if (onSd) {
11596                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11597            }
11598            return pkgLite.recommendedInstallLocation;
11599        }
11600
11601        /*
11602         * Invoke remote method to get package information and install
11603         * location values. Override install location based on default
11604         * policy if needed and then create install arguments based
11605         * on the install location.
11606         */
11607        public void handleStartCopy() throws RemoteException {
11608            int ret = PackageManager.INSTALL_SUCCEEDED;
11609
11610            // If we're already staged, we've firmly committed to an install location
11611            if (origin.staged) {
11612                if (origin.file != null) {
11613                    installFlags |= PackageManager.INSTALL_INTERNAL;
11614                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11615                } else if (origin.cid != null) {
11616                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11617                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11618                } else {
11619                    throw new IllegalStateException("Invalid stage location");
11620                }
11621            }
11622
11623            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11624            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11625            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11626            PackageInfoLite pkgLite = null;
11627
11628            if (onInt && onSd) {
11629                // Check if both bits are set.
11630                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11631                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11632            } else if (onSd && ephemeral) {
11633                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11634                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11635            } else {
11636                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11637                        packageAbiOverride);
11638
11639                if (DEBUG_EPHEMERAL && ephemeral) {
11640                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11641                }
11642
11643                /*
11644                 * If we have too little free space, try to free cache
11645                 * before giving up.
11646                 */
11647                if (!origin.staged && pkgLite.recommendedInstallLocation
11648                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11649                    // TODO: focus freeing disk space on the target device
11650                    final StorageManager storage = StorageManager.from(mContext);
11651                    final long lowThreshold = storage.getStorageLowBytes(
11652                            Environment.getDataDirectory());
11653
11654                    final long sizeBytes = mContainerService.calculateInstalledSize(
11655                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11656
11657                    try {
11658                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11659                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11660                                installFlags, packageAbiOverride);
11661                    } catch (InstallerException e) {
11662                        Slog.w(TAG, "Failed to free cache", e);
11663                    }
11664
11665                    /*
11666                     * The cache free must have deleted the file we
11667                     * downloaded to install.
11668                     *
11669                     * TODO: fix the "freeCache" call to not delete
11670                     *       the file we care about.
11671                     */
11672                    if (pkgLite.recommendedInstallLocation
11673                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11674                        pkgLite.recommendedInstallLocation
11675                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11676                    }
11677                }
11678            }
11679
11680            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11681                int loc = pkgLite.recommendedInstallLocation;
11682                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11683                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11684                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11685                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11686                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11687                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11688                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11689                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11690                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11691                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11692                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11693                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11694                } else {
11695                    // Override with defaults if needed.
11696                    loc = installLocationPolicy(pkgLite);
11697                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11698                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11699                    } else if (!onSd && !onInt) {
11700                        // Override install location with flags
11701                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11702                            // Set the flag to install on external media.
11703                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11704                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11705                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11706                            if (DEBUG_EPHEMERAL) {
11707                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11708                            }
11709                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11710                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11711                                    |PackageManager.INSTALL_INTERNAL);
11712                        } else {
11713                            // Make sure the flag for installing on external
11714                            // media is unset
11715                            installFlags |= PackageManager.INSTALL_INTERNAL;
11716                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11717                        }
11718                    }
11719                }
11720            }
11721
11722            final InstallArgs args = createInstallArgs(this);
11723            mArgs = args;
11724
11725            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11726                // TODO: http://b/22976637
11727                // Apps installed for "all" users use the device owner to verify the app
11728                UserHandle verifierUser = getUser();
11729                if (verifierUser == UserHandle.ALL) {
11730                    verifierUser = UserHandle.SYSTEM;
11731                }
11732
11733                /*
11734                 * Determine if we have any installed package verifiers. If we
11735                 * do, then we'll defer to them to verify the packages.
11736                 */
11737                final int requiredUid = mRequiredVerifierPackage == null ? -1
11738                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11739                                verifierUser.getIdentifier());
11740                if (!origin.existing && requiredUid != -1
11741                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11742                    final Intent verification = new Intent(
11743                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11744                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11745                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11746                            PACKAGE_MIME_TYPE);
11747                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11748
11749                    // Query all live verifiers based on current user state
11750                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11751                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11752
11753                    if (DEBUG_VERIFY) {
11754                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11755                                + verification.toString() + " with " + pkgLite.verifiers.length
11756                                + " optional verifiers");
11757                    }
11758
11759                    final int verificationId = mPendingVerificationToken++;
11760
11761                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11762
11763                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11764                            installerPackageName);
11765
11766                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11767                            installFlags);
11768
11769                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11770                            pkgLite.packageName);
11771
11772                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11773                            pkgLite.versionCode);
11774
11775                    if (verificationParams != null) {
11776                        if (verificationParams.getVerificationURI() != null) {
11777                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11778                                 verificationParams.getVerificationURI());
11779                        }
11780                        if (verificationParams.getOriginatingURI() != null) {
11781                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11782                                  verificationParams.getOriginatingURI());
11783                        }
11784                        if (verificationParams.getReferrer() != null) {
11785                            verification.putExtra(Intent.EXTRA_REFERRER,
11786                                  verificationParams.getReferrer());
11787                        }
11788                        if (verificationParams.getOriginatingUid() >= 0) {
11789                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11790                                  verificationParams.getOriginatingUid());
11791                        }
11792                        if (verificationParams.getInstallerUid() >= 0) {
11793                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11794                                  verificationParams.getInstallerUid());
11795                        }
11796                    }
11797
11798                    final PackageVerificationState verificationState = new PackageVerificationState(
11799                            requiredUid, args);
11800
11801                    mPendingVerification.append(verificationId, verificationState);
11802
11803                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11804                            receivers, verificationState);
11805
11806                    /*
11807                     * If any sufficient verifiers were listed in the package
11808                     * manifest, attempt to ask them.
11809                     */
11810                    if (sufficientVerifiers != null) {
11811                        final int N = sufficientVerifiers.size();
11812                        if (N == 0) {
11813                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11814                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11815                        } else {
11816                            for (int i = 0; i < N; i++) {
11817                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11818
11819                                final Intent sufficientIntent = new Intent(verification);
11820                                sufficientIntent.setComponent(verifierComponent);
11821                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11822                            }
11823                        }
11824                    }
11825
11826                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11827                            mRequiredVerifierPackage, receivers);
11828                    if (ret == PackageManager.INSTALL_SUCCEEDED
11829                            && mRequiredVerifierPackage != null) {
11830                        Trace.asyncTraceBegin(
11831                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11832                        /*
11833                         * Send the intent to the required verification agent,
11834                         * but only start the verification timeout after the
11835                         * target BroadcastReceivers have run.
11836                         */
11837                        verification.setComponent(requiredVerifierComponent);
11838                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11839                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11840                                new BroadcastReceiver() {
11841                                    @Override
11842                                    public void onReceive(Context context, Intent intent) {
11843                                        final Message msg = mHandler
11844                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11845                                        msg.arg1 = verificationId;
11846                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11847                                    }
11848                                }, null, 0, null, null);
11849
11850                        /*
11851                         * We don't want the copy to proceed until verification
11852                         * succeeds, so null out this field.
11853                         */
11854                        mArgs = null;
11855                    }
11856                } else {
11857                    /*
11858                     * No package verification is enabled, so immediately start
11859                     * the remote call to initiate copy using temporary file.
11860                     */
11861                    ret = args.copyApk(mContainerService, true);
11862                }
11863            }
11864
11865            mRet = ret;
11866        }
11867
11868        @Override
11869        void handleReturnCode() {
11870            // If mArgs is null, then MCS couldn't be reached. When it
11871            // reconnects, it will try again to install. At that point, this
11872            // will succeed.
11873            if (mArgs != null) {
11874                processPendingInstall(mArgs, mRet);
11875            }
11876        }
11877
11878        @Override
11879        void handleServiceError() {
11880            mArgs = createInstallArgs(this);
11881            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11882        }
11883
11884        public boolean isForwardLocked() {
11885            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11886        }
11887    }
11888
11889    /**
11890     * Used during creation of InstallArgs
11891     *
11892     * @param installFlags package installation flags
11893     * @return true if should be installed on external storage
11894     */
11895    private static boolean installOnExternalAsec(int installFlags) {
11896        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11897            return false;
11898        }
11899        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11900            return true;
11901        }
11902        return false;
11903    }
11904
11905    /**
11906     * Used during creation of InstallArgs
11907     *
11908     * @param installFlags package installation flags
11909     * @return true if should be installed as forward locked
11910     */
11911    private static boolean installForwardLocked(int installFlags) {
11912        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11913    }
11914
11915    private InstallArgs createInstallArgs(InstallParams params) {
11916        if (params.move != null) {
11917            return new MoveInstallArgs(params);
11918        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11919            return new AsecInstallArgs(params);
11920        } else {
11921            return new FileInstallArgs(params);
11922        }
11923    }
11924
11925    /**
11926     * Create args that describe an existing installed package. Typically used
11927     * when cleaning up old installs, or used as a move source.
11928     */
11929    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11930            String resourcePath, String[] instructionSets) {
11931        final boolean isInAsec;
11932        if (installOnExternalAsec(installFlags)) {
11933            /* Apps on SD card are always in ASEC containers. */
11934            isInAsec = true;
11935        } else if (installForwardLocked(installFlags)
11936                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11937            /*
11938             * Forward-locked apps are only in ASEC containers if they're the
11939             * new style
11940             */
11941            isInAsec = true;
11942        } else {
11943            isInAsec = false;
11944        }
11945
11946        if (isInAsec) {
11947            return new AsecInstallArgs(codePath, instructionSets,
11948                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11949        } else {
11950            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11951        }
11952    }
11953
11954    static abstract class InstallArgs {
11955        /** @see InstallParams#origin */
11956        final OriginInfo origin;
11957        /** @see InstallParams#move */
11958        final MoveInfo move;
11959
11960        final IPackageInstallObserver2 observer;
11961        // Always refers to PackageManager flags only
11962        final int installFlags;
11963        final String installerPackageName;
11964        final String volumeUuid;
11965        final UserHandle user;
11966        final String abiOverride;
11967        final String[] installGrantPermissions;
11968        /** If non-null, drop an async trace when the install completes */
11969        final String traceMethod;
11970        final int traceCookie;
11971
11972        // The list of instruction sets supported by this app. This is currently
11973        // only used during the rmdex() phase to clean up resources. We can get rid of this
11974        // if we move dex files under the common app path.
11975        /* nullable */ String[] instructionSets;
11976
11977        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11978                int installFlags, String installerPackageName, String volumeUuid,
11979                UserHandle user, String[] instructionSets,
11980                String abiOverride, String[] installGrantPermissions,
11981                String traceMethod, int traceCookie) {
11982            this.origin = origin;
11983            this.move = move;
11984            this.installFlags = installFlags;
11985            this.observer = observer;
11986            this.installerPackageName = installerPackageName;
11987            this.volumeUuid = volumeUuid;
11988            this.user = user;
11989            this.instructionSets = instructionSets;
11990            this.abiOverride = abiOverride;
11991            this.installGrantPermissions = installGrantPermissions;
11992            this.traceMethod = traceMethod;
11993            this.traceCookie = traceCookie;
11994        }
11995
11996        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11997        abstract int doPreInstall(int status);
11998
11999        /**
12000         * Rename package into final resting place. All paths on the given
12001         * scanned package should be updated to reflect the rename.
12002         */
12003        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12004        abstract int doPostInstall(int status, int uid);
12005
12006        /** @see PackageSettingBase#codePathString */
12007        abstract String getCodePath();
12008        /** @see PackageSettingBase#resourcePathString */
12009        abstract String getResourcePath();
12010
12011        // Need installer lock especially for dex file removal.
12012        abstract void cleanUpResourcesLI();
12013        abstract boolean doPostDeleteLI(boolean delete);
12014
12015        /**
12016         * Called before the source arguments are copied. This is used mostly
12017         * for MoveParams when it needs to read the source file to put it in the
12018         * destination.
12019         */
12020        int doPreCopy() {
12021            return PackageManager.INSTALL_SUCCEEDED;
12022        }
12023
12024        /**
12025         * Called after the source arguments are copied. This is used mostly for
12026         * MoveParams when it needs to read the source file to put it in the
12027         * destination.
12028         *
12029         * @return
12030         */
12031        int doPostCopy(int uid) {
12032            return PackageManager.INSTALL_SUCCEEDED;
12033        }
12034
12035        protected boolean isFwdLocked() {
12036            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12037        }
12038
12039        protected boolean isExternalAsec() {
12040            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12041        }
12042
12043        protected boolean isEphemeral() {
12044            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12045        }
12046
12047        UserHandle getUser() {
12048            return user;
12049        }
12050    }
12051
12052    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12053        if (!allCodePaths.isEmpty()) {
12054            if (instructionSets == null) {
12055                throw new IllegalStateException("instructionSet == null");
12056            }
12057            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12058            for (String codePath : allCodePaths) {
12059                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12060                    try {
12061                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12062                    } catch (InstallerException ignored) {
12063                    }
12064                }
12065            }
12066        }
12067    }
12068
12069    /**
12070     * Logic to handle installation of non-ASEC applications, including copying
12071     * and renaming logic.
12072     */
12073    class FileInstallArgs extends InstallArgs {
12074        private File codeFile;
12075        private File resourceFile;
12076
12077        // Example topology:
12078        // /data/app/com.example/base.apk
12079        // /data/app/com.example/split_foo.apk
12080        // /data/app/com.example/lib/arm/libfoo.so
12081        // /data/app/com.example/lib/arm64/libfoo.so
12082        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12083
12084        /** New install */
12085        FileInstallArgs(InstallParams params) {
12086            super(params.origin, params.move, params.observer, params.installFlags,
12087                    params.installerPackageName, params.volumeUuid,
12088                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12089                    params.grantedRuntimePermissions,
12090                    params.traceMethod, params.traceCookie);
12091            if (isFwdLocked()) {
12092                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12093            }
12094        }
12095
12096        /** Existing install */
12097        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12098            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12099                    null, null, null, 0);
12100            this.codeFile = (codePath != null) ? new File(codePath) : null;
12101            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12102        }
12103
12104        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12105            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12106            try {
12107                return doCopyApk(imcs, temp);
12108            } finally {
12109                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12110            }
12111        }
12112
12113        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12114            if (origin.staged) {
12115                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12116                codeFile = origin.file;
12117                resourceFile = origin.file;
12118                return PackageManager.INSTALL_SUCCEEDED;
12119            }
12120
12121            try {
12122                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12123                final File tempDir =
12124                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12125                codeFile = tempDir;
12126                resourceFile = tempDir;
12127            } catch (IOException e) {
12128                Slog.w(TAG, "Failed to create copy file: " + e);
12129                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12130            }
12131
12132            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12133                @Override
12134                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12135                    if (!FileUtils.isValidExtFilename(name)) {
12136                        throw new IllegalArgumentException("Invalid filename: " + name);
12137                    }
12138                    try {
12139                        final File file = new File(codeFile, name);
12140                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12141                                O_RDWR | O_CREAT, 0644);
12142                        Os.chmod(file.getAbsolutePath(), 0644);
12143                        return new ParcelFileDescriptor(fd);
12144                    } catch (ErrnoException e) {
12145                        throw new RemoteException("Failed to open: " + e.getMessage());
12146                    }
12147                }
12148            };
12149
12150            int ret = PackageManager.INSTALL_SUCCEEDED;
12151            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12152            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12153                Slog.e(TAG, "Failed to copy package");
12154                return ret;
12155            }
12156
12157            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12158            NativeLibraryHelper.Handle handle = null;
12159            try {
12160                handle = NativeLibraryHelper.Handle.create(codeFile);
12161                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12162                        abiOverride);
12163            } catch (IOException e) {
12164                Slog.e(TAG, "Copying native libraries failed", e);
12165                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12166            } finally {
12167                IoUtils.closeQuietly(handle);
12168            }
12169
12170            return ret;
12171        }
12172
12173        int doPreInstall(int status) {
12174            if (status != PackageManager.INSTALL_SUCCEEDED) {
12175                cleanUp();
12176            }
12177            return status;
12178        }
12179
12180        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12181            if (status != PackageManager.INSTALL_SUCCEEDED) {
12182                cleanUp();
12183                return false;
12184            }
12185
12186            final File targetDir = codeFile.getParentFile();
12187            final File beforeCodeFile = codeFile;
12188            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12189
12190            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12191            try {
12192                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12193            } catch (ErrnoException e) {
12194                Slog.w(TAG, "Failed to rename", e);
12195                return false;
12196            }
12197
12198            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12199                Slog.w(TAG, "Failed to restorecon");
12200                return false;
12201            }
12202
12203            // Reflect the rename internally
12204            codeFile = afterCodeFile;
12205            resourceFile = afterCodeFile;
12206
12207            // Reflect the rename in scanned details
12208            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12209            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12210                    afterCodeFile, pkg.baseCodePath));
12211            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12212                    afterCodeFile, pkg.splitCodePaths));
12213
12214            // Reflect the rename in app info
12215            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12216            pkg.setApplicationInfoCodePath(pkg.codePath);
12217            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12218            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12219            pkg.setApplicationInfoResourcePath(pkg.codePath);
12220            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12221            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12222
12223            return true;
12224        }
12225
12226        int doPostInstall(int status, int uid) {
12227            if (status != PackageManager.INSTALL_SUCCEEDED) {
12228                cleanUp();
12229            }
12230            return status;
12231        }
12232
12233        @Override
12234        String getCodePath() {
12235            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12236        }
12237
12238        @Override
12239        String getResourcePath() {
12240            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12241        }
12242
12243        private boolean cleanUp() {
12244            if (codeFile == null || !codeFile.exists()) {
12245                return false;
12246            }
12247
12248            removeCodePathLI(codeFile);
12249
12250            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12251                resourceFile.delete();
12252            }
12253
12254            return true;
12255        }
12256
12257        void cleanUpResourcesLI() {
12258            // Try enumerating all code paths before deleting
12259            List<String> allCodePaths = Collections.EMPTY_LIST;
12260            if (codeFile != null && codeFile.exists()) {
12261                try {
12262                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12263                    allCodePaths = pkg.getAllCodePaths();
12264                } catch (PackageParserException e) {
12265                    // Ignored; we tried our best
12266                }
12267            }
12268
12269            cleanUp();
12270            removeDexFiles(allCodePaths, instructionSets);
12271        }
12272
12273        boolean doPostDeleteLI(boolean delete) {
12274            // XXX err, shouldn't we respect the delete flag?
12275            cleanUpResourcesLI();
12276            return true;
12277        }
12278    }
12279
12280    private boolean isAsecExternal(String cid) {
12281        final String asecPath = PackageHelper.getSdFilesystem(cid);
12282        return !asecPath.startsWith(mAsecInternalPath);
12283    }
12284
12285    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12286            PackageManagerException {
12287        if (copyRet < 0) {
12288            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12289                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12290                throw new PackageManagerException(copyRet, message);
12291            }
12292        }
12293    }
12294
12295    /**
12296     * Extract the MountService "container ID" from the full code path of an
12297     * .apk.
12298     */
12299    static String cidFromCodePath(String fullCodePath) {
12300        int eidx = fullCodePath.lastIndexOf("/");
12301        String subStr1 = fullCodePath.substring(0, eidx);
12302        int sidx = subStr1.lastIndexOf("/");
12303        return subStr1.substring(sidx+1, eidx);
12304    }
12305
12306    /**
12307     * Logic to handle installation of ASEC applications, including copying and
12308     * renaming logic.
12309     */
12310    class AsecInstallArgs extends InstallArgs {
12311        static final String RES_FILE_NAME = "pkg.apk";
12312        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12313
12314        String cid;
12315        String packagePath;
12316        String resourcePath;
12317
12318        /** New install */
12319        AsecInstallArgs(InstallParams params) {
12320            super(params.origin, params.move, params.observer, params.installFlags,
12321                    params.installerPackageName, params.volumeUuid,
12322                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12323                    params.grantedRuntimePermissions,
12324                    params.traceMethod, params.traceCookie);
12325        }
12326
12327        /** Existing install */
12328        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12329                        boolean isExternal, boolean isForwardLocked) {
12330            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12331                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12332                    instructionSets, null, null, null, 0);
12333            // Hackily pretend we're still looking at a full code path
12334            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12335                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12336            }
12337
12338            // Extract cid from fullCodePath
12339            int eidx = fullCodePath.lastIndexOf("/");
12340            String subStr1 = fullCodePath.substring(0, eidx);
12341            int sidx = subStr1.lastIndexOf("/");
12342            cid = subStr1.substring(sidx+1, eidx);
12343            setMountPath(subStr1);
12344        }
12345
12346        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12347            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12348                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12349                    instructionSets, null, null, null, 0);
12350            this.cid = cid;
12351            setMountPath(PackageHelper.getSdDir(cid));
12352        }
12353
12354        void createCopyFile() {
12355            cid = mInstallerService.allocateExternalStageCidLegacy();
12356        }
12357
12358        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12359            if (origin.staged && origin.cid != null) {
12360                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12361                cid = origin.cid;
12362                setMountPath(PackageHelper.getSdDir(cid));
12363                return PackageManager.INSTALL_SUCCEEDED;
12364            }
12365
12366            if (temp) {
12367                createCopyFile();
12368            } else {
12369                /*
12370                 * Pre-emptively destroy the container since it's destroyed if
12371                 * copying fails due to it existing anyway.
12372                 */
12373                PackageHelper.destroySdDir(cid);
12374            }
12375
12376            final String newMountPath = imcs.copyPackageToContainer(
12377                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12378                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12379
12380            if (newMountPath != null) {
12381                setMountPath(newMountPath);
12382                return PackageManager.INSTALL_SUCCEEDED;
12383            } else {
12384                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12385            }
12386        }
12387
12388        @Override
12389        String getCodePath() {
12390            return packagePath;
12391        }
12392
12393        @Override
12394        String getResourcePath() {
12395            return resourcePath;
12396        }
12397
12398        int doPreInstall(int status) {
12399            if (status != PackageManager.INSTALL_SUCCEEDED) {
12400                // Destroy container
12401                PackageHelper.destroySdDir(cid);
12402            } else {
12403                boolean mounted = PackageHelper.isContainerMounted(cid);
12404                if (!mounted) {
12405                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12406                            Process.SYSTEM_UID);
12407                    if (newMountPath != null) {
12408                        setMountPath(newMountPath);
12409                    } else {
12410                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12411                    }
12412                }
12413            }
12414            return status;
12415        }
12416
12417        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12418            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12419            String newMountPath = null;
12420            if (PackageHelper.isContainerMounted(cid)) {
12421                // Unmount the container
12422                if (!PackageHelper.unMountSdDir(cid)) {
12423                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12424                    return false;
12425                }
12426            }
12427            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12428                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12429                        " which might be stale. Will try to clean up.");
12430                // Clean up the stale container and proceed to recreate.
12431                if (!PackageHelper.destroySdDir(newCacheId)) {
12432                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12433                    return false;
12434                }
12435                // Successfully cleaned up stale container. Try to rename again.
12436                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12437                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12438                            + " inspite of cleaning it up.");
12439                    return false;
12440                }
12441            }
12442            if (!PackageHelper.isContainerMounted(newCacheId)) {
12443                Slog.w(TAG, "Mounting container " + newCacheId);
12444                newMountPath = PackageHelper.mountSdDir(newCacheId,
12445                        getEncryptKey(), Process.SYSTEM_UID);
12446            } else {
12447                newMountPath = PackageHelper.getSdDir(newCacheId);
12448            }
12449            if (newMountPath == null) {
12450                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12451                return false;
12452            }
12453            Log.i(TAG, "Succesfully renamed " + cid +
12454                    " to " + newCacheId +
12455                    " at new path: " + newMountPath);
12456            cid = newCacheId;
12457
12458            final File beforeCodeFile = new File(packagePath);
12459            setMountPath(newMountPath);
12460            final File afterCodeFile = new File(packagePath);
12461
12462            // Reflect the rename in scanned details
12463            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12464            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12465                    afterCodeFile, pkg.baseCodePath));
12466            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12467                    afterCodeFile, pkg.splitCodePaths));
12468
12469            // Reflect the rename in app info
12470            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12471            pkg.setApplicationInfoCodePath(pkg.codePath);
12472            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12473            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12474            pkg.setApplicationInfoResourcePath(pkg.codePath);
12475            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12476            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12477
12478            return true;
12479        }
12480
12481        private void setMountPath(String mountPath) {
12482            final File mountFile = new File(mountPath);
12483
12484            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12485            if (monolithicFile.exists()) {
12486                packagePath = monolithicFile.getAbsolutePath();
12487                if (isFwdLocked()) {
12488                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12489                } else {
12490                    resourcePath = packagePath;
12491                }
12492            } else {
12493                packagePath = mountFile.getAbsolutePath();
12494                resourcePath = packagePath;
12495            }
12496        }
12497
12498        int doPostInstall(int status, int uid) {
12499            if (status != PackageManager.INSTALL_SUCCEEDED) {
12500                cleanUp();
12501            } else {
12502                final int groupOwner;
12503                final String protectedFile;
12504                if (isFwdLocked()) {
12505                    groupOwner = UserHandle.getSharedAppGid(uid);
12506                    protectedFile = RES_FILE_NAME;
12507                } else {
12508                    groupOwner = -1;
12509                    protectedFile = null;
12510                }
12511
12512                if (uid < Process.FIRST_APPLICATION_UID
12513                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12514                    Slog.e(TAG, "Failed to finalize " + cid);
12515                    PackageHelper.destroySdDir(cid);
12516                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12517                }
12518
12519                boolean mounted = PackageHelper.isContainerMounted(cid);
12520                if (!mounted) {
12521                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12522                }
12523            }
12524            return status;
12525        }
12526
12527        private void cleanUp() {
12528            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12529
12530            // Destroy secure container
12531            PackageHelper.destroySdDir(cid);
12532        }
12533
12534        private List<String> getAllCodePaths() {
12535            final File codeFile = new File(getCodePath());
12536            if (codeFile != null && codeFile.exists()) {
12537                try {
12538                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12539                    return pkg.getAllCodePaths();
12540                } catch (PackageParserException e) {
12541                    // Ignored; we tried our best
12542                }
12543            }
12544            return Collections.EMPTY_LIST;
12545        }
12546
12547        void cleanUpResourcesLI() {
12548            // Enumerate all code paths before deleting
12549            cleanUpResourcesLI(getAllCodePaths());
12550        }
12551
12552        private void cleanUpResourcesLI(List<String> allCodePaths) {
12553            cleanUp();
12554            removeDexFiles(allCodePaths, instructionSets);
12555        }
12556
12557        String getPackageName() {
12558            return getAsecPackageName(cid);
12559        }
12560
12561        boolean doPostDeleteLI(boolean delete) {
12562            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12563            final List<String> allCodePaths = getAllCodePaths();
12564            boolean mounted = PackageHelper.isContainerMounted(cid);
12565            if (mounted) {
12566                // Unmount first
12567                if (PackageHelper.unMountSdDir(cid)) {
12568                    mounted = false;
12569                }
12570            }
12571            if (!mounted && delete) {
12572                cleanUpResourcesLI(allCodePaths);
12573            }
12574            return !mounted;
12575        }
12576
12577        @Override
12578        int doPreCopy() {
12579            if (isFwdLocked()) {
12580                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12581                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12582                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12583                }
12584            }
12585
12586            return PackageManager.INSTALL_SUCCEEDED;
12587        }
12588
12589        @Override
12590        int doPostCopy(int uid) {
12591            if (isFwdLocked()) {
12592                if (uid < Process.FIRST_APPLICATION_UID
12593                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12594                                RES_FILE_NAME)) {
12595                    Slog.e(TAG, "Failed to finalize " + cid);
12596                    PackageHelper.destroySdDir(cid);
12597                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12598                }
12599            }
12600
12601            return PackageManager.INSTALL_SUCCEEDED;
12602        }
12603    }
12604
12605    /**
12606     * Logic to handle movement of existing installed applications.
12607     */
12608    class MoveInstallArgs extends InstallArgs {
12609        private File codeFile;
12610        private File resourceFile;
12611
12612        /** New install */
12613        MoveInstallArgs(InstallParams params) {
12614            super(params.origin, params.move, params.observer, params.installFlags,
12615                    params.installerPackageName, params.volumeUuid,
12616                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12617                    params.grantedRuntimePermissions,
12618                    params.traceMethod, params.traceCookie);
12619        }
12620
12621        int copyApk(IMediaContainerService imcs, boolean temp) {
12622            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12623                    + move.fromUuid + " to " + move.toUuid);
12624            synchronized (mInstaller) {
12625                try {
12626                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12627                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12628                } catch (InstallerException e) {
12629                    Slog.w(TAG, "Failed to move app", e);
12630                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12631                }
12632            }
12633
12634            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12635            resourceFile = codeFile;
12636            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12637
12638            return PackageManager.INSTALL_SUCCEEDED;
12639        }
12640
12641        int doPreInstall(int status) {
12642            if (status != PackageManager.INSTALL_SUCCEEDED) {
12643                cleanUp(move.toUuid);
12644            }
12645            return status;
12646        }
12647
12648        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12649            if (status != PackageManager.INSTALL_SUCCEEDED) {
12650                cleanUp(move.toUuid);
12651                return false;
12652            }
12653
12654            // Reflect the move in app info
12655            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12656            pkg.setApplicationInfoCodePath(pkg.codePath);
12657            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12658            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12659            pkg.setApplicationInfoResourcePath(pkg.codePath);
12660            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12661            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12662
12663            return true;
12664        }
12665
12666        int doPostInstall(int status, int uid) {
12667            if (status == PackageManager.INSTALL_SUCCEEDED) {
12668                cleanUp(move.fromUuid);
12669            } else {
12670                cleanUp(move.toUuid);
12671            }
12672            return status;
12673        }
12674
12675        @Override
12676        String getCodePath() {
12677            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12678        }
12679
12680        @Override
12681        String getResourcePath() {
12682            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12683        }
12684
12685        private boolean cleanUp(String volumeUuid) {
12686            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12687                    move.dataAppName);
12688            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12689            synchronized (mInstallLock) {
12690                // Clean up both app data and code
12691                removeDataDirsLI(volumeUuid, move.packageName);
12692                removeCodePathLI(codeFile);
12693            }
12694            return true;
12695        }
12696
12697        void cleanUpResourcesLI() {
12698            throw new UnsupportedOperationException();
12699        }
12700
12701        boolean doPostDeleteLI(boolean delete) {
12702            throw new UnsupportedOperationException();
12703        }
12704    }
12705
12706    static String getAsecPackageName(String packageCid) {
12707        int idx = packageCid.lastIndexOf("-");
12708        if (idx == -1) {
12709            return packageCid;
12710        }
12711        return packageCid.substring(0, idx);
12712    }
12713
12714    // Utility method used to create code paths based on package name and available index.
12715    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12716        String idxStr = "";
12717        int idx = 1;
12718        // Fall back to default value of idx=1 if prefix is not
12719        // part of oldCodePath
12720        if (oldCodePath != null) {
12721            String subStr = oldCodePath;
12722            // Drop the suffix right away
12723            if (suffix != null && subStr.endsWith(suffix)) {
12724                subStr = subStr.substring(0, subStr.length() - suffix.length());
12725            }
12726            // If oldCodePath already contains prefix find out the
12727            // ending index to either increment or decrement.
12728            int sidx = subStr.lastIndexOf(prefix);
12729            if (sidx != -1) {
12730                subStr = subStr.substring(sidx + prefix.length());
12731                if (subStr != null) {
12732                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12733                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12734                    }
12735                    try {
12736                        idx = Integer.parseInt(subStr);
12737                        if (idx <= 1) {
12738                            idx++;
12739                        } else {
12740                            idx--;
12741                        }
12742                    } catch(NumberFormatException e) {
12743                    }
12744                }
12745            }
12746        }
12747        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12748        return prefix + idxStr;
12749    }
12750
12751    private File getNextCodePath(File targetDir, String packageName) {
12752        int suffix = 1;
12753        File result;
12754        do {
12755            result = new File(targetDir, packageName + "-" + suffix);
12756            suffix++;
12757        } while (result.exists());
12758        return result;
12759    }
12760
12761    // Utility method that returns the relative package path with respect
12762    // to the installation directory. Like say for /data/data/com.test-1.apk
12763    // string com.test-1 is returned.
12764    static String deriveCodePathName(String codePath) {
12765        if (codePath == null) {
12766            return null;
12767        }
12768        final File codeFile = new File(codePath);
12769        final String name = codeFile.getName();
12770        if (codeFile.isDirectory()) {
12771            return name;
12772        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12773            final int lastDot = name.lastIndexOf('.');
12774            return name.substring(0, lastDot);
12775        } else {
12776            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12777            return null;
12778        }
12779    }
12780
12781    static class PackageInstalledInfo {
12782        String name;
12783        int uid;
12784        // The set of users that originally had this package installed.
12785        int[] origUsers;
12786        // The set of users that now have this package installed.
12787        int[] newUsers;
12788        PackageParser.Package pkg;
12789        int returnCode;
12790        String returnMsg;
12791        PackageRemovedInfo removedInfo;
12792        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
12793
12794        public void setError(int code, String msg) {
12795            setReturnCode(code);
12796            setReturnMessage(msg);
12797            Slog.w(TAG, msg);
12798        }
12799
12800        public void setError(String msg, PackageParserException e) {
12801            setReturnCode(e.error);
12802            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12803            Slog.w(TAG, msg, e);
12804        }
12805
12806        public void setError(String msg, PackageManagerException e) {
12807            returnCode = e.error;
12808            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12809            Slog.w(TAG, msg, e);
12810        }
12811
12812        public void setReturnCode(int returnCode) {
12813            this.returnCode = returnCode;
12814            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12815            for (int i = 0; i < childCount; i++) {
12816                addedChildPackages.valueAt(i).returnCode = returnCode;
12817            }
12818        }
12819
12820        private void setReturnMessage(String returnMsg) {
12821            this.returnMsg = returnMsg;
12822            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12823            for (int i = 0; i < childCount; i++) {
12824                addedChildPackages.valueAt(i).returnMsg = returnMsg;
12825            }
12826        }
12827
12828        // In some error cases we want to convey more info back to the observer
12829        String origPackage;
12830        String origPermission;
12831    }
12832
12833    /*
12834     * Install a non-existing package.
12835     */
12836    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12837            UserHandle user, String installerPackageName, String volumeUuid,
12838            PackageInstalledInfo res) {
12839        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12840
12841        // Remember this for later, in case we need to rollback this install
12842        String pkgName = pkg.packageName;
12843
12844        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12845
12846        synchronized(mPackages) {
12847            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12848                // A package with the same name is already installed, though
12849                // it has been renamed to an older name.  The package we
12850                // are trying to install should be installed as an update to
12851                // the existing one, but that has not been requested, so bail.
12852                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12853                        + " without first uninstalling package running as "
12854                        + mSettings.mRenamedPackages.get(pkgName));
12855                return;
12856            }
12857            if (mPackages.containsKey(pkgName)) {
12858                // Don't allow installation over an existing package with the same name.
12859                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12860                        + " without first uninstalling.");
12861                return;
12862            }
12863        }
12864
12865        try {
12866            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12867                    System.currentTimeMillis(), user);
12868
12869            updateSettingsLI(newPackage, installerPackageName, null, res, user);
12870
12871            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12872                prepareAppDataAfterInstall(newPackage);
12873
12874            } else {
12875                // Remove package from internal structures, but keep around any
12876                // data that might have already existed
12877                deletePackageLI(pkgName, UserHandle.ALL, false, null,
12878                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12879            }
12880        } catch (PackageManagerException e) {
12881            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12882        }
12883
12884        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12885    }
12886
12887    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12888        // Can't rotate keys during boot or if sharedUser.
12889        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12890                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12891            return false;
12892        }
12893        // app is using upgradeKeySets; make sure all are valid
12894        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12895        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12896        for (int i = 0; i < upgradeKeySets.length; i++) {
12897            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12898                Slog.wtf(TAG, "Package "
12899                         + (oldPs.name != null ? oldPs.name : "<null>")
12900                         + " contains upgrade-key-set reference to unknown key-set: "
12901                         + upgradeKeySets[i]
12902                         + " reverting to signatures check.");
12903                return false;
12904            }
12905        }
12906        return true;
12907    }
12908
12909    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12910        // Upgrade keysets are being used.  Determine if new package has a superset of the
12911        // required keys.
12912        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12913        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12914        for (int i = 0; i < upgradeKeySets.length; i++) {
12915            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12916            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12917                return true;
12918            }
12919        }
12920        return false;
12921    }
12922
12923    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12924            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
12925        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12926
12927        final PackageParser.Package oldPackage;
12928        final String pkgName = pkg.packageName;
12929        final int[] allUsers;
12930
12931        // First find the old package info and check signatures
12932        synchronized(mPackages) {
12933            oldPackage = mPackages.get(pkgName);
12934            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12935            if (isEphemeral && !oldIsEphemeral) {
12936                // can't downgrade from full to ephemeral
12937                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12938                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
12939                return;
12940            }
12941            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12942            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12943            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12944                if (!checkUpgradeKeySetLP(ps, pkg)) {
12945                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12946                            "New package not signed by keys specified by upgrade-keysets: "
12947                                    + pkgName);
12948                    return;
12949                }
12950            } else {
12951                // default to original signature matching
12952                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12953                        != PackageManager.SIGNATURE_MATCH) {
12954                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12955                            "New package has a different signature: " + pkgName);
12956                    return;
12957                }
12958            }
12959
12960            // In case of rollback, remember per-user/profile install state
12961            allUsers = sUserManager.getUserIds();
12962        }
12963
12964        // Update what is removed
12965        res.removedInfo = new PackageRemovedInfo();
12966        res.removedInfo.uid = oldPackage.applicationInfo.uid;
12967        res.removedInfo.removedPackage = oldPackage.packageName;
12968        res.removedInfo.isUpdate = true;
12969        final int childCount = (oldPackage.childPackages != null)
12970                ? oldPackage.childPackages.size() : 0;
12971        for (int i = 0; i < childCount; i++) {
12972            boolean childPackageUpdated = false;
12973            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
12974            if (res.addedChildPackages != null) {
12975                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
12976                if (childRes != null) {
12977                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
12978                    childRes.removedInfo.removedPackage = childPkg.packageName;
12979                    childRes.removedInfo.isUpdate = true;
12980                    childPackageUpdated = true;
12981                }
12982            }
12983            if (!childPackageUpdated) {
12984                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
12985                childRemovedRes.removedPackage = childPkg.packageName;
12986                childRemovedRes.isUpdate = false;
12987                childRemovedRes.dataRemoved = true;
12988                synchronized (mPackages) {
12989                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
12990                    if (childPs != null) {
12991                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
12992                    }
12993                }
12994                if (res.removedInfo.removedChildPackages == null) {
12995                    res.removedInfo.removedChildPackages = new ArrayMap<>();
12996                }
12997                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
12998            }
12999        }
13000
13001        boolean sysPkg = (isSystemApp(oldPackage));
13002        if (sysPkg) {
13003            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13004                    user, allUsers, installerPackageName, res);
13005        } else {
13006            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13007                    user, allUsers, installerPackageName, res);
13008        }
13009    }
13010
13011    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13012            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13013            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13014        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13015                + deletedPackage);
13016
13017        String pkgName = deletedPackage.packageName;
13018        boolean deletedPkg = true;
13019        boolean addedPkg = false;
13020
13021        final long origUpdateTime = (pkg.mExtras != null)
13022                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13023
13024        // First delete the existing package while retaining the data directory
13025        if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13026                res.removedInfo, true, pkg)) {
13027            // If the existing package wasn't successfully deleted
13028            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13029            deletedPkg = false;
13030        } else {
13031            // Successfully deleted the old package; proceed with replace.
13032
13033            // If deleted package lived in a container, give users a chance to
13034            // relinquish resources before killing.
13035            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13036                if (DEBUG_INSTALL) {
13037                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13038                }
13039                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13040                final ArrayList<String> pkgList = new ArrayList<String>(1);
13041                pkgList.add(deletedPackage.applicationInfo.packageName);
13042                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13043            }
13044
13045            deleteCodeCacheDirsLI(pkg);
13046
13047            try {
13048                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13049                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13050                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13051                prepareAppDataAfterInstall(newPackage);
13052                addedPkg = true;
13053            } catch (PackageManagerException e) {
13054                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13055            }
13056        }
13057
13058        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13059            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13060
13061            // Revert all internal state mutations and added folders for the failed install
13062            if (addedPkg) {
13063                deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13064                        res.removedInfo, true, null);
13065            }
13066
13067            // Restore the old package
13068            if (deletedPkg) {
13069                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13070                File restoreFile = new File(deletedPackage.codePath);
13071                // Parse old package
13072                boolean oldExternal = isExternal(deletedPackage);
13073                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13074                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13075                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13076                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13077                try {
13078                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13079                            null);
13080                } catch (PackageManagerException e) {
13081                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13082                            + e.getMessage());
13083                    return;
13084                }
13085
13086                synchronized (mPackages) {
13087                    // Ensure the installer package name up to date
13088                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13089
13090                    // Update permissions for restored package
13091                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13092
13093                    mSettings.writeLPr();
13094                }
13095
13096                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13097            }
13098        } else {
13099            synchronized (mPackages) {
13100                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13101                if (ps != null) {
13102                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13103                    if (res.removedInfo.removedChildPackages != null) {
13104                        final int childCount = res.removedInfo.removedChildPackages.size();
13105                        // Iterate in reverse as we may modify the collection
13106                        for (int i = childCount - 1; i >= 0; i--) {
13107                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13108                            if (res.addedChildPackages.containsKey(childPackageName)) {
13109                                res.removedInfo.removedChildPackages.removeAt(i);
13110                            } else {
13111                                PackageRemovedInfo childInfo = res.removedInfo
13112                                        .removedChildPackages.valueAt(i);
13113                                childInfo.removedForAllUsers = mPackages.get(
13114                                        childInfo.removedPackage) == null;
13115                            }
13116                        }
13117                    }
13118                }
13119            }
13120        }
13121    }
13122
13123    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13124            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13125            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13126        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13127                + ", old=" + deletedPackage);
13128
13129        final boolean disabledSystem;
13130
13131        // Set the system/privileged flags as needed
13132        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13133        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13134                != 0) {
13135            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13136        }
13137
13138        // Kill package processes including services, providers, etc.
13139        killPackage(deletedPackage, "replace sys pkg");
13140
13141        // Remove existing system package
13142        removePackageLI(deletedPackage, true);
13143
13144        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13145        if (!disabledSystem) {
13146            // We didn't need to disable the .apk as a current system package,
13147            // which means we are replacing another update that is already
13148            // installed.  We need to make sure to delete the older one's .apk.
13149            res.removedInfo.args = createInstallArgsForExisting(0,
13150                    deletedPackage.applicationInfo.getCodePath(),
13151                    deletedPackage.applicationInfo.getResourcePath(),
13152                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13153        } else {
13154            res.removedInfo.args = null;
13155        }
13156
13157        // Successfully disabled the old package. Now proceed with re-installation
13158        deleteCodeCacheDirsLI(pkg);
13159
13160        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13161        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13162                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13163
13164        PackageParser.Package newPackage = null;
13165        try {
13166            // Add the package to the internal data structures
13167            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13168
13169            // Set the update and install times
13170            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13171            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13172                    System.currentTimeMillis());
13173
13174            // Check for shared user id changes
13175            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13176                    deletedPackage, newPackage);
13177            if (invalidPackageName != null) {
13178                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13179                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13180                                + " to " + invalidPackageName);
13181            }
13182
13183            // Update the package dynamic state if succeeded
13184            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13185                // Now that the install succeeded make sure we remove data
13186                // directories for any child package the update removed.
13187                final int deletedChildCount = (deletedPackage.childPackages != null)
13188                        ? deletedPackage.childPackages.size() : 0;
13189                final int newChildCount = (newPackage.childPackages != null)
13190                        ? newPackage.childPackages.size() : 0;
13191                for (int i = 0; i < deletedChildCount; i++) {
13192                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13193                    boolean childPackageDeleted = true;
13194                    for (int j = 0; j < newChildCount; j++) {
13195                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13196                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13197                            childPackageDeleted = false;
13198                            break;
13199                        }
13200                    }
13201                    if (childPackageDeleted) {
13202                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13203                                deletedChildPkg.packageName);
13204                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13205                            PackageRemovedInfo removedChildRes = res.removedInfo
13206                                    .removedChildPackages.get(deletedChildPkg.packageName);
13207                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13208                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13209                        }
13210                    }
13211                }
13212
13213                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13214                prepareAppDataAfterInstall(newPackage);
13215            }
13216        } catch (PackageManagerException e) {
13217            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13218            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13219        }
13220
13221        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13222            // Re installation failed. Restore old information
13223            // Remove new pkg information
13224            if (newPackage != null) {
13225                removeInstalledPackageLI(newPackage, true);
13226            }
13227            // Add back the old system package
13228            try {
13229                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13230            } catch (PackageManagerException e) {
13231                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13232            }
13233
13234            synchronized (mPackages) {
13235                if (disabledSystem) {
13236                    enableSystemPackageLPw(deletedPackage);
13237                }
13238
13239                // Ensure the installer package name up to date
13240                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13241
13242                // Update permissions for restored package
13243                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13244
13245                mSettings.writeLPr();
13246            }
13247
13248            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13249                    + " after failed upgrade");
13250        }
13251    }
13252
13253    /**
13254     * Checks whether the parent or any of the child packages have a change shared
13255     * user. For a package to be a valid update the shred users of the parent and
13256     * the children should match. We may later support changing child shared users.
13257     * @param oldPkg The updated package.
13258     * @param newPkg The update package.
13259     * @return The shared user that change between the versions.
13260     */
13261    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13262            PackageParser.Package newPkg) {
13263        // Check parent shared user
13264        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13265            return newPkg.packageName;
13266        }
13267        // Check child shared users
13268        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13269        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13270        for (int i = 0; i < newChildCount; i++) {
13271            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13272            // If this child was present, did it have the same shared user?
13273            for (int j = 0; j < oldChildCount; j++) {
13274                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13275                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13276                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13277                    return newChildPkg.packageName;
13278                }
13279            }
13280        }
13281        return null;
13282    }
13283
13284    private void removeNativeBinariesLI(PackageParser.Package pkg) {
13285        // Remove the lib path for the parent package
13286        PackageSetting ps = (PackageSetting) pkg.mExtras;
13287        if (ps != null) {
13288            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13289        }
13290        // Remove the lib path for the child packages
13291        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13292        for (int i = 0; i < childCount; i++) {
13293            ps = (PackageSetting) pkg.childPackages.get(i).mExtras;
13294            if (ps != null) {
13295                NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13296            }
13297        }
13298    }
13299
13300    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13301        // Enable the parent package
13302        mSettings.enableSystemPackageLPw(pkg.packageName);
13303        // Enable the child packages
13304        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13305        for (int i = 0; i < childCount; i++) {
13306            PackageParser.Package childPkg = pkg.childPackages.get(i);
13307            mSettings.enableSystemPackageLPw(childPkg.packageName);
13308        }
13309    }
13310
13311    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13312            PackageParser.Package newPkg) {
13313        // Disable the parent package (parent always replaced)
13314        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13315        // Disable the child packages
13316        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13317        for (int i = 0; i < childCount; i++) {
13318            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13319            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13320            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13321        }
13322        return disabled;
13323    }
13324
13325    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13326            String installerPackageName) {
13327        // Enable the parent package
13328        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13329        // Enable the child packages
13330        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13331        for (int i = 0; i < childCount; i++) {
13332            PackageParser.Package childPkg = pkg.childPackages.get(i);
13333            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13334        }
13335    }
13336
13337    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13338        // Collect all used permissions in the UID
13339        ArraySet<String> usedPermissions = new ArraySet<>();
13340        final int packageCount = su.packages.size();
13341        for (int i = 0; i < packageCount; i++) {
13342            PackageSetting ps = su.packages.valueAt(i);
13343            if (ps.pkg == null) {
13344                continue;
13345            }
13346            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13347            for (int j = 0; j < requestedPermCount; j++) {
13348                String permission = ps.pkg.requestedPermissions.get(j);
13349                BasePermission bp = mSettings.mPermissions.get(permission);
13350                if (bp != null) {
13351                    usedPermissions.add(permission);
13352                }
13353            }
13354        }
13355
13356        PermissionsState permissionsState = su.getPermissionsState();
13357        // Prune install permissions
13358        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13359        final int installPermCount = installPermStates.size();
13360        for (int i = installPermCount - 1; i >= 0;  i--) {
13361            PermissionState permissionState = installPermStates.get(i);
13362            if (!usedPermissions.contains(permissionState.getName())) {
13363                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13364                if (bp != null) {
13365                    permissionsState.revokeInstallPermission(bp);
13366                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13367                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13368                }
13369            }
13370        }
13371
13372        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13373
13374        // Prune runtime permissions
13375        for (int userId : allUserIds) {
13376            List<PermissionState> runtimePermStates = permissionsState
13377                    .getRuntimePermissionStates(userId);
13378            final int runtimePermCount = runtimePermStates.size();
13379            for (int i = runtimePermCount - 1; i >= 0; i--) {
13380                PermissionState permissionState = runtimePermStates.get(i);
13381                if (!usedPermissions.contains(permissionState.getName())) {
13382                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13383                    if (bp != null) {
13384                        permissionsState.revokeRuntimePermission(bp, userId);
13385                        permissionsState.updatePermissionFlags(bp, userId,
13386                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13387                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13388                                runtimePermissionChangedUserIds, userId);
13389                    }
13390                }
13391            }
13392        }
13393
13394        return runtimePermissionChangedUserIds;
13395    }
13396
13397    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13398            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13399        // Update the parent package setting
13400        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13401                res, user);
13402        // Update the child packages setting
13403        final int childCount = (newPackage.childPackages != null)
13404                ? newPackage.childPackages.size() : 0;
13405        for (int i = 0; i < childCount; i++) {
13406            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13407            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13408            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13409                    childRes.origUsers, childRes, user);
13410        }
13411    }
13412
13413    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13414            String installerPackageName, int[] allUsers, int[] installedForUsers,
13415            PackageInstalledInfo res, UserHandle user) {
13416        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13417
13418        String pkgName = newPackage.packageName;
13419        synchronized (mPackages) {
13420            //write settings. the installStatus will be incomplete at this stage.
13421            //note that the new package setting would have already been
13422            //added to mPackages. It hasn't been persisted yet.
13423            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13424            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13425            mSettings.writeLPr();
13426            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13427        }
13428
13429        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13430        synchronized (mPackages) {
13431            updatePermissionsLPw(newPackage.packageName, newPackage,
13432                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13433                            ? UPDATE_PERMISSIONS_ALL : 0));
13434            // For system-bundled packages, we assume that installing an upgraded version
13435            // of the package implies that the user actually wants to run that new code,
13436            // so we enable the package.
13437            PackageSetting ps = mSettings.mPackages.get(pkgName);
13438            final int userId = user.getIdentifier();
13439            if (ps != null) {
13440                if (isSystemApp(newPackage)) {
13441                    if (DEBUG_INSTALL) {
13442                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13443                    }
13444                    // Enable system package for requested users
13445                    if (res.origUsers != null) {
13446                        for (int origUserId : res.origUsers) {
13447                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13448                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13449                                        origUserId, installerPackageName);
13450                            }
13451                        }
13452                    }
13453                    // Also convey the prior install/uninstall state
13454                    if (allUsers != null && installedForUsers != null) {
13455                        for (int currentUserId : allUsers) {
13456                            final boolean installed = ArrayUtils.contains(
13457                                    installedForUsers, currentUserId);
13458                            if (DEBUG_INSTALL) {
13459                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13460                            }
13461                            ps.setInstalled(installed, currentUserId);
13462                        }
13463                        // these install state changes will be persisted in the
13464                        // upcoming call to mSettings.writeLPr().
13465                    }
13466                }
13467                // It's implied that when a user requests installation, they want the app to be
13468                // installed and enabled.
13469                if (userId != UserHandle.USER_ALL) {
13470                    ps.setInstalled(true, userId);
13471                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13472                }
13473            }
13474            res.name = pkgName;
13475            res.uid = newPackage.applicationInfo.uid;
13476            res.pkg = newPackage;
13477            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13478            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13479            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13480            //to update install status
13481            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13482            mSettings.writeLPr();
13483            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13484        }
13485
13486        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13487    }
13488
13489    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13490        try {
13491            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13492            installPackageLI(args, res);
13493        } finally {
13494            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13495        }
13496    }
13497
13498    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13499        final int installFlags = args.installFlags;
13500        final String installerPackageName = args.installerPackageName;
13501        final String volumeUuid = args.volumeUuid;
13502        final File tmpPackageFile = new File(args.getCodePath());
13503        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13504        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13505                || (args.volumeUuid != null));
13506        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13507        boolean replace = false;
13508        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13509        if (args.move != null) {
13510            // moving a complete application; perform an initial scan on the new install location
13511            scanFlags |= SCAN_INITIAL;
13512        }
13513
13514        // Result object to be returned
13515        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13516
13517        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13518
13519        // Sanity check
13520        if (ephemeral && (forwardLocked || onExternal)) {
13521            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13522                    + " external=" + onExternal);
13523            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13524            return;
13525        }
13526
13527        // Retrieve PackageSettings and parse package
13528        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13529                | PackageParser.PARSE_ENFORCE_CODE
13530                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13531                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13532                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13533        PackageParser pp = new PackageParser();
13534        pp.setSeparateProcesses(mSeparateProcesses);
13535        pp.setDisplayMetrics(mMetrics);
13536
13537        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13538        final PackageParser.Package pkg;
13539        try {
13540            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13541        } catch (PackageParserException e) {
13542            res.setError("Failed parse during installPackageLI", e);
13543            return;
13544        } finally {
13545            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13546        }
13547
13548        // If we are installing a clustered package add results for the children
13549        if (pkg.childPackages != null) {
13550            synchronized (mPackages) {
13551                final int childCount = pkg.childPackages.size();
13552                for (int i = 0; i < childCount; i++) {
13553                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13554                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13555                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13556                    childRes.pkg = childPkg;
13557                    childRes.name = childPkg.packageName;
13558                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13559                    if (childPs != null) {
13560                        childRes.origUsers = childPs.queryInstalledUsers(
13561                                sUserManager.getUserIds(), true);
13562                    }
13563                    if ((mPackages.containsKey(childPkg.packageName))) {
13564                        childRes.removedInfo = new PackageRemovedInfo();
13565                        childRes.removedInfo.removedPackage = childPkg.packageName;
13566                    }
13567                    if (res.addedChildPackages == null) {
13568                        res.addedChildPackages = new ArrayMap<>();
13569                    }
13570                    res.addedChildPackages.put(childPkg.packageName, childRes);
13571                }
13572            }
13573        }
13574
13575        // If package doesn't declare API override, mark that we have an install
13576        // time CPU ABI override.
13577        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13578            pkg.cpuAbiOverride = args.abiOverride;
13579        }
13580
13581        String pkgName = res.name = pkg.packageName;
13582        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13583            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13584                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13585                return;
13586            }
13587        }
13588
13589        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13590        try {
13591            PackageParser.collectCertificates(pkg, parseFlags);
13592        } catch (PackageParserException e) {
13593            res.setError("Failed collect during installPackageLI", e);
13594            return;
13595        } finally {
13596            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13597        }
13598
13599        // Get rid of all references to package scan path via parser.
13600        pp = null;
13601        String oldCodePath = null;
13602        boolean systemApp = false;
13603        synchronized (mPackages) {
13604            // Check if installing already existing package
13605            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13606                String oldName = mSettings.mRenamedPackages.get(pkgName);
13607                if (pkg.mOriginalPackages != null
13608                        && pkg.mOriginalPackages.contains(oldName)
13609                        && mPackages.containsKey(oldName)) {
13610                    // This package is derived from an original package,
13611                    // and this device has been updating from that original
13612                    // name.  We must continue using the original name, so
13613                    // rename the new package here.
13614                    pkg.setPackageName(oldName);
13615                    pkgName = pkg.packageName;
13616                    replace = true;
13617                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13618                            + oldName + " pkgName=" + pkgName);
13619                } else if (mPackages.containsKey(pkgName)) {
13620                    // This package, under its official name, already exists
13621                    // on the device; we should replace it.
13622                    replace = true;
13623                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13624                }
13625
13626                // Child packages are installed through the parent package
13627                if (pkg.parentPackage != null) {
13628                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13629                            "Package " + pkg.packageName + " is child of package "
13630                                    + pkg.parentPackage.parentPackage + ". Child packages "
13631                                    + "can be updated only through the parent package.");
13632                    return;
13633                }
13634
13635                if (replace) {
13636                    // Prevent apps opting out from runtime permissions
13637                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13638                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13639                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13640                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13641                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13642                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13643                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13644                                        + " doesn't support runtime permissions but the old"
13645                                        + " target SDK " + oldTargetSdk + " does.");
13646                        return;
13647                    }
13648
13649                    // Prevent installing of child packages
13650                    if (oldPackage.parentPackage != null) {
13651                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13652                                "Package " + pkg.packageName + " is child of package "
13653                                        + oldPackage.parentPackage + ". Child packages "
13654                                        + "can be updated only through the parent package.");
13655                        return;
13656                    }
13657                }
13658            }
13659
13660            PackageSetting ps = mSettings.mPackages.get(pkgName);
13661            if (ps != null) {
13662                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13663
13664                // Quick sanity check that we're signed correctly if updating;
13665                // we'll check this again later when scanning, but we want to
13666                // bail early here before tripping over redefined permissions.
13667                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13668                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13669                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13670                                + pkg.packageName + " upgrade keys do not match the "
13671                                + "previously installed version");
13672                        return;
13673                    }
13674                } else {
13675                    try {
13676                        verifySignaturesLP(ps, pkg);
13677                    } catch (PackageManagerException e) {
13678                        res.setError(e.error, e.getMessage());
13679                        return;
13680                    }
13681                }
13682
13683                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13684                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13685                    systemApp = (ps.pkg.applicationInfo.flags &
13686                            ApplicationInfo.FLAG_SYSTEM) != 0;
13687                }
13688                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13689            }
13690
13691            // Check whether the newly-scanned package wants to define an already-defined perm
13692            int N = pkg.permissions.size();
13693            for (int i = N-1; i >= 0; i--) {
13694                PackageParser.Permission perm = pkg.permissions.get(i);
13695                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13696                if (bp != null) {
13697                    // If the defining package is signed with our cert, it's okay.  This
13698                    // also includes the "updating the same package" case, of course.
13699                    // "updating same package" could also involve key-rotation.
13700                    final boolean sigsOk;
13701                    if (bp.sourcePackage.equals(pkg.packageName)
13702                            && (bp.packageSetting instanceof PackageSetting)
13703                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13704                                    scanFlags))) {
13705                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13706                    } else {
13707                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13708                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13709                    }
13710                    if (!sigsOk) {
13711                        // If the owning package is the system itself, we log but allow
13712                        // install to proceed; we fail the install on all other permission
13713                        // redefinitions.
13714                        if (!bp.sourcePackage.equals("android")) {
13715                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13716                                    + pkg.packageName + " attempting to redeclare permission "
13717                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13718                            res.origPermission = perm.info.name;
13719                            res.origPackage = bp.sourcePackage;
13720                            return;
13721                        } else {
13722                            Slog.w(TAG, "Package " + pkg.packageName
13723                                    + " attempting to redeclare system permission "
13724                                    + perm.info.name + "; ignoring new declaration");
13725                            pkg.permissions.remove(i);
13726                        }
13727                    }
13728                }
13729            }
13730        }
13731
13732        if (systemApp) {
13733            if (onExternal) {
13734                // Abort update; system app can't be replaced with app on sdcard
13735                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13736                        "Cannot install updates to system apps on sdcard");
13737                return;
13738            } else if (ephemeral) {
13739                // Abort update; system app can't be replaced with an ephemeral app
13740                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13741                        "Cannot update a system app with an ephemeral app");
13742                return;
13743            }
13744        }
13745
13746        if (args.move != null) {
13747            // We did an in-place move, so dex is ready to roll
13748            scanFlags |= SCAN_NO_DEX;
13749            scanFlags |= SCAN_MOVE;
13750
13751            synchronized (mPackages) {
13752                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13753                if (ps == null) {
13754                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13755                            "Missing settings for moved package " + pkgName);
13756                }
13757
13758                // We moved the entire application as-is, so bring over the
13759                // previously derived ABI information.
13760                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13761                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13762            }
13763
13764        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13765            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13766            scanFlags |= SCAN_NO_DEX;
13767
13768            try {
13769                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13770                    args.abiOverride : pkg.cpuAbiOverride);
13771                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13772                        true /* extract libs */);
13773            } catch (PackageManagerException pme) {
13774                Slog.e(TAG, "Error deriving application ABI", pme);
13775                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13776                return;
13777            }
13778
13779            // Extract package to save the VM unzipping the APK in memory during
13780            // launch. Only do this if profile-guided compilation is enabled because
13781            // otherwise BackgroundDexOptService will not dexopt the package later.
13782            if (mUseJitProfiles) {
13783                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13784                // Do not run PackageDexOptimizer through the local performDexOpt
13785                // method because `pkg` is not in `mPackages` yet.
13786                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13787                        false /* useProfiles */, true /* extractOnly */);
13788                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13789                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13790                    String msg = "Extracking package failed for " + pkgName;
13791                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13792                    return;
13793                }
13794            }
13795        }
13796
13797        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13798            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13799            return;
13800        }
13801
13802        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13803
13804        if (replace) {
13805            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13806                    installerPackageName, res);
13807        } else {
13808            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13809                    args.user, installerPackageName, volumeUuid, res);
13810        }
13811        synchronized (mPackages) {
13812            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13813            if (ps != null) {
13814                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13815            }
13816
13817            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13818            for (int i = 0; i < childCount; i++) {
13819                PackageParser.Package childPkg = pkg.childPackages.get(i);
13820                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13821                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13822                if (childPs != null) {
13823                    childRes.newUsers = childPs.queryInstalledUsers(
13824                            sUserManager.getUserIds(), true);
13825                }
13826            }
13827        }
13828    }
13829
13830    private void startIntentFilterVerifications(int userId, boolean replacing,
13831            PackageParser.Package pkg) {
13832        if (mIntentFilterVerifierComponent == null) {
13833            Slog.w(TAG, "No IntentFilter verification will not be done as "
13834                    + "there is no IntentFilterVerifier available!");
13835            return;
13836        }
13837
13838        final int verifierUid = getPackageUid(
13839                mIntentFilterVerifierComponent.getPackageName(),
13840                MATCH_DEBUG_TRIAGED_MISSING,
13841                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13842
13843        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13844        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13845        mHandler.sendMessage(msg);
13846
13847        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13848        for (int i = 0; i < childCount; i++) {
13849            PackageParser.Package childPkg = pkg.childPackages.get(i);
13850            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13851            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
13852            mHandler.sendMessage(msg);
13853        }
13854    }
13855
13856    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13857            PackageParser.Package pkg) {
13858        int size = pkg.activities.size();
13859        if (size == 0) {
13860            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13861                    "No activity, so no need to verify any IntentFilter!");
13862            return;
13863        }
13864
13865        final boolean hasDomainURLs = hasDomainURLs(pkg);
13866        if (!hasDomainURLs) {
13867            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13868                    "No domain URLs, so no need to verify any IntentFilter!");
13869            return;
13870        }
13871
13872        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13873                + " if any IntentFilter from the " + size
13874                + " Activities needs verification ...");
13875
13876        int count = 0;
13877        final String packageName = pkg.packageName;
13878
13879        synchronized (mPackages) {
13880            // If this is a new install and we see that we've already run verification for this
13881            // package, we have nothing to do: it means the state was restored from backup.
13882            if (!replacing) {
13883                IntentFilterVerificationInfo ivi =
13884                        mSettings.getIntentFilterVerificationLPr(packageName);
13885                if (ivi != null) {
13886                    if (DEBUG_DOMAIN_VERIFICATION) {
13887                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13888                                + ivi.getStatusString());
13889                    }
13890                    return;
13891                }
13892            }
13893
13894            // If any filters need to be verified, then all need to be.
13895            boolean needToVerify = false;
13896            for (PackageParser.Activity a : pkg.activities) {
13897                for (ActivityIntentInfo filter : a.intents) {
13898                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13899                        if (DEBUG_DOMAIN_VERIFICATION) {
13900                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13901                        }
13902                        needToVerify = true;
13903                        break;
13904                    }
13905                }
13906            }
13907
13908            if (needToVerify) {
13909                final int verificationId = mIntentFilterVerificationToken++;
13910                for (PackageParser.Activity a : pkg.activities) {
13911                    for (ActivityIntentInfo filter : a.intents) {
13912                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13913                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13914                                    "Verification needed for IntentFilter:" + filter.toString());
13915                            mIntentFilterVerifier.addOneIntentFilterVerification(
13916                                    verifierUid, userId, verificationId, filter, packageName);
13917                            count++;
13918                        }
13919                    }
13920                }
13921            }
13922        }
13923
13924        if (count > 0) {
13925            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13926                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13927                    +  " for userId:" + userId);
13928            mIntentFilterVerifier.startVerifications(userId);
13929        } else {
13930            if (DEBUG_DOMAIN_VERIFICATION) {
13931                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13932            }
13933        }
13934    }
13935
13936    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13937        final ComponentName cn  = filter.activity.getComponentName();
13938        final String packageName = cn.getPackageName();
13939
13940        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13941                packageName);
13942        if (ivi == null) {
13943            return true;
13944        }
13945        int status = ivi.getStatus();
13946        switch (status) {
13947            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13948            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13949                return true;
13950
13951            default:
13952                // Nothing to do
13953                return false;
13954        }
13955    }
13956
13957    private static boolean isMultiArch(ApplicationInfo info) {
13958        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13959    }
13960
13961    private static boolean isExternal(PackageParser.Package pkg) {
13962        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13963    }
13964
13965    private static boolean isExternal(PackageSetting ps) {
13966        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13967    }
13968
13969    private static boolean isEphemeral(PackageParser.Package pkg) {
13970        return pkg.applicationInfo.isEphemeralApp();
13971    }
13972
13973    private static boolean isEphemeral(PackageSetting ps) {
13974        return ps.pkg != null && isEphemeral(ps.pkg);
13975    }
13976
13977    private static boolean isSystemApp(PackageParser.Package pkg) {
13978        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13979    }
13980
13981    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13982        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13983    }
13984
13985    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13986        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13987    }
13988
13989    private static boolean isSystemApp(PackageSetting ps) {
13990        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13991    }
13992
13993    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13994        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13995    }
13996
13997    private int packageFlagsToInstallFlags(PackageSetting ps) {
13998        int installFlags = 0;
13999        if (isEphemeral(ps)) {
14000            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14001        }
14002        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14003            // This existing package was an external ASEC install when we have
14004            // the external flag without a UUID
14005            installFlags |= PackageManager.INSTALL_EXTERNAL;
14006        }
14007        if (ps.isForwardLocked()) {
14008            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14009        }
14010        return installFlags;
14011    }
14012
14013    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14014        if (isExternal(pkg)) {
14015            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14016                return StorageManager.UUID_PRIMARY_PHYSICAL;
14017            } else {
14018                return pkg.volumeUuid;
14019            }
14020        } else {
14021            return StorageManager.UUID_PRIVATE_INTERNAL;
14022        }
14023    }
14024
14025    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14026        if (isExternal(pkg)) {
14027            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14028                return mSettings.getExternalVersion();
14029            } else {
14030                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14031            }
14032        } else {
14033            return mSettings.getInternalVersion();
14034        }
14035    }
14036
14037    private void deleteTempPackageFiles() {
14038        final FilenameFilter filter = new FilenameFilter() {
14039            public boolean accept(File dir, String name) {
14040                return name.startsWith("vmdl") && name.endsWith(".tmp");
14041            }
14042        };
14043        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14044            file.delete();
14045        }
14046    }
14047
14048    @Override
14049    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14050            int flags) {
14051        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14052                flags);
14053    }
14054
14055    @Override
14056    public void deletePackage(final String packageName,
14057            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14058        mContext.enforceCallingOrSelfPermission(
14059                android.Manifest.permission.DELETE_PACKAGES, null);
14060        Preconditions.checkNotNull(packageName);
14061        Preconditions.checkNotNull(observer);
14062        final int uid = Binder.getCallingUid();
14063        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14064        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14065        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14066            mContext.enforceCallingOrSelfPermission(
14067                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14068                    "deletePackage for user " + userId);
14069        }
14070
14071        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14072            try {
14073                observer.onPackageDeleted(packageName,
14074                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14075            } catch (RemoteException re) {
14076            }
14077            return;
14078        }
14079
14080        for (int currentUserId : users) {
14081            if (getBlockUninstallForUser(packageName, currentUserId)) {
14082                try {
14083                    observer.onPackageDeleted(packageName,
14084                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14085                } catch (RemoteException re) {
14086                }
14087                return;
14088            }
14089        }
14090
14091        if (DEBUG_REMOVE) {
14092            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
14093        }
14094        // Queue up an async operation since the package deletion may take a little while.
14095        mHandler.post(new Runnable() {
14096            public void run() {
14097                mHandler.removeCallbacks(this);
14098                final int returnCode = deletePackageX(packageName, userId, flags);
14099                try {
14100                    observer.onPackageDeleted(packageName, returnCode, null);
14101                } catch (RemoteException e) {
14102                    Log.i(TAG, "Observer no longer exists.");
14103                } //end catch
14104            } //end run
14105        });
14106    }
14107
14108    @Override
14109    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14110        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14111    }
14112
14113    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14114        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14115                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14116        try {
14117            if (dpm != null) {
14118                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14119                        /* callingUserOnly =*/ false);
14120                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14121                        : deviceOwnerComponentName.getPackageName();
14122                // Does the package contains the device owner?
14123                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14124                // this check is probably not needed, since DO should be registered as a device
14125                // admin on some user too. (Original bug for this: b/17657954)
14126                if (packageName.equals(deviceOwnerPackageName)) {
14127                    return true;
14128                }
14129                // Does it contain a device admin for any user?
14130                int[] users;
14131                if (userId == UserHandle.USER_ALL) {
14132                    users = sUserManager.getUserIds();
14133                } else {
14134                    users = new int[]{userId};
14135                }
14136                for (int i = 0; i < users.length; ++i) {
14137                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14138                        return true;
14139                    }
14140                }
14141            }
14142        } catch (RemoteException e) {
14143        }
14144        return false;
14145    }
14146
14147    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14148        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14149    }
14150
14151    /**
14152     *  This method is an internal method that could be get invoked either
14153     *  to delete an installed package or to clean up a failed installation.
14154     *  After deleting an installed package, a broadcast is sent to notify any
14155     *  listeners that the package has been installed. For cleaning up a failed
14156     *  installation, the broadcast is not necessary since the package's
14157     *  installation wouldn't have sent the initial broadcast either
14158     *  The key steps in deleting a package are
14159     *  deleting the package information in internal structures like mPackages,
14160     *  deleting the packages base directories through installd
14161     *  updating mSettings to reflect current status
14162     *  persisting settings for later use
14163     *  sending a broadcast if necessary
14164     */
14165    private int deletePackageX(String packageName, int userId, int flags) {
14166        final PackageRemovedInfo info = new PackageRemovedInfo();
14167        final boolean res;
14168
14169        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14170                ? UserHandle.ALL : new UserHandle(userId);
14171
14172        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14173            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14174            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14175        }
14176
14177        PackageSetting uninstalledPs = null;
14178
14179        // for the uninstall-updates case and restricted profiles, remember the per-
14180        // user handle installed state
14181        int[] allUsers;
14182        synchronized (mPackages) {
14183            uninstalledPs = mSettings.mPackages.get(packageName);
14184            if (uninstalledPs == null) {
14185                Slog.w(TAG, "Not removing non-existent package " + packageName);
14186                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14187            }
14188            allUsers = sUserManager.getUserIds();
14189            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14190        }
14191
14192        synchronized (mInstallLock) {
14193            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14194            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14195                    flags | REMOVE_CHATTY, info, true, null);
14196            synchronized (mPackages) {
14197                if (res) {
14198                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14199                }
14200            }
14201        }
14202
14203        if (res) {
14204            info.sendPackageRemovedBroadcasts();
14205            info.sendSystemPackageUpdatedBroadcasts();
14206            info.sendSystemPackageAppearedBroadcasts();
14207        }
14208        // Force a gc here.
14209        Runtime.getRuntime().gc();
14210        // Delete the resources here after sending the broadcast to let
14211        // other processes clean up before deleting resources.
14212        if (info.args != null) {
14213            synchronized (mInstallLock) {
14214                info.args.doPostDeleteLI(true);
14215            }
14216        }
14217
14218        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14219    }
14220
14221    class PackageRemovedInfo {
14222        String removedPackage;
14223        int uid = -1;
14224        int removedAppId = -1;
14225        int[] origUsers;
14226        int[] removedUsers = null;
14227        boolean isRemovedPackageSystemUpdate = false;
14228        boolean isUpdate;
14229        boolean dataRemoved;
14230        boolean removedForAllUsers;
14231        // Clean up resources deleted packages.
14232        InstallArgs args = null;
14233        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14234        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14235
14236        void sendPackageRemovedBroadcasts() {
14237            sendPackageRemovedBroadcastInternal();
14238            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14239            for (int i = 0; i < childCount; i++) {
14240                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14241                childInfo.sendPackageRemovedBroadcastInternal();
14242            }
14243        }
14244
14245        void sendSystemPackageUpdatedBroadcasts() {
14246            if (isRemovedPackageSystemUpdate) {
14247                sendSystemPackageUpdatedBroadcastsInternal();
14248                final int childCount = (removedChildPackages != null)
14249                        ? removedChildPackages.size() : 0;
14250                for (int i = 0; i < childCount; i++) {
14251                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14252                    if (childInfo.isRemovedPackageSystemUpdate) {
14253                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14254                    }
14255                }
14256            }
14257        }
14258
14259        void sendSystemPackageAppearedBroadcasts() {
14260            final int packageCount = (appearedChildPackages != null)
14261                    ? appearedChildPackages.size() : 0;
14262            for (int i = 0; i < packageCount; i++) {
14263                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14264                for (int userId : installedInfo.newUsers) {
14265                    sendPackageAddedForUser(installedInfo.name, true,
14266                            UserHandle.getAppId(installedInfo.uid), userId);
14267                }
14268            }
14269        }
14270
14271        private void sendSystemPackageUpdatedBroadcastsInternal() {
14272            Bundle extras = new Bundle(2);
14273            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14274            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14275            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14276                    extras, 0, null, null, null);
14277            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14278                    extras, 0, null, null, null);
14279            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14280                    null, 0, removedPackage, null, null);
14281        }
14282
14283        private void sendPackageRemovedBroadcastInternal() {
14284            Bundle extras = new Bundle(2);
14285            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14286            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14287            if (isUpdate || isRemovedPackageSystemUpdate) {
14288                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14289            }
14290            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14291            if (removedPackage != null) {
14292                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14293                        extras, 0, null, null, removedUsers);
14294                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14295                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14296                            removedPackage, extras, 0, null, null, removedUsers);
14297                }
14298            }
14299            if (removedAppId >= 0) {
14300                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14301                        removedUsers);
14302            }
14303        }
14304    }
14305
14306    /*
14307     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14308     * flag is not set, the data directory is removed as well.
14309     * make sure this flag is set for partially installed apps. If not its meaningless to
14310     * delete a partially installed application.
14311     */
14312    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14313            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14314        String packageName = ps.name;
14315        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14316        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14317        // Retrieve object to delete permissions for shared user later on
14318        final PackageSetting deletedPs;
14319        // reader
14320        synchronized (mPackages) {
14321            deletedPs = mSettings.mPackages.get(packageName);
14322            if (outInfo != null) {
14323                outInfo.removedPackage = packageName;
14324                outInfo.removedUsers = deletedPs != null
14325                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14326                        : null;
14327            }
14328        }
14329        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14330            removeDataDirsLI(ps.volumeUuid, packageName);
14331            if (outInfo != null) {
14332                outInfo.dataRemoved = true;
14333            }
14334            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14335        }
14336        // writer
14337        synchronized (mPackages) {
14338            if (deletedPs != null) {
14339                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14340                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14341                    clearDefaultBrowserIfNeeded(packageName);
14342                    if (outInfo != null) {
14343                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14344                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14345                    }
14346                    updatePermissionsLPw(deletedPs.name, null, 0);
14347                    if (deletedPs.sharedUser != null) {
14348                        // Remove permissions associated with package. Since runtime
14349                        // permissions are per user we have to kill the removed package
14350                        // or packages running under the shared user of the removed
14351                        // package if revoking the permissions requested only by the removed
14352                        // package is successful and this causes a change in gids.
14353                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14354                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14355                                    userId);
14356                            if (userIdToKill == UserHandle.USER_ALL
14357                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14358                                // If gids changed for this user, kill all affected packages.
14359                                mHandler.post(new Runnable() {
14360                                    @Override
14361                                    public void run() {
14362                                        // This has to happen with no lock held.
14363                                        killApplication(deletedPs.name, deletedPs.appId,
14364                                                KILL_APP_REASON_GIDS_CHANGED);
14365                                    }
14366                                });
14367                                break;
14368                            }
14369                        }
14370                    }
14371                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14372                }
14373                // make sure to preserve per-user disabled state if this removal was just
14374                // a downgrade of a system app to the factory package
14375                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14376                    if (DEBUG_REMOVE) {
14377                        Slog.d(TAG, "Propagating install state across downgrade");
14378                    }
14379                    for (int userId : allUserHandles) {
14380                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14381                        if (DEBUG_REMOVE) {
14382                            Slog.d(TAG, "    user " + userId + " => " + installed);
14383                        }
14384                        ps.setInstalled(installed, userId);
14385                    }
14386                }
14387            }
14388            // can downgrade to reader
14389            if (writeSettings) {
14390                // Save settings now
14391                mSettings.writeLPr();
14392            }
14393        }
14394        if (outInfo != null) {
14395            // A user ID was deleted here. Go through all users and remove it
14396            // from KeyStore.
14397            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14398        }
14399    }
14400
14401    static boolean locationIsPrivileged(File path) {
14402        try {
14403            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14404                    .getCanonicalPath();
14405            return path.getCanonicalPath().startsWith(privilegedAppDir);
14406        } catch (IOException e) {
14407            Slog.e(TAG, "Unable to access code path " + path);
14408        }
14409        return false;
14410    }
14411
14412    /*
14413     * Tries to delete system package.
14414     */
14415    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14416            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14417            boolean writeSettings) {
14418        if (deletedPkg.parentPackage != null) {
14419            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14420            return false;
14421        }
14422
14423        final boolean applyUserRestrictions
14424                = (allUserHandles != null) && (outInfo.origUsers != null);
14425        final PackageSetting disabledPs;
14426        // Confirm if the system package has been updated
14427        // An updated system app can be deleted. This will also have to restore
14428        // the system pkg from system partition
14429        // reader
14430        synchronized (mPackages) {
14431            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName);
14432        }
14433
14434        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14435                + " disabledPs=" + disabledPs);
14436
14437        if (disabledPs == null) {
14438            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14439            return false;
14440        } else if (DEBUG_REMOVE) {
14441            Slog.d(TAG, "Deleting system pkg from data partition");
14442        }
14443
14444        if (DEBUG_REMOVE) {
14445            if (applyUserRestrictions) {
14446                Slog.d(TAG, "Remembering install states:");
14447                for (int userId : allUserHandles) {
14448                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14449                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14450                }
14451            }
14452        }
14453
14454        // Delete the updated package
14455        outInfo.isRemovedPackageSystemUpdate = true;
14456        if (outInfo.removedChildPackages != null) {
14457            final int childCount = (deletedPkg.childPackages != null)
14458                    ? deletedPkg.childPackages.size() : 0;
14459            for (int i = 0; i < childCount; i++) {
14460                String childPackageName = deletedPkg.childPackages.get(i).packageName;
14461                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14462                        .contains(childPackageName)) {
14463                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14464                            childPackageName);
14465                    if (childInfo != null) {
14466                        childInfo.isRemovedPackageSystemUpdate = true;
14467                    }
14468                }
14469            }
14470        }
14471
14472        if (disabledPs.versionCode < deletedPs.versionCode) {
14473            // Delete data for downgrades
14474            flags &= ~PackageManager.DELETE_KEEP_DATA;
14475        } else {
14476            // Preserve data by setting flag
14477            flags |= PackageManager.DELETE_KEEP_DATA;
14478        }
14479
14480        boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles,
14481                outInfo, writeSettings, disabledPs.pkg);
14482        if (!ret) {
14483            return false;
14484        }
14485
14486        // writer
14487        synchronized (mPackages) {
14488            // Reinstate the old system package
14489            enableSystemPackageLPw(disabledPs.pkg);
14490            // Remove any native libraries from the upgraded package.
14491            removeNativeBinariesLI(deletedPkg);
14492        }
14493
14494        // Install the system package
14495        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14496        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14497        if (locationIsPrivileged(disabledPs.codePath)) {
14498            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14499        }
14500
14501        final PackageParser.Package newPkg;
14502        try {
14503            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14504        } catch (PackageManagerException e) {
14505            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14506                    + e.getMessage());
14507            return false;
14508        }
14509
14510        prepareAppDataAfterInstall(newPkg);
14511
14512        // writer
14513        synchronized (mPackages) {
14514            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14515
14516            // Propagate the permissions state as we do not want to drop on the floor
14517            // runtime permissions. The update permissions method below will take
14518            // care of removing obsolete permissions and grant install permissions.
14519            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14520            updatePermissionsLPw(newPkg.packageName, newPkg,
14521                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14522
14523            if (applyUserRestrictions) {
14524                if (DEBUG_REMOVE) {
14525                    Slog.d(TAG, "Propagating install state across reinstall");
14526                }
14527                for (int userId : allUserHandles) {
14528                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14529                    if (DEBUG_REMOVE) {
14530                        Slog.d(TAG, "    user " + userId + " => " + installed);
14531                    }
14532                    ps.setInstalled(installed, userId);
14533
14534                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14535                }
14536                // Regardless of writeSettings we need to ensure that this restriction
14537                // state propagation is persisted
14538                mSettings.writeAllUsersPackageRestrictionsLPr();
14539            }
14540            // can downgrade to reader here
14541            if (writeSettings) {
14542                mSettings.writeLPr();
14543            }
14544        }
14545        return true;
14546    }
14547
14548    private boolean deleteInstalledPackageLI(PackageParser.Package pkg,
14549            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14550            PackageRemovedInfo outInfo, boolean writeSettings,
14551            PackageParser.Package replacingPackage) {
14552        PackageSetting ps = null;
14553
14554        synchronized (mPackages) {
14555            pkg = mPackages.get(pkg.packageName);
14556            if (pkg == null) {
14557                return false;
14558            }
14559
14560            ps = mSettings.mPackages.get(pkg.packageName);
14561            if (ps == null) {
14562                return false;
14563            }
14564
14565            if (outInfo != null) {
14566                outInfo.uid = ps.appId;
14567            }
14568
14569            if (outInfo != null && outInfo.removedChildPackages != null) {
14570                final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14571                for (int i = 0; i < childCount; i++) {
14572                    String childPackageName = ps.childPackageNames.get(i);
14573                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14574                    if (childPs == null) {
14575                        return false;
14576                    }
14577                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14578                            childPackageName);
14579                    if (childInfo != null) {
14580                        childInfo.uid = childPs.appId;
14581                    }
14582                }
14583            }
14584        }
14585
14586        // Delete package data from internal structures and also remove data if flag is set
14587        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14588
14589        // Delete the child packages data
14590        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14591        for (int i = 0; i < childCount; i++) {
14592            PackageSetting childPs;
14593            synchronized (mPackages) {
14594                childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName);
14595            }
14596            if (childPs != null) {
14597                PackageRemovedInfo childOutInfo = (outInfo != null
14598                        && outInfo.removedChildPackages != null)
14599                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14600                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14601                        && (replacingPackage != null
14602                        && !replacingPackage.hasChildPackage(childPs.name))
14603                        ? flags & ~DELETE_KEEP_DATA : flags;
14604                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14605                        deleteFlags, writeSettings);
14606            }
14607        }
14608
14609        // Delete application code and resources only for parent packages
14610        if (ps.pkg.parentPackage == null) {
14611            if (deleteCodeAndResources && (outInfo != null)) {
14612                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14613                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14614                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14615            }
14616        }
14617
14618        return true;
14619    }
14620
14621    @Override
14622    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14623            int userId) {
14624        mContext.enforceCallingOrSelfPermission(
14625                android.Manifest.permission.DELETE_PACKAGES, null);
14626        synchronized (mPackages) {
14627            PackageSetting ps = mSettings.mPackages.get(packageName);
14628            if (ps == null) {
14629                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14630                return false;
14631            }
14632            if (!ps.getInstalled(userId)) {
14633                // Can't block uninstall for an app that is not installed or enabled.
14634                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14635                return false;
14636            }
14637            ps.setBlockUninstall(blockUninstall, userId);
14638            mSettings.writePackageRestrictionsLPr(userId);
14639        }
14640        return true;
14641    }
14642
14643    @Override
14644    public boolean getBlockUninstallForUser(String packageName, int userId) {
14645        synchronized (mPackages) {
14646            PackageSetting ps = mSettings.mPackages.get(packageName);
14647            if (ps == null) {
14648                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14649                return false;
14650            }
14651            return ps.getBlockUninstall(userId);
14652        }
14653    }
14654
14655    @Override
14656    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14657        int callingUid = Binder.getCallingUid();
14658        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14659            throw new SecurityException(
14660                    "setRequiredForSystemUser can only be run by the system or root");
14661        }
14662        synchronized (mPackages) {
14663            PackageSetting ps = mSettings.mPackages.get(packageName);
14664            if (ps == null) {
14665                Log.w(TAG, "Package doesn't exist: " + packageName);
14666                return false;
14667            }
14668            if (systemUserApp) {
14669                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14670            } else {
14671                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14672            }
14673            mSettings.writeLPr();
14674        }
14675        return true;
14676    }
14677
14678    /*
14679     * This method handles package deletion in general
14680     */
14681    private boolean deletePackageLI(String packageName, UserHandle user,
14682            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14683            PackageRemovedInfo outInfo, boolean writeSettings,
14684            PackageParser.Package replacingPackage) {
14685        if (packageName == null) {
14686            Slog.w(TAG, "Attempt to delete null packageName.");
14687            return false;
14688        }
14689
14690        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14691
14692        PackageSetting ps;
14693
14694        synchronized (mPackages) {
14695            ps = mSettings.mPackages.get(packageName);
14696            if (ps == null) {
14697                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14698                return false;
14699            }
14700
14701            if (ps.pkg.parentPackage != null && (!isSystemApp(ps)
14702                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14703                if (DEBUG_REMOVE) {
14704                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14705                            + ((user == null) ? UserHandle.USER_ALL : user));
14706                }
14707                final int removedUserId = (user != null) ? user.getIdentifier()
14708                        : UserHandle.USER_ALL;
14709                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14710                    return false;
14711                }
14712                markPackageUninstalledForUserLPw(ps, user);
14713                scheduleWritePackageRestrictionsLocked(user);
14714                return true;
14715            }
14716        }
14717
14718        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14719                && user.getIdentifier() != UserHandle.USER_ALL)) {
14720            // The caller is asking that the package only be deleted for a single
14721            // user.  To do this, we just mark its uninstalled state and delete
14722            // its data. If this is a system app, we only allow this to happen if
14723            // they have set the special DELETE_SYSTEM_APP which requests different
14724            // semantics than normal for uninstalling system apps.
14725            markPackageUninstalledForUserLPw(ps, user);
14726
14727            if (!isSystemApp(ps)) {
14728                // Do not uninstall the APK if an app should be cached
14729                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14730                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14731                    // Other user still have this package installed, so all
14732                    // we need to do is clear this user's data and save that
14733                    // it is uninstalled.
14734                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14735                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14736                        return false;
14737                    }
14738                    scheduleWritePackageRestrictionsLocked(user);
14739                    return true;
14740                } else {
14741                    // We need to set it back to 'installed' so the uninstall
14742                    // broadcasts will be sent correctly.
14743                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14744                    ps.setInstalled(true, user.getIdentifier());
14745                }
14746            } else {
14747                // This is a system app, so we assume that the
14748                // other users still have this package installed, so all
14749                // we need to do is clear this user's data and save that
14750                // it is uninstalled.
14751                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14752                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14753                    return false;
14754                }
14755                scheduleWritePackageRestrictionsLocked(user);
14756                return true;
14757            }
14758        }
14759
14760        // If we are deleting a composite package for all users, keep track
14761        // of result for each child.
14762        if (ps.childPackageNames != null && outInfo != null) {
14763            synchronized (mPackages) {
14764                final int childCount = ps.childPackageNames.size();
14765                outInfo.removedChildPackages = new ArrayMap<>(childCount);
14766                for (int i = 0; i < childCount; i++) {
14767                    String childPackageName = ps.childPackageNames.get(i);
14768                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
14769                    childInfo.removedPackage = childPackageName;
14770                    outInfo.removedChildPackages.put(childPackageName, childInfo);
14771                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14772                    if (childPs != null) {
14773                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
14774                    }
14775                }
14776            }
14777        }
14778
14779        boolean ret = false;
14780        if (isSystemApp(ps)) {
14781            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14782            // When an updated system application is deleted we delete the existing resources
14783            // as well and fall back to existing code in system partition
14784            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
14785        } else {
14786            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14787            // Kill application pre-emptively especially for apps on sd.
14788            killApplication(packageName, ps.appId, "uninstall pkg");
14789            ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles,
14790                    outInfo, writeSettings, replacingPackage);
14791        }
14792
14793        // Take a note whether we deleted the package for all users
14794        if (outInfo != null) {
14795            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14796            if (outInfo.removedChildPackages != null) {
14797                synchronized (mPackages) {
14798                    final int childCount = outInfo.removedChildPackages.size();
14799                    for (int i = 0; i < childCount; i++) {
14800                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
14801                        if (childInfo != null) {
14802                            childInfo.removedForAllUsers = mPackages.get(
14803                                    childInfo.removedPackage) == null;
14804                        }
14805                    }
14806                }
14807            }
14808            // If we uninstalled an update to a system app there may be some
14809            // child packages that appeared as they are declared in the system
14810            // app but were not declared in the update.
14811            if (isSystemApp(ps)) {
14812                synchronized (mPackages) {
14813                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
14814                    final int childCount = (updatedPs.childPackageNames != null)
14815                            ? updatedPs.childPackageNames.size() : 0;
14816                    for (int i = 0; i < childCount; i++) {
14817                        String childPackageName = updatedPs.childPackageNames.get(i);
14818                        if (outInfo.removedChildPackages == null
14819                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
14820                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14821                            if (childPs == null) {
14822                                continue;
14823                            }
14824                            PackageInstalledInfo installRes = new PackageInstalledInfo();
14825                            installRes.name = childPackageName;
14826                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
14827                            installRes.pkg = mPackages.get(childPackageName);
14828                            installRes.uid = childPs.pkg.applicationInfo.uid;
14829                            if (outInfo.appearedChildPackages == null) {
14830                                outInfo.appearedChildPackages = new ArrayMap<>();
14831                            }
14832                            outInfo.appearedChildPackages.put(childPackageName, installRes);
14833                        }
14834                    }
14835                }
14836            }
14837        }
14838
14839        return ret;
14840    }
14841
14842    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14843        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14844                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14845        for (int nextUserId : userIds) {
14846            if (DEBUG_REMOVE) {
14847                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14848            }
14849            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14850                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14851                    false /*hidden*/, false /*suspended*/, null, null, null,
14852                    false /*blockUninstall*/,
14853                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14854        }
14855    }
14856
14857    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
14858            PackageRemovedInfo outInfo) {
14859        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14860                : new int[] {userId};
14861        for (int nextUserId : userIds) {
14862            if (DEBUG_REMOVE) {
14863                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
14864                        + nextUserId);
14865            }
14866            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
14867            try {
14868                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
14869            } catch (InstallerException e) {
14870                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
14871                return false;
14872            }
14873            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
14874            schedulePackageCleaning(ps.name, nextUserId, false);
14875            synchronized (mPackages) {
14876                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
14877                    scheduleWritePackageRestrictionsLocked(nextUserId);
14878                }
14879                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
14880            }
14881        }
14882
14883        if (outInfo != null) {
14884            outInfo.removedPackage = ps.name;
14885            outInfo.removedAppId = ps.appId;
14886            outInfo.removedUsers = userIds;
14887        }
14888
14889        return true;
14890    }
14891
14892    private final class ClearStorageConnection implements ServiceConnection {
14893        IMediaContainerService mContainerService;
14894
14895        @Override
14896        public void onServiceConnected(ComponentName name, IBinder service) {
14897            synchronized (this) {
14898                mContainerService = IMediaContainerService.Stub.asInterface(service);
14899                notifyAll();
14900            }
14901        }
14902
14903        @Override
14904        public void onServiceDisconnected(ComponentName name) {
14905        }
14906    }
14907
14908    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14909        final boolean mounted;
14910        if (Environment.isExternalStorageEmulated()) {
14911            mounted = true;
14912        } else {
14913            final String status = Environment.getExternalStorageState();
14914
14915            mounted = status.equals(Environment.MEDIA_MOUNTED)
14916                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14917        }
14918
14919        if (!mounted) {
14920            return;
14921        }
14922
14923        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14924        int[] users;
14925        if (userId == UserHandle.USER_ALL) {
14926            users = sUserManager.getUserIds();
14927        } else {
14928            users = new int[] { userId };
14929        }
14930        final ClearStorageConnection conn = new ClearStorageConnection();
14931        if (mContext.bindServiceAsUser(
14932                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14933            try {
14934                for (int curUser : users) {
14935                    long timeout = SystemClock.uptimeMillis() + 5000;
14936                    synchronized (conn) {
14937                        long now = SystemClock.uptimeMillis();
14938                        while (conn.mContainerService == null && now < timeout) {
14939                            try {
14940                                conn.wait(timeout - now);
14941                            } catch (InterruptedException e) {
14942                            }
14943                        }
14944                    }
14945                    if (conn.mContainerService == null) {
14946                        return;
14947                    }
14948
14949                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14950                    clearDirectory(conn.mContainerService,
14951                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14952                    if (allData) {
14953                        clearDirectory(conn.mContainerService,
14954                                userEnv.buildExternalStorageAppDataDirs(packageName));
14955                        clearDirectory(conn.mContainerService,
14956                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14957                    }
14958                }
14959            } finally {
14960                mContext.unbindService(conn);
14961            }
14962        }
14963    }
14964
14965    @Override
14966    public void clearApplicationUserData(final String packageName,
14967            final IPackageDataObserver observer, final int userId) {
14968        mContext.enforceCallingOrSelfPermission(
14969                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14970        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14971        // Queue up an async operation since the package deletion may take a little while.
14972        mHandler.post(new Runnable() {
14973            public void run() {
14974                mHandler.removeCallbacks(this);
14975                final boolean succeeded;
14976                synchronized (mInstallLock) {
14977                    succeeded = clearApplicationUserDataLI(packageName, userId);
14978                }
14979                clearExternalStorageDataSync(packageName, userId, true);
14980                if (succeeded) {
14981                    // invoke DeviceStorageMonitor's update method to clear any notifications
14982                    DeviceStorageMonitorInternal
14983                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14984                    if (dsm != null) {
14985                        dsm.checkMemory();
14986                    }
14987                }
14988                if(observer != null) {
14989                    try {
14990                        observer.onRemoveCompleted(packageName, succeeded);
14991                    } catch (RemoteException e) {
14992                        Log.i(TAG, "Observer no longer exists.");
14993                    }
14994                } //end if observer
14995            } //end run
14996        });
14997    }
14998
14999    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15000        if (packageName == null) {
15001            Slog.w(TAG, "Attempt to delete null packageName.");
15002            return false;
15003        }
15004
15005        // Try finding details about the requested package
15006        PackageParser.Package pkg;
15007        synchronized (mPackages) {
15008            pkg = mPackages.get(packageName);
15009            if (pkg == null) {
15010                final PackageSetting ps = mSettings.mPackages.get(packageName);
15011                if (ps != null) {
15012                    pkg = ps.pkg;
15013                }
15014            }
15015
15016            if (pkg == null) {
15017                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15018                return false;
15019            }
15020
15021            PackageSetting ps = (PackageSetting) pkg.mExtras;
15022            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15023        }
15024
15025        // Always delete data directories for package, even if we found no other
15026        // record of app. This helps users recover from UID mismatches without
15027        // resorting to a full data wipe.
15028        // TODO: triage flags as part of 26466827
15029        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15030        try {
15031            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15032        } catch (InstallerException e) {
15033            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15034            return false;
15035        }
15036
15037        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15038        removeKeystoreDataIfNeeded(userId, appId);
15039
15040        // Create a native library symlink only if we have native libraries
15041        // and if the native libraries are 32 bit libraries. We do not provide
15042        // this symlink for 64 bit libraries.
15043        if (pkg.applicationInfo.primaryCpuAbi != null &&
15044                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15045            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15046            try {
15047                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15048                        nativeLibPath, userId);
15049            } catch (InstallerException e) {
15050                Slog.w(TAG, "Failed linking native library dir", e);
15051                return false;
15052            }
15053        }
15054
15055        return true;
15056    }
15057
15058    /**
15059     * Reverts user permission state changes (permissions and flags) in
15060     * all packages for a given user.
15061     *
15062     * @param userId The device user for which to do a reset.
15063     */
15064    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15065        final int packageCount = mPackages.size();
15066        for (int i = 0; i < packageCount; i++) {
15067            PackageParser.Package pkg = mPackages.valueAt(i);
15068            PackageSetting ps = (PackageSetting) pkg.mExtras;
15069            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15070        }
15071    }
15072
15073    /**
15074     * Reverts user permission state changes (permissions and flags).
15075     *
15076     * @param ps The package for which to reset.
15077     * @param userId The device user for which to do a reset.
15078     */
15079    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15080            final PackageSetting ps, final int userId) {
15081        if (ps.pkg == null) {
15082            return;
15083        }
15084
15085        // These are flags that can change base on user actions.
15086        final int userSettableMask = FLAG_PERMISSION_USER_SET
15087                | FLAG_PERMISSION_USER_FIXED
15088                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15089                | FLAG_PERMISSION_REVIEW_REQUIRED;
15090
15091        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15092                | FLAG_PERMISSION_POLICY_FIXED;
15093
15094        boolean writeInstallPermissions = false;
15095        boolean writeRuntimePermissions = false;
15096
15097        final int permissionCount = ps.pkg.requestedPermissions.size();
15098        for (int i = 0; i < permissionCount; i++) {
15099            String permission = ps.pkg.requestedPermissions.get(i);
15100
15101            BasePermission bp = mSettings.mPermissions.get(permission);
15102            if (bp == null) {
15103                continue;
15104            }
15105
15106            // If shared user we just reset the state to which only this app contributed.
15107            if (ps.sharedUser != null) {
15108                boolean used = false;
15109                final int packageCount = ps.sharedUser.packages.size();
15110                for (int j = 0; j < packageCount; j++) {
15111                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15112                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15113                            && pkg.pkg.requestedPermissions.contains(permission)) {
15114                        used = true;
15115                        break;
15116                    }
15117                }
15118                if (used) {
15119                    continue;
15120                }
15121            }
15122
15123            PermissionsState permissionsState = ps.getPermissionsState();
15124
15125            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15126
15127            // Always clear the user settable flags.
15128            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15129                    bp.name) != null;
15130            // If permission review is enabled and this is a legacy app, mark the
15131            // permission as requiring a review as this is the initial state.
15132            int flags = 0;
15133            if (Build.PERMISSIONS_REVIEW_REQUIRED
15134                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15135                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15136            }
15137            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15138                if (hasInstallState) {
15139                    writeInstallPermissions = true;
15140                } else {
15141                    writeRuntimePermissions = true;
15142                }
15143            }
15144
15145            // Below is only runtime permission handling.
15146            if (!bp.isRuntime()) {
15147                continue;
15148            }
15149
15150            // Never clobber system or policy.
15151            if ((oldFlags & policyOrSystemFlags) != 0) {
15152                continue;
15153            }
15154
15155            // If this permission was granted by default, make sure it is.
15156            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15157                if (permissionsState.grantRuntimePermission(bp, userId)
15158                        != PERMISSION_OPERATION_FAILURE) {
15159                    writeRuntimePermissions = true;
15160                }
15161            // If permission review is enabled the permissions for a legacy apps
15162            // are represented as constantly granted runtime ones, so don't revoke.
15163            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15164                // Otherwise, reset the permission.
15165                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15166                switch (revokeResult) {
15167                    case PERMISSION_OPERATION_SUCCESS: {
15168                        writeRuntimePermissions = true;
15169                    } break;
15170
15171                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15172                        writeRuntimePermissions = true;
15173                        final int appId = ps.appId;
15174                        mHandler.post(new Runnable() {
15175                            @Override
15176                            public void run() {
15177                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15178                            }
15179                        });
15180                    } break;
15181                }
15182            }
15183        }
15184
15185        // Synchronously write as we are taking permissions away.
15186        if (writeRuntimePermissions) {
15187            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15188        }
15189
15190        // Synchronously write as we are taking permissions away.
15191        if (writeInstallPermissions) {
15192            mSettings.writeLPr();
15193        }
15194    }
15195
15196    /**
15197     * Remove entries from the keystore daemon. Will only remove it if the
15198     * {@code appId} is valid.
15199     */
15200    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15201        if (appId < 0) {
15202            return;
15203        }
15204
15205        final KeyStore keyStore = KeyStore.getInstance();
15206        if (keyStore != null) {
15207            if (userId == UserHandle.USER_ALL) {
15208                for (final int individual : sUserManager.getUserIds()) {
15209                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15210                }
15211            } else {
15212                keyStore.clearUid(UserHandle.getUid(userId, appId));
15213            }
15214        } else {
15215            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15216        }
15217    }
15218
15219    @Override
15220    public void deleteApplicationCacheFiles(final String packageName,
15221            final IPackageDataObserver observer) {
15222        mContext.enforceCallingOrSelfPermission(
15223                android.Manifest.permission.DELETE_CACHE_FILES, null);
15224        // Queue up an async operation since the package deletion may take a little while.
15225        final int userId = UserHandle.getCallingUserId();
15226        mHandler.post(new Runnable() {
15227            public void run() {
15228                mHandler.removeCallbacks(this);
15229                final boolean succeded;
15230                synchronized (mInstallLock) {
15231                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15232                }
15233                clearExternalStorageDataSync(packageName, userId, false);
15234                if (observer != null) {
15235                    try {
15236                        observer.onRemoveCompleted(packageName, succeded);
15237                    } catch (RemoteException e) {
15238                        Log.i(TAG, "Observer no longer exists.");
15239                    }
15240                } //end if observer
15241            } //end run
15242        });
15243    }
15244
15245    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15246        if (packageName == null) {
15247            Slog.w(TAG, "Attempt to delete null packageName.");
15248            return false;
15249        }
15250        PackageParser.Package p;
15251        synchronized (mPackages) {
15252            p = mPackages.get(packageName);
15253        }
15254        if (p == null) {
15255            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15256            return false;
15257        }
15258        final ApplicationInfo applicationInfo = p.applicationInfo;
15259        if (applicationInfo == null) {
15260            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15261            return false;
15262        }
15263        // TODO: triage flags as part of 26466827
15264        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15265        try {
15266            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15267                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15268        } catch (InstallerException e) {
15269            Slog.w(TAG, "Couldn't remove cache files for package "
15270                    + packageName + " u" + userId, e);
15271            return false;
15272        }
15273        return true;
15274    }
15275
15276    @Override
15277    public void getPackageSizeInfo(final String packageName, int userHandle,
15278            final IPackageStatsObserver observer) {
15279        mContext.enforceCallingOrSelfPermission(
15280                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15281        if (packageName == null) {
15282            throw new IllegalArgumentException("Attempt to get size of null packageName");
15283        }
15284
15285        PackageStats stats = new PackageStats(packageName, userHandle);
15286
15287        /*
15288         * Queue up an async operation since the package measurement may take a
15289         * little while.
15290         */
15291        Message msg = mHandler.obtainMessage(INIT_COPY);
15292        msg.obj = new MeasureParams(stats, observer);
15293        mHandler.sendMessage(msg);
15294    }
15295
15296    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15297            PackageStats pStats) {
15298        if (packageName == null) {
15299            Slog.w(TAG, "Attempt to get size of null packageName.");
15300            return false;
15301        }
15302        PackageParser.Package p;
15303        boolean dataOnly = false;
15304        String libDirRoot = null;
15305        String asecPath = null;
15306        PackageSetting ps = null;
15307        synchronized (mPackages) {
15308            p = mPackages.get(packageName);
15309            ps = mSettings.mPackages.get(packageName);
15310            if(p == null) {
15311                dataOnly = true;
15312                if((ps == null) || (ps.pkg == null)) {
15313                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15314                    return false;
15315                }
15316                p = ps.pkg;
15317            }
15318            if (ps != null) {
15319                libDirRoot = ps.legacyNativeLibraryPathString;
15320            }
15321            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15322                final long token = Binder.clearCallingIdentity();
15323                try {
15324                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15325                    if (secureContainerId != null) {
15326                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15327                    }
15328                } finally {
15329                    Binder.restoreCallingIdentity(token);
15330                }
15331            }
15332        }
15333        String publicSrcDir = null;
15334        if(!dataOnly) {
15335            final ApplicationInfo applicationInfo = p.applicationInfo;
15336            if (applicationInfo == null) {
15337                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15338                return false;
15339            }
15340            if (p.isForwardLocked()) {
15341                publicSrcDir = applicationInfo.getBaseResourcePath();
15342            }
15343        }
15344        // TODO: extend to measure size of split APKs
15345        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15346        // not just the first level.
15347        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15348        // just the primary.
15349        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15350
15351        String apkPath;
15352        File packageDir = new File(p.codePath);
15353
15354        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15355            apkPath = packageDir.getAbsolutePath();
15356            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15357            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15358                libDirRoot = null;
15359            }
15360        } else {
15361            apkPath = p.baseCodePath;
15362        }
15363
15364        // TODO: triage flags as part of 26466827
15365        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15366        try {
15367            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15368                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15369        } catch (InstallerException e) {
15370            return false;
15371        }
15372
15373        // Fix-up for forward-locked applications in ASEC containers.
15374        if (!isExternal(p)) {
15375            pStats.codeSize += pStats.externalCodeSize;
15376            pStats.externalCodeSize = 0L;
15377        }
15378
15379        return true;
15380    }
15381
15382
15383    @Override
15384    public void addPackageToPreferred(String packageName) {
15385        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15386    }
15387
15388    @Override
15389    public void removePackageFromPreferred(String packageName) {
15390        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15391    }
15392
15393    @Override
15394    public List<PackageInfo> getPreferredPackages(int flags) {
15395        return new ArrayList<PackageInfo>();
15396    }
15397
15398    private int getUidTargetSdkVersionLockedLPr(int uid) {
15399        Object obj = mSettings.getUserIdLPr(uid);
15400        if (obj instanceof SharedUserSetting) {
15401            final SharedUserSetting sus = (SharedUserSetting) obj;
15402            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15403            final Iterator<PackageSetting> it = sus.packages.iterator();
15404            while (it.hasNext()) {
15405                final PackageSetting ps = it.next();
15406                if (ps.pkg != null) {
15407                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15408                    if (v < vers) vers = v;
15409                }
15410            }
15411            return vers;
15412        } else if (obj instanceof PackageSetting) {
15413            final PackageSetting ps = (PackageSetting) obj;
15414            if (ps.pkg != null) {
15415                return ps.pkg.applicationInfo.targetSdkVersion;
15416            }
15417        }
15418        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15419    }
15420
15421    @Override
15422    public void addPreferredActivity(IntentFilter filter, int match,
15423            ComponentName[] set, ComponentName activity, int userId) {
15424        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15425                "Adding preferred");
15426    }
15427
15428    private void addPreferredActivityInternal(IntentFilter filter, int match,
15429            ComponentName[] set, ComponentName activity, boolean always, int userId,
15430            String opname) {
15431        // writer
15432        int callingUid = Binder.getCallingUid();
15433        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
15434        if (filter.countActions() == 0) {
15435            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15436            return;
15437        }
15438        synchronized (mPackages) {
15439            if (mContext.checkCallingOrSelfPermission(
15440                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15441                    != PackageManager.PERMISSION_GRANTED) {
15442                if (getUidTargetSdkVersionLockedLPr(callingUid)
15443                        < Build.VERSION_CODES.FROYO) {
15444                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15445                            + callingUid);
15446                    return;
15447                }
15448                mContext.enforceCallingOrSelfPermission(
15449                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15450            }
15451
15452            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15453            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15454                    + userId + ":");
15455            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15456            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15457            scheduleWritePackageRestrictionsLocked(userId);
15458        }
15459    }
15460
15461    @Override
15462    public void replacePreferredActivity(IntentFilter filter, int match,
15463            ComponentName[] set, ComponentName activity, int userId) {
15464        if (filter.countActions() != 1) {
15465            throw new IllegalArgumentException(
15466                    "replacePreferredActivity expects filter to have only 1 action.");
15467        }
15468        if (filter.countDataAuthorities() != 0
15469                || filter.countDataPaths() != 0
15470                || filter.countDataSchemes() > 1
15471                || filter.countDataTypes() != 0) {
15472            throw new IllegalArgumentException(
15473                    "replacePreferredActivity expects filter to have no data authorities, " +
15474                    "paths, or types; and at most one scheme.");
15475        }
15476
15477        final int callingUid = Binder.getCallingUid();
15478        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
15479        synchronized (mPackages) {
15480            if (mContext.checkCallingOrSelfPermission(
15481                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15482                    != PackageManager.PERMISSION_GRANTED) {
15483                if (getUidTargetSdkVersionLockedLPr(callingUid)
15484                        < Build.VERSION_CODES.FROYO) {
15485                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15486                            + Binder.getCallingUid());
15487                    return;
15488                }
15489                mContext.enforceCallingOrSelfPermission(
15490                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15491            }
15492
15493            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15494            if (pir != null) {
15495                // Get all of the existing entries that exactly match this filter.
15496                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15497                if (existing != null && existing.size() == 1) {
15498                    PreferredActivity cur = existing.get(0);
15499                    if (DEBUG_PREFERRED) {
15500                        Slog.i(TAG, "Checking replace of preferred:");
15501                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15502                        if (!cur.mPref.mAlways) {
15503                            Slog.i(TAG, "  -- CUR; not mAlways!");
15504                        } else {
15505                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15506                            Slog.i(TAG, "  -- CUR: mSet="
15507                                    + Arrays.toString(cur.mPref.mSetComponents));
15508                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15509                            Slog.i(TAG, "  -- NEW: mMatch="
15510                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15511                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15512                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15513                        }
15514                    }
15515                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15516                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15517                            && cur.mPref.sameSet(set)) {
15518                        // Setting the preferred activity to what it happens to be already
15519                        if (DEBUG_PREFERRED) {
15520                            Slog.i(TAG, "Replacing with same preferred activity "
15521                                    + cur.mPref.mShortComponent + " for user "
15522                                    + userId + ":");
15523                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15524                        }
15525                        return;
15526                    }
15527                }
15528
15529                if (existing != null) {
15530                    if (DEBUG_PREFERRED) {
15531                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15532                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15533                    }
15534                    for (int i = 0; i < existing.size(); i++) {
15535                        PreferredActivity pa = existing.get(i);
15536                        if (DEBUG_PREFERRED) {
15537                            Slog.i(TAG, "Removing existing preferred activity "
15538                                    + pa.mPref.mComponent + ":");
15539                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15540                        }
15541                        pir.removeFilter(pa);
15542                    }
15543                }
15544            }
15545            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15546                    "Replacing preferred");
15547        }
15548    }
15549
15550    @Override
15551    public void clearPackagePreferredActivities(String packageName) {
15552        final int uid = Binder.getCallingUid();
15553        // writer
15554        synchronized (mPackages) {
15555            PackageParser.Package pkg = mPackages.get(packageName);
15556            if (pkg == null || pkg.applicationInfo.uid != uid) {
15557                if (mContext.checkCallingOrSelfPermission(
15558                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15559                        != PackageManager.PERMISSION_GRANTED) {
15560                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15561                            < Build.VERSION_CODES.FROYO) {
15562                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15563                                + Binder.getCallingUid());
15564                        return;
15565                    }
15566                    mContext.enforceCallingOrSelfPermission(
15567                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15568                }
15569            }
15570
15571            int user = UserHandle.getCallingUserId();
15572            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15573                scheduleWritePackageRestrictionsLocked(user);
15574            }
15575        }
15576    }
15577
15578    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15579    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15580        ArrayList<PreferredActivity> removed = null;
15581        boolean changed = false;
15582        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15583            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15584            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15585            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15586                continue;
15587            }
15588            Iterator<PreferredActivity> it = pir.filterIterator();
15589            while (it.hasNext()) {
15590                PreferredActivity pa = it.next();
15591                // Mark entry for removal only if it matches the package name
15592                // and the entry is of type "always".
15593                if (packageName == null ||
15594                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15595                                && pa.mPref.mAlways)) {
15596                    if (removed == null) {
15597                        removed = new ArrayList<PreferredActivity>();
15598                    }
15599                    removed.add(pa);
15600                }
15601            }
15602            if (removed != null) {
15603                for (int j=0; j<removed.size(); j++) {
15604                    PreferredActivity pa = removed.get(j);
15605                    pir.removeFilter(pa);
15606                }
15607                changed = true;
15608            }
15609        }
15610        return changed;
15611    }
15612
15613    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15614    private void clearIntentFilterVerificationsLPw(int userId) {
15615        final int packageCount = mPackages.size();
15616        for (int i = 0; i < packageCount; i++) {
15617            PackageParser.Package pkg = mPackages.valueAt(i);
15618            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15619        }
15620    }
15621
15622    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15623    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15624        if (userId == UserHandle.USER_ALL) {
15625            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15626                    sUserManager.getUserIds())) {
15627                for (int oneUserId : sUserManager.getUserIds()) {
15628                    scheduleWritePackageRestrictionsLocked(oneUserId);
15629                }
15630            }
15631        } else {
15632            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15633                scheduleWritePackageRestrictionsLocked(userId);
15634            }
15635        }
15636    }
15637
15638    void clearDefaultBrowserIfNeeded(String packageName) {
15639        for (int oneUserId : sUserManager.getUserIds()) {
15640            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15641            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15642            if (packageName.equals(defaultBrowserPackageName)) {
15643                setDefaultBrowserPackageName(null, oneUserId);
15644            }
15645        }
15646    }
15647
15648    @Override
15649    public void resetApplicationPreferences(int userId) {
15650        mContext.enforceCallingOrSelfPermission(
15651                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15652        // writer
15653        synchronized (mPackages) {
15654            final long identity = Binder.clearCallingIdentity();
15655            try {
15656                clearPackagePreferredActivitiesLPw(null, userId);
15657                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15658                // TODO: We have to reset the default SMS and Phone. This requires
15659                // significant refactoring to keep all default apps in the package
15660                // manager (cleaner but more work) or have the services provide
15661                // callbacks to the package manager to request a default app reset.
15662                applyFactoryDefaultBrowserLPw(userId);
15663                clearIntentFilterVerificationsLPw(userId);
15664                primeDomainVerificationsLPw(userId);
15665                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15666                scheduleWritePackageRestrictionsLocked(userId);
15667            } finally {
15668                Binder.restoreCallingIdentity(identity);
15669            }
15670        }
15671    }
15672
15673    @Override
15674    public int getPreferredActivities(List<IntentFilter> outFilters,
15675            List<ComponentName> outActivities, String packageName) {
15676
15677        int num = 0;
15678        final int userId = UserHandle.getCallingUserId();
15679        // reader
15680        synchronized (mPackages) {
15681            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15682            if (pir != null) {
15683                final Iterator<PreferredActivity> it = pir.filterIterator();
15684                while (it.hasNext()) {
15685                    final PreferredActivity pa = it.next();
15686                    if (packageName == null
15687                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15688                                    && pa.mPref.mAlways)) {
15689                        if (outFilters != null) {
15690                            outFilters.add(new IntentFilter(pa));
15691                        }
15692                        if (outActivities != null) {
15693                            outActivities.add(pa.mPref.mComponent);
15694                        }
15695                    }
15696                }
15697            }
15698        }
15699
15700        return num;
15701    }
15702
15703    @Override
15704    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15705            int userId) {
15706        int callingUid = Binder.getCallingUid();
15707        if (callingUid != Process.SYSTEM_UID) {
15708            throw new SecurityException(
15709                    "addPersistentPreferredActivity can only be run by the system");
15710        }
15711        if (filter.countActions() == 0) {
15712            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15713            return;
15714        }
15715        synchronized (mPackages) {
15716            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15717                    ":");
15718            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15719            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15720                    new PersistentPreferredActivity(filter, activity));
15721            scheduleWritePackageRestrictionsLocked(userId);
15722        }
15723    }
15724
15725    @Override
15726    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15727        int callingUid = Binder.getCallingUid();
15728        if (callingUid != Process.SYSTEM_UID) {
15729            throw new SecurityException(
15730                    "clearPackagePersistentPreferredActivities can only be run by the system");
15731        }
15732        ArrayList<PersistentPreferredActivity> removed = null;
15733        boolean changed = false;
15734        synchronized (mPackages) {
15735            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15736                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15737                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15738                        .valueAt(i);
15739                if (userId != thisUserId) {
15740                    continue;
15741                }
15742                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15743                while (it.hasNext()) {
15744                    PersistentPreferredActivity ppa = it.next();
15745                    // Mark entry for removal only if it matches the package name.
15746                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15747                        if (removed == null) {
15748                            removed = new ArrayList<PersistentPreferredActivity>();
15749                        }
15750                        removed.add(ppa);
15751                    }
15752                }
15753                if (removed != null) {
15754                    for (int j=0; j<removed.size(); j++) {
15755                        PersistentPreferredActivity ppa = removed.get(j);
15756                        ppir.removeFilter(ppa);
15757                    }
15758                    changed = true;
15759                }
15760            }
15761
15762            if (changed) {
15763                scheduleWritePackageRestrictionsLocked(userId);
15764            }
15765        }
15766    }
15767
15768    /**
15769     * Common machinery for picking apart a restored XML blob and passing
15770     * it to a caller-supplied functor to be applied to the running system.
15771     */
15772    private void restoreFromXml(XmlPullParser parser, int userId,
15773            String expectedStartTag, BlobXmlRestorer functor)
15774            throws IOException, XmlPullParserException {
15775        int type;
15776        while ((type = parser.next()) != XmlPullParser.START_TAG
15777                && type != XmlPullParser.END_DOCUMENT) {
15778        }
15779        if (type != XmlPullParser.START_TAG) {
15780            // oops didn't find a start tag?!
15781            if (DEBUG_BACKUP) {
15782                Slog.e(TAG, "Didn't find start tag during restore");
15783            }
15784            return;
15785        }
15786Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15787        // this is supposed to be TAG_PREFERRED_BACKUP
15788        if (!expectedStartTag.equals(parser.getName())) {
15789            if (DEBUG_BACKUP) {
15790                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15791            }
15792            return;
15793        }
15794
15795        // skip interfering stuff, then we're aligned with the backing implementation
15796        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15797Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15798        functor.apply(parser, userId);
15799    }
15800
15801    private interface BlobXmlRestorer {
15802        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15803    }
15804
15805    /**
15806     * Non-Binder method, support for the backup/restore mechanism: write the
15807     * full set of preferred activities in its canonical XML format.  Returns the
15808     * XML output as a byte array, or null if there is none.
15809     */
15810    @Override
15811    public byte[] getPreferredActivityBackup(int userId) {
15812        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15813            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15814        }
15815
15816        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15817        try {
15818            final XmlSerializer serializer = new FastXmlSerializer();
15819            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15820            serializer.startDocument(null, true);
15821            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15822
15823            synchronized (mPackages) {
15824                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15825            }
15826
15827            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15828            serializer.endDocument();
15829            serializer.flush();
15830        } catch (Exception e) {
15831            if (DEBUG_BACKUP) {
15832                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15833            }
15834            return null;
15835        }
15836
15837        return dataStream.toByteArray();
15838    }
15839
15840    @Override
15841    public void restorePreferredActivities(byte[] backup, int userId) {
15842        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15843            throw new SecurityException("Only the system may call restorePreferredActivities()");
15844        }
15845
15846        try {
15847            final XmlPullParser parser = Xml.newPullParser();
15848            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15849            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15850                    new BlobXmlRestorer() {
15851                        @Override
15852                        public void apply(XmlPullParser parser, int userId)
15853                                throws XmlPullParserException, IOException {
15854                            synchronized (mPackages) {
15855                                mSettings.readPreferredActivitiesLPw(parser, userId);
15856                            }
15857                        }
15858                    } );
15859        } catch (Exception e) {
15860            if (DEBUG_BACKUP) {
15861                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15862            }
15863        }
15864    }
15865
15866    /**
15867     * Non-Binder method, support for the backup/restore mechanism: write the
15868     * default browser (etc) settings in its canonical XML format.  Returns the default
15869     * browser XML representation as a byte array, or null if there is none.
15870     */
15871    @Override
15872    public byte[] getDefaultAppsBackup(int userId) {
15873        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15874            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15875        }
15876
15877        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15878        try {
15879            final XmlSerializer serializer = new FastXmlSerializer();
15880            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15881            serializer.startDocument(null, true);
15882            serializer.startTag(null, TAG_DEFAULT_APPS);
15883
15884            synchronized (mPackages) {
15885                mSettings.writeDefaultAppsLPr(serializer, userId);
15886            }
15887
15888            serializer.endTag(null, TAG_DEFAULT_APPS);
15889            serializer.endDocument();
15890            serializer.flush();
15891        } catch (Exception e) {
15892            if (DEBUG_BACKUP) {
15893                Slog.e(TAG, "Unable to write default apps for backup", e);
15894            }
15895            return null;
15896        }
15897
15898        return dataStream.toByteArray();
15899    }
15900
15901    @Override
15902    public void restoreDefaultApps(byte[] backup, int userId) {
15903        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15904            throw new SecurityException("Only the system may call restoreDefaultApps()");
15905        }
15906
15907        try {
15908            final XmlPullParser parser = Xml.newPullParser();
15909            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15910            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15911                    new BlobXmlRestorer() {
15912                        @Override
15913                        public void apply(XmlPullParser parser, int userId)
15914                                throws XmlPullParserException, IOException {
15915                            synchronized (mPackages) {
15916                                mSettings.readDefaultAppsLPw(parser, userId);
15917                            }
15918                        }
15919                    } );
15920        } catch (Exception e) {
15921            if (DEBUG_BACKUP) {
15922                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15923            }
15924        }
15925    }
15926
15927    @Override
15928    public byte[] getIntentFilterVerificationBackup(int userId) {
15929        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15930            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15931        }
15932
15933        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15934        try {
15935            final XmlSerializer serializer = new FastXmlSerializer();
15936            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15937            serializer.startDocument(null, true);
15938            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15939
15940            synchronized (mPackages) {
15941                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15942            }
15943
15944            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15945            serializer.endDocument();
15946            serializer.flush();
15947        } catch (Exception e) {
15948            if (DEBUG_BACKUP) {
15949                Slog.e(TAG, "Unable to write default apps for backup", e);
15950            }
15951            return null;
15952        }
15953
15954        return dataStream.toByteArray();
15955    }
15956
15957    @Override
15958    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15959        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15960            throw new SecurityException("Only the system may call restorePreferredActivities()");
15961        }
15962
15963        try {
15964            final XmlPullParser parser = Xml.newPullParser();
15965            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15966            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15967                    new BlobXmlRestorer() {
15968                        @Override
15969                        public void apply(XmlPullParser parser, int userId)
15970                                throws XmlPullParserException, IOException {
15971                            synchronized (mPackages) {
15972                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15973                                mSettings.writeLPr();
15974                            }
15975                        }
15976                    } );
15977        } catch (Exception e) {
15978            if (DEBUG_BACKUP) {
15979                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15980            }
15981        }
15982    }
15983
15984    @Override
15985    public byte[] getPermissionGrantBackup(int userId) {
15986        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15987            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15988        }
15989
15990        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15991        try {
15992            final XmlSerializer serializer = new FastXmlSerializer();
15993            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15994            serializer.startDocument(null, true);
15995            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15996
15997            synchronized (mPackages) {
15998                serializeRuntimePermissionGrantsLPr(serializer, userId);
15999            }
16000
16001            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16002            serializer.endDocument();
16003            serializer.flush();
16004        } catch (Exception e) {
16005            if (DEBUG_BACKUP) {
16006                Slog.e(TAG, "Unable to write default apps for backup", e);
16007            }
16008            return null;
16009        }
16010
16011        return dataStream.toByteArray();
16012    }
16013
16014    @Override
16015    public void restorePermissionGrants(byte[] backup, int userId) {
16016        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16017            throw new SecurityException("Only the system may call restorePermissionGrants()");
16018        }
16019
16020        try {
16021            final XmlPullParser parser = Xml.newPullParser();
16022            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16023            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16024                    new BlobXmlRestorer() {
16025                        @Override
16026                        public void apply(XmlPullParser parser, int userId)
16027                                throws XmlPullParserException, IOException {
16028                            synchronized (mPackages) {
16029                                processRestoredPermissionGrantsLPr(parser, userId);
16030                            }
16031                        }
16032                    } );
16033        } catch (Exception e) {
16034            if (DEBUG_BACKUP) {
16035                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16036            }
16037        }
16038    }
16039
16040    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16041            throws IOException {
16042        serializer.startTag(null, TAG_ALL_GRANTS);
16043
16044        final int N = mSettings.mPackages.size();
16045        for (int i = 0; i < N; i++) {
16046            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16047            boolean pkgGrantsKnown = false;
16048
16049            PermissionsState packagePerms = ps.getPermissionsState();
16050
16051            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16052                final int grantFlags = state.getFlags();
16053                // only look at grants that are not system/policy fixed
16054                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16055                    final boolean isGranted = state.isGranted();
16056                    // And only back up the user-twiddled state bits
16057                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16058                        final String packageName = mSettings.mPackages.keyAt(i);
16059                        if (!pkgGrantsKnown) {
16060                            serializer.startTag(null, TAG_GRANT);
16061                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16062                            pkgGrantsKnown = true;
16063                        }
16064
16065                        final boolean userSet =
16066                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16067                        final boolean userFixed =
16068                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16069                        final boolean revoke =
16070                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16071
16072                        serializer.startTag(null, TAG_PERMISSION);
16073                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16074                        if (isGranted) {
16075                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16076                        }
16077                        if (userSet) {
16078                            serializer.attribute(null, ATTR_USER_SET, "true");
16079                        }
16080                        if (userFixed) {
16081                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16082                        }
16083                        if (revoke) {
16084                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16085                        }
16086                        serializer.endTag(null, TAG_PERMISSION);
16087                    }
16088                }
16089            }
16090
16091            if (pkgGrantsKnown) {
16092                serializer.endTag(null, TAG_GRANT);
16093            }
16094        }
16095
16096        serializer.endTag(null, TAG_ALL_GRANTS);
16097    }
16098
16099    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16100            throws XmlPullParserException, IOException {
16101        String pkgName = null;
16102        int outerDepth = parser.getDepth();
16103        int type;
16104        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16105                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16106            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16107                continue;
16108            }
16109
16110            final String tagName = parser.getName();
16111            if (tagName.equals(TAG_GRANT)) {
16112                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16113                if (DEBUG_BACKUP) {
16114                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16115                }
16116            } else if (tagName.equals(TAG_PERMISSION)) {
16117
16118                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16119                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16120
16121                int newFlagSet = 0;
16122                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16123                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16124                }
16125                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16126                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16127                }
16128                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16129                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16130                }
16131                if (DEBUG_BACKUP) {
16132                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16133                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16134                }
16135                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16136                if (ps != null) {
16137                    // Already installed so we apply the grant immediately
16138                    if (DEBUG_BACKUP) {
16139                        Slog.v(TAG, "        + already installed; applying");
16140                    }
16141                    PermissionsState perms = ps.getPermissionsState();
16142                    BasePermission bp = mSettings.mPermissions.get(permName);
16143                    if (bp != null) {
16144                        if (isGranted) {
16145                            perms.grantRuntimePermission(bp, userId);
16146                        }
16147                        if (newFlagSet != 0) {
16148                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16149                        }
16150                    }
16151                } else {
16152                    // Need to wait for post-restore install to apply the grant
16153                    if (DEBUG_BACKUP) {
16154                        Slog.v(TAG, "        - not yet installed; saving for later");
16155                    }
16156                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16157                            isGranted, newFlagSet, userId);
16158                }
16159            } else {
16160                PackageManagerService.reportSettingsProblem(Log.WARN,
16161                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16162                XmlUtils.skipCurrentTag(parser);
16163            }
16164        }
16165
16166        scheduleWriteSettingsLocked();
16167        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16168    }
16169
16170    @Override
16171    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16172            int sourceUserId, int targetUserId, int flags) {
16173        mContext.enforceCallingOrSelfPermission(
16174                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16175        int callingUid = Binder.getCallingUid();
16176        enforceOwnerRights(ownerPackage, callingUid);
16177        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16178        if (intentFilter.countActions() == 0) {
16179            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16180            return;
16181        }
16182        synchronized (mPackages) {
16183            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16184                    ownerPackage, targetUserId, flags);
16185            CrossProfileIntentResolver resolver =
16186                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16187            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16188            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16189            if (existing != null) {
16190                int size = existing.size();
16191                for (int i = 0; i < size; i++) {
16192                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16193                        return;
16194                    }
16195                }
16196            }
16197            resolver.addFilter(newFilter);
16198            scheduleWritePackageRestrictionsLocked(sourceUserId);
16199        }
16200    }
16201
16202    @Override
16203    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16204        mContext.enforceCallingOrSelfPermission(
16205                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16206        int callingUid = Binder.getCallingUid();
16207        enforceOwnerRights(ownerPackage, callingUid);
16208        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16209        synchronized (mPackages) {
16210            CrossProfileIntentResolver resolver =
16211                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16212            ArraySet<CrossProfileIntentFilter> set =
16213                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16214            for (CrossProfileIntentFilter filter : set) {
16215                if (filter.getOwnerPackage().equals(ownerPackage)) {
16216                    resolver.removeFilter(filter);
16217                }
16218            }
16219            scheduleWritePackageRestrictionsLocked(sourceUserId);
16220        }
16221    }
16222
16223    // Enforcing that callingUid is owning pkg on userId
16224    private void enforceOwnerRights(String pkg, int callingUid) {
16225        // The system owns everything.
16226        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16227            return;
16228        }
16229        int callingUserId = UserHandle.getUserId(callingUid);
16230        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16231        if (pi == null) {
16232            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16233                    + callingUserId);
16234        }
16235        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16236            throw new SecurityException("Calling uid " + callingUid
16237                    + " does not own package " + pkg);
16238        }
16239    }
16240
16241    @Override
16242    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16243        Intent intent = new Intent(Intent.ACTION_MAIN);
16244        intent.addCategory(Intent.CATEGORY_HOME);
16245
16246        final int callingUserId = UserHandle.getCallingUserId();
16247        List<ResolveInfo> list = queryIntentActivities(intent, null,
16248                PackageManager.GET_META_DATA, callingUserId);
16249        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16250                true, false, false, callingUserId);
16251
16252        allHomeCandidates.clear();
16253        if (list != null) {
16254            for (ResolveInfo ri : list) {
16255                allHomeCandidates.add(ri);
16256            }
16257        }
16258        return (preferred == null || preferred.activityInfo == null)
16259                ? null
16260                : new ComponentName(preferred.activityInfo.packageName,
16261                        preferred.activityInfo.name);
16262    }
16263
16264    @Override
16265    public void setApplicationEnabledSetting(String appPackageName,
16266            int newState, int flags, int userId, String callingPackage) {
16267        if (!sUserManager.exists(userId)) return;
16268        if (callingPackage == null) {
16269            callingPackage = Integer.toString(Binder.getCallingUid());
16270        }
16271        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16272    }
16273
16274    @Override
16275    public void setComponentEnabledSetting(ComponentName componentName,
16276            int newState, int flags, int userId) {
16277        if (!sUserManager.exists(userId)) return;
16278        setEnabledSetting(componentName.getPackageName(),
16279                componentName.getClassName(), newState, flags, userId, null);
16280    }
16281
16282    private void setEnabledSetting(final String packageName, String className, int newState,
16283            final int flags, int userId, String callingPackage) {
16284        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16285              || newState == COMPONENT_ENABLED_STATE_ENABLED
16286              || newState == COMPONENT_ENABLED_STATE_DISABLED
16287              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16288              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16289            throw new IllegalArgumentException("Invalid new component state: "
16290                    + newState);
16291        }
16292        PackageSetting pkgSetting;
16293        final int uid = Binder.getCallingUid();
16294        final int permission = mContext.checkCallingOrSelfPermission(
16295                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16296        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
16297        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16298        boolean sendNow = false;
16299        boolean isApp = (className == null);
16300        String componentName = isApp ? packageName : className;
16301        int packageUid = -1;
16302        ArrayList<String> components;
16303
16304        // writer
16305        synchronized (mPackages) {
16306            pkgSetting = mSettings.mPackages.get(packageName);
16307            if (pkgSetting == null) {
16308                if (className == null) {
16309                    throw new IllegalArgumentException("Unknown package: " + packageName);
16310                }
16311                throw new IllegalArgumentException(
16312                        "Unknown component: " + packageName + "/" + className);
16313            }
16314            // Allow root and verify that userId is not being specified by a different user
16315            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16316                throw new SecurityException(
16317                        "Permission Denial: attempt to change component state from pid="
16318                        + Binder.getCallingPid()
16319                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16320            }
16321            if (className == null) {
16322                // We're dealing with an application/package level state change
16323                if (pkgSetting.getEnabled(userId) == newState) {
16324                    // Nothing to do
16325                    return;
16326                }
16327                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16328                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16329                    // Don't care about who enables an app.
16330                    callingPackage = null;
16331                }
16332                pkgSetting.setEnabled(newState, userId, callingPackage);
16333                // pkgSetting.pkg.mSetEnabled = newState;
16334            } else {
16335                // We're dealing with a component level state change
16336                // First, verify that this is a valid class name.
16337                PackageParser.Package pkg = pkgSetting.pkg;
16338                if (pkg == null || !pkg.hasComponentClassName(className)) {
16339                    if (pkg != null &&
16340                            pkg.applicationInfo.targetSdkVersion >=
16341                                    Build.VERSION_CODES.JELLY_BEAN) {
16342                        throw new IllegalArgumentException("Component class " + className
16343                                + " does not exist in " + packageName);
16344                    } else {
16345                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16346                                + className + " does not exist in " + packageName);
16347                    }
16348                }
16349                switch (newState) {
16350                case COMPONENT_ENABLED_STATE_ENABLED:
16351                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16352                        return;
16353                    }
16354                    break;
16355                case COMPONENT_ENABLED_STATE_DISABLED:
16356                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16357                        return;
16358                    }
16359                    break;
16360                case COMPONENT_ENABLED_STATE_DEFAULT:
16361                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16362                        return;
16363                    }
16364                    break;
16365                default:
16366                    Slog.e(TAG, "Invalid new component state: " + newState);
16367                    return;
16368                }
16369            }
16370            scheduleWritePackageRestrictionsLocked(userId);
16371            components = mPendingBroadcasts.get(userId, packageName);
16372            final boolean newPackage = components == null;
16373            if (newPackage) {
16374                components = new ArrayList<String>();
16375            }
16376            if (!components.contains(componentName)) {
16377                components.add(componentName);
16378            }
16379            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16380                sendNow = true;
16381                // Purge entry from pending broadcast list if another one exists already
16382                // since we are sending one right away.
16383                mPendingBroadcasts.remove(userId, packageName);
16384            } else {
16385                if (newPackage) {
16386                    mPendingBroadcasts.put(userId, packageName, components);
16387                }
16388                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16389                    // Schedule a message
16390                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16391                }
16392            }
16393        }
16394
16395        long callingId = Binder.clearCallingIdentity();
16396        try {
16397            if (sendNow) {
16398                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16399                sendPackageChangedBroadcast(packageName,
16400                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16401            }
16402        } finally {
16403            Binder.restoreCallingIdentity(callingId);
16404        }
16405    }
16406
16407    private void sendPackageChangedBroadcast(String packageName,
16408            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16409        if (DEBUG_INSTALL)
16410            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16411                    + componentNames);
16412        Bundle extras = new Bundle(4);
16413        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16414        String nameList[] = new String[componentNames.size()];
16415        componentNames.toArray(nameList);
16416        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16417        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16418        extras.putInt(Intent.EXTRA_UID, packageUid);
16419        // If this is not reporting a change of the overall package, then only send it
16420        // to registered receivers.  We don't want to launch a swath of apps for every
16421        // little component state change.
16422        final int flags = !componentNames.contains(packageName)
16423                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16424        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16425                new int[] {UserHandle.getUserId(packageUid)});
16426    }
16427
16428    @Override
16429    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16430        if (!sUserManager.exists(userId)) return;
16431        final int uid = Binder.getCallingUid();
16432        final int permission = mContext.checkCallingOrSelfPermission(
16433                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16434        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16435        enforceCrossUserPermission(uid, userId, true, true, "stop package");
16436        // writer
16437        synchronized (mPackages) {
16438            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16439                    allowedByPermission, uid, userId)) {
16440                scheduleWritePackageRestrictionsLocked(userId);
16441            }
16442        }
16443    }
16444
16445    @Override
16446    public String getInstallerPackageName(String packageName) {
16447        // reader
16448        synchronized (mPackages) {
16449            return mSettings.getInstallerPackageNameLPr(packageName);
16450        }
16451    }
16452
16453    @Override
16454    public int getApplicationEnabledSetting(String packageName, int userId) {
16455        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16456        int uid = Binder.getCallingUid();
16457        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
16458        // reader
16459        synchronized (mPackages) {
16460            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16461        }
16462    }
16463
16464    @Override
16465    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16466        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16467        int uid = Binder.getCallingUid();
16468        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
16469        // reader
16470        synchronized (mPackages) {
16471            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16472        }
16473    }
16474
16475    @Override
16476    public void enterSafeMode() {
16477        enforceSystemOrRoot("Only the system can request entering safe mode");
16478
16479        if (!mSystemReady) {
16480            mSafeMode = true;
16481        }
16482    }
16483
16484    @Override
16485    public void systemReady() {
16486        mSystemReady = true;
16487
16488        // Read the compatibilty setting when the system is ready.
16489        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16490                mContext.getContentResolver(),
16491                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16492        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16493        if (DEBUG_SETTINGS) {
16494            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16495        }
16496
16497        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16498
16499        synchronized (mPackages) {
16500            // Verify that all of the preferred activity components actually
16501            // exist.  It is possible for applications to be updated and at
16502            // that point remove a previously declared activity component that
16503            // had been set as a preferred activity.  We try to clean this up
16504            // the next time we encounter that preferred activity, but it is
16505            // possible for the user flow to never be able to return to that
16506            // situation so here we do a sanity check to make sure we haven't
16507            // left any junk around.
16508            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16509            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16510                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16511                removed.clear();
16512                for (PreferredActivity pa : pir.filterSet()) {
16513                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16514                        removed.add(pa);
16515                    }
16516                }
16517                if (removed.size() > 0) {
16518                    for (int r=0; r<removed.size(); r++) {
16519                        PreferredActivity pa = removed.get(r);
16520                        Slog.w(TAG, "Removing dangling preferred activity: "
16521                                + pa.mPref.mComponent);
16522                        pir.removeFilter(pa);
16523                    }
16524                    mSettings.writePackageRestrictionsLPr(
16525                            mSettings.mPreferredActivities.keyAt(i));
16526                }
16527            }
16528
16529            for (int userId : UserManagerService.getInstance().getUserIds()) {
16530                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16531                    grantPermissionsUserIds = ArrayUtils.appendInt(
16532                            grantPermissionsUserIds, userId);
16533                }
16534            }
16535        }
16536        sUserManager.systemReady();
16537
16538        // If we upgraded grant all default permissions before kicking off.
16539        for (int userId : grantPermissionsUserIds) {
16540            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16541        }
16542
16543        // Kick off any messages waiting for system ready
16544        if (mPostSystemReadyMessages != null) {
16545            for (Message msg : mPostSystemReadyMessages) {
16546                msg.sendToTarget();
16547            }
16548            mPostSystemReadyMessages = null;
16549        }
16550
16551        // Watch for external volumes that come and go over time
16552        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16553        storage.registerListener(mStorageListener);
16554
16555        mInstallerService.systemReady();
16556        mPackageDexOptimizer.systemReady();
16557
16558        MountServiceInternal mountServiceInternal = LocalServices.getService(
16559                MountServiceInternal.class);
16560        mountServiceInternal.addExternalStoragePolicy(
16561                new MountServiceInternal.ExternalStorageMountPolicy() {
16562            @Override
16563            public int getMountMode(int uid, String packageName) {
16564                if (Process.isIsolated(uid)) {
16565                    return Zygote.MOUNT_EXTERNAL_NONE;
16566                }
16567                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16568                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16569                }
16570                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16571                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16572                }
16573                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16574                    return Zygote.MOUNT_EXTERNAL_READ;
16575                }
16576                return Zygote.MOUNT_EXTERNAL_WRITE;
16577            }
16578
16579            @Override
16580            public boolean hasExternalStorage(int uid, String packageName) {
16581                return true;
16582            }
16583        });
16584    }
16585
16586    @Override
16587    public boolean isSafeMode() {
16588        return mSafeMode;
16589    }
16590
16591    @Override
16592    public boolean hasSystemUidErrors() {
16593        return mHasSystemUidErrors;
16594    }
16595
16596    static String arrayToString(int[] array) {
16597        StringBuffer buf = new StringBuffer(128);
16598        buf.append('[');
16599        if (array != null) {
16600            for (int i=0; i<array.length; i++) {
16601                if (i > 0) buf.append(", ");
16602                buf.append(array[i]);
16603            }
16604        }
16605        buf.append(']');
16606        return buf.toString();
16607    }
16608
16609    static class DumpState {
16610        public static final int DUMP_LIBS = 1 << 0;
16611        public static final int DUMP_FEATURES = 1 << 1;
16612        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16613        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16614        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16615        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16616        public static final int DUMP_PERMISSIONS = 1 << 6;
16617        public static final int DUMP_PACKAGES = 1 << 7;
16618        public static final int DUMP_SHARED_USERS = 1 << 8;
16619        public static final int DUMP_MESSAGES = 1 << 9;
16620        public static final int DUMP_PROVIDERS = 1 << 10;
16621        public static final int DUMP_VERIFIERS = 1 << 11;
16622        public static final int DUMP_PREFERRED = 1 << 12;
16623        public static final int DUMP_PREFERRED_XML = 1 << 13;
16624        public static final int DUMP_KEYSETS = 1 << 14;
16625        public static final int DUMP_VERSION = 1 << 15;
16626        public static final int DUMP_INSTALLS = 1 << 16;
16627        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16628        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16629
16630        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16631
16632        private int mTypes;
16633
16634        private int mOptions;
16635
16636        private boolean mTitlePrinted;
16637
16638        private SharedUserSetting mSharedUser;
16639
16640        public boolean isDumping(int type) {
16641            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16642                return true;
16643            }
16644
16645            return (mTypes & type) != 0;
16646        }
16647
16648        public void setDump(int type) {
16649            mTypes |= type;
16650        }
16651
16652        public boolean isOptionEnabled(int option) {
16653            return (mOptions & option) != 0;
16654        }
16655
16656        public void setOptionEnabled(int option) {
16657            mOptions |= option;
16658        }
16659
16660        public boolean onTitlePrinted() {
16661            final boolean printed = mTitlePrinted;
16662            mTitlePrinted = true;
16663            return printed;
16664        }
16665
16666        public boolean getTitlePrinted() {
16667            return mTitlePrinted;
16668        }
16669
16670        public void setTitlePrinted(boolean enabled) {
16671            mTitlePrinted = enabled;
16672        }
16673
16674        public SharedUserSetting getSharedUser() {
16675            return mSharedUser;
16676        }
16677
16678        public void setSharedUser(SharedUserSetting user) {
16679            mSharedUser = user;
16680        }
16681    }
16682
16683    @Override
16684    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16685            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16686        (new PackageManagerShellCommand(this)).exec(
16687                this, in, out, err, args, resultReceiver);
16688    }
16689
16690    @Override
16691    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16692        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16693                != PackageManager.PERMISSION_GRANTED) {
16694            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16695                    + Binder.getCallingPid()
16696                    + ", uid=" + Binder.getCallingUid()
16697                    + " without permission "
16698                    + android.Manifest.permission.DUMP);
16699            return;
16700        }
16701
16702        DumpState dumpState = new DumpState();
16703        boolean fullPreferred = false;
16704        boolean checkin = false;
16705
16706        String packageName = null;
16707        ArraySet<String> permissionNames = null;
16708
16709        int opti = 0;
16710        while (opti < args.length) {
16711            String opt = args[opti];
16712            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16713                break;
16714            }
16715            opti++;
16716
16717            if ("-a".equals(opt)) {
16718                // Right now we only know how to print all.
16719            } else if ("-h".equals(opt)) {
16720                pw.println("Package manager dump options:");
16721                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16722                pw.println("    --checkin: dump for a checkin");
16723                pw.println("    -f: print details of intent filters");
16724                pw.println("    -h: print this help");
16725                pw.println("  cmd may be one of:");
16726                pw.println("    l[ibraries]: list known shared libraries");
16727                pw.println("    f[eatures]: list device features");
16728                pw.println("    k[eysets]: print known keysets");
16729                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16730                pw.println("    perm[issions]: dump permissions");
16731                pw.println("    permission [name ...]: dump declaration and use of given permission");
16732                pw.println("    pref[erred]: print preferred package settings");
16733                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16734                pw.println("    prov[iders]: dump content providers");
16735                pw.println("    p[ackages]: dump installed packages");
16736                pw.println("    s[hared-users]: dump shared user IDs");
16737                pw.println("    m[essages]: print collected runtime messages");
16738                pw.println("    v[erifiers]: print package verifier info");
16739                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16740                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16741                pw.println("    version: print database version info");
16742                pw.println("    write: write current settings now");
16743                pw.println("    installs: details about install sessions");
16744                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16745                pw.println("    <package.name>: info about given package");
16746                return;
16747            } else if ("--checkin".equals(opt)) {
16748                checkin = true;
16749            } else if ("-f".equals(opt)) {
16750                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16751            } else {
16752                pw.println("Unknown argument: " + opt + "; use -h for help");
16753            }
16754        }
16755
16756        // Is the caller requesting to dump a particular piece of data?
16757        if (opti < args.length) {
16758            String cmd = args[opti];
16759            opti++;
16760            // Is this a package name?
16761            if ("android".equals(cmd) || cmd.contains(".")) {
16762                packageName = cmd;
16763                // When dumping a single package, we always dump all of its
16764                // filter information since the amount of data will be reasonable.
16765                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16766            } else if ("check-permission".equals(cmd)) {
16767                if (opti >= args.length) {
16768                    pw.println("Error: check-permission missing permission argument");
16769                    return;
16770                }
16771                String perm = args[opti];
16772                opti++;
16773                if (opti >= args.length) {
16774                    pw.println("Error: check-permission missing package argument");
16775                    return;
16776                }
16777                String pkg = args[opti];
16778                opti++;
16779                int user = UserHandle.getUserId(Binder.getCallingUid());
16780                if (opti < args.length) {
16781                    try {
16782                        user = Integer.parseInt(args[opti]);
16783                    } catch (NumberFormatException e) {
16784                        pw.println("Error: check-permission user argument is not a number: "
16785                                + args[opti]);
16786                        return;
16787                    }
16788                }
16789                pw.println(checkPermission(perm, pkg, user));
16790                return;
16791            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16792                dumpState.setDump(DumpState.DUMP_LIBS);
16793            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16794                dumpState.setDump(DumpState.DUMP_FEATURES);
16795            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16796                if (opti >= args.length) {
16797                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16798                            | DumpState.DUMP_SERVICE_RESOLVERS
16799                            | DumpState.DUMP_RECEIVER_RESOLVERS
16800                            | DumpState.DUMP_CONTENT_RESOLVERS);
16801                } else {
16802                    while (opti < args.length) {
16803                        String name = args[opti];
16804                        if ("a".equals(name) || "activity".equals(name)) {
16805                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16806                        } else if ("s".equals(name) || "service".equals(name)) {
16807                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16808                        } else if ("r".equals(name) || "receiver".equals(name)) {
16809                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16810                        } else if ("c".equals(name) || "content".equals(name)) {
16811                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16812                        } else {
16813                            pw.println("Error: unknown resolver table type: " + name);
16814                            return;
16815                        }
16816                        opti++;
16817                    }
16818                }
16819            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16820                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16821            } else if ("permission".equals(cmd)) {
16822                if (opti >= args.length) {
16823                    pw.println("Error: permission requires permission name");
16824                    return;
16825                }
16826                permissionNames = new ArraySet<>();
16827                while (opti < args.length) {
16828                    permissionNames.add(args[opti]);
16829                    opti++;
16830                }
16831                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16832                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16833            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16834                dumpState.setDump(DumpState.DUMP_PREFERRED);
16835            } else if ("preferred-xml".equals(cmd)) {
16836                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16837                if (opti < args.length && "--full".equals(args[opti])) {
16838                    fullPreferred = true;
16839                    opti++;
16840                }
16841            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16842                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16843            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16844                dumpState.setDump(DumpState.DUMP_PACKAGES);
16845            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16846                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16847            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16848                dumpState.setDump(DumpState.DUMP_PROVIDERS);
16849            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
16850                dumpState.setDump(DumpState.DUMP_MESSAGES);
16851            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
16852                dumpState.setDump(DumpState.DUMP_VERIFIERS);
16853            } else if ("i".equals(cmd) || "ifv".equals(cmd)
16854                    || "intent-filter-verifiers".equals(cmd)) {
16855                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
16856            } else if ("version".equals(cmd)) {
16857                dumpState.setDump(DumpState.DUMP_VERSION);
16858            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
16859                dumpState.setDump(DumpState.DUMP_KEYSETS);
16860            } else if ("installs".equals(cmd)) {
16861                dumpState.setDump(DumpState.DUMP_INSTALLS);
16862            } else if ("write".equals(cmd)) {
16863                synchronized (mPackages) {
16864                    mSettings.writeLPr();
16865                    pw.println("Settings written.");
16866                    return;
16867                }
16868            }
16869        }
16870
16871        if (checkin) {
16872            pw.println("vers,1");
16873        }
16874
16875        // reader
16876        synchronized (mPackages) {
16877            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16878                if (!checkin) {
16879                    if (dumpState.onTitlePrinted())
16880                        pw.println();
16881                    pw.println("Database versions:");
16882                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16883                }
16884            }
16885
16886            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16887                if (!checkin) {
16888                    if (dumpState.onTitlePrinted())
16889                        pw.println();
16890                    pw.println("Verifiers:");
16891                    pw.print("  Required: ");
16892                    pw.print(mRequiredVerifierPackage);
16893                    pw.print(" (uid=");
16894                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16895                            UserHandle.USER_SYSTEM));
16896                    pw.println(")");
16897                } else if (mRequiredVerifierPackage != null) {
16898                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16899                    pw.print(",");
16900                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16901                            UserHandle.USER_SYSTEM));
16902                }
16903            }
16904
16905            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16906                    packageName == null) {
16907                if (mIntentFilterVerifierComponent != null) {
16908                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16909                    if (!checkin) {
16910                        if (dumpState.onTitlePrinted())
16911                            pw.println();
16912                        pw.println("Intent Filter Verifier:");
16913                        pw.print("  Using: ");
16914                        pw.print(verifierPackageName);
16915                        pw.print(" (uid=");
16916                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16917                                UserHandle.USER_SYSTEM));
16918                        pw.println(")");
16919                    } else if (verifierPackageName != null) {
16920                        pw.print("ifv,"); pw.print(verifierPackageName);
16921                        pw.print(",");
16922                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16923                                UserHandle.USER_SYSTEM));
16924                    }
16925                } else {
16926                    pw.println();
16927                    pw.println("No Intent Filter Verifier available!");
16928                }
16929            }
16930
16931            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16932                boolean printedHeader = false;
16933                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16934                while (it.hasNext()) {
16935                    String name = it.next();
16936                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16937                    if (!checkin) {
16938                        if (!printedHeader) {
16939                            if (dumpState.onTitlePrinted())
16940                                pw.println();
16941                            pw.println("Libraries:");
16942                            printedHeader = true;
16943                        }
16944                        pw.print("  ");
16945                    } else {
16946                        pw.print("lib,");
16947                    }
16948                    pw.print(name);
16949                    if (!checkin) {
16950                        pw.print(" -> ");
16951                    }
16952                    if (ent.path != null) {
16953                        if (!checkin) {
16954                            pw.print("(jar) ");
16955                            pw.print(ent.path);
16956                        } else {
16957                            pw.print(",jar,");
16958                            pw.print(ent.path);
16959                        }
16960                    } else {
16961                        if (!checkin) {
16962                            pw.print("(apk) ");
16963                            pw.print(ent.apk);
16964                        } else {
16965                            pw.print(",apk,");
16966                            pw.print(ent.apk);
16967                        }
16968                    }
16969                    pw.println();
16970                }
16971            }
16972
16973            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16974                if (dumpState.onTitlePrinted())
16975                    pw.println();
16976                if (!checkin) {
16977                    pw.println("Features:");
16978                }
16979
16980                for (FeatureInfo feat : mAvailableFeatures.values()) {
16981                    if (checkin) {
16982                        pw.print("feat,");
16983                        pw.print(feat.name);
16984                        pw.print(",");
16985                        pw.println(feat.version);
16986                    } else {
16987                        pw.print("  ");
16988                        pw.print(feat.name);
16989                        if (feat.version > 0) {
16990                            pw.print(" version=");
16991                            pw.print(feat.version);
16992                        }
16993                        pw.println();
16994                    }
16995                }
16996            }
16997
16998            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16999                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17000                        : "Activity Resolver Table:", "  ", packageName,
17001                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17002                    dumpState.setTitlePrinted(true);
17003                }
17004            }
17005            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17006                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17007                        : "Receiver Resolver Table:", "  ", packageName,
17008                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17009                    dumpState.setTitlePrinted(true);
17010                }
17011            }
17012            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17013                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17014                        : "Service Resolver Table:", "  ", packageName,
17015                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17016                    dumpState.setTitlePrinted(true);
17017                }
17018            }
17019            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17020                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17021                        : "Provider Resolver Table:", "  ", packageName,
17022                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17023                    dumpState.setTitlePrinted(true);
17024                }
17025            }
17026
17027            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17028                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17029                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17030                    int user = mSettings.mPreferredActivities.keyAt(i);
17031                    if (pir.dump(pw,
17032                            dumpState.getTitlePrinted()
17033                                ? "\nPreferred Activities User " + user + ":"
17034                                : "Preferred Activities User " + user + ":", "  ",
17035                            packageName, true, false)) {
17036                        dumpState.setTitlePrinted(true);
17037                    }
17038                }
17039            }
17040
17041            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17042                pw.flush();
17043                FileOutputStream fout = new FileOutputStream(fd);
17044                BufferedOutputStream str = new BufferedOutputStream(fout);
17045                XmlSerializer serializer = new FastXmlSerializer();
17046                try {
17047                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17048                    serializer.startDocument(null, true);
17049                    serializer.setFeature(
17050                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17051                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17052                    serializer.endDocument();
17053                    serializer.flush();
17054                } catch (IllegalArgumentException e) {
17055                    pw.println("Failed writing: " + e);
17056                } catch (IllegalStateException e) {
17057                    pw.println("Failed writing: " + e);
17058                } catch (IOException e) {
17059                    pw.println("Failed writing: " + e);
17060                }
17061            }
17062
17063            if (!checkin
17064                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17065                    && packageName == null) {
17066                pw.println();
17067                int count = mSettings.mPackages.size();
17068                if (count == 0) {
17069                    pw.println("No applications!");
17070                    pw.println();
17071                } else {
17072                    final String prefix = "  ";
17073                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17074                    if (allPackageSettings.size() == 0) {
17075                        pw.println("No domain preferred apps!");
17076                        pw.println();
17077                    } else {
17078                        pw.println("App verification status:");
17079                        pw.println();
17080                        count = 0;
17081                        for (PackageSetting ps : allPackageSettings) {
17082                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17083                            if (ivi == null || ivi.getPackageName() == null) continue;
17084                            pw.println(prefix + "Package: " + ivi.getPackageName());
17085                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17086                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17087                            pw.println();
17088                            count++;
17089                        }
17090                        if (count == 0) {
17091                            pw.println(prefix + "No app verification established.");
17092                            pw.println();
17093                        }
17094                        for (int userId : sUserManager.getUserIds()) {
17095                            pw.println("App linkages for user " + userId + ":");
17096                            pw.println();
17097                            count = 0;
17098                            for (PackageSetting ps : allPackageSettings) {
17099                                final long status = ps.getDomainVerificationStatusForUser(userId);
17100                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17101                                    continue;
17102                                }
17103                                pw.println(prefix + "Package: " + ps.name);
17104                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17105                                String statusStr = IntentFilterVerificationInfo.
17106                                        getStatusStringFromValue(status);
17107                                pw.println(prefix + "Status:  " + statusStr);
17108                                pw.println();
17109                                count++;
17110                            }
17111                            if (count == 0) {
17112                                pw.println(prefix + "No configured app linkages.");
17113                                pw.println();
17114                            }
17115                        }
17116                    }
17117                }
17118            }
17119
17120            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17121                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17122                if (packageName == null && permissionNames == null) {
17123                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17124                        if (iperm == 0) {
17125                            if (dumpState.onTitlePrinted())
17126                                pw.println();
17127                            pw.println("AppOp Permissions:");
17128                        }
17129                        pw.print("  AppOp Permission ");
17130                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17131                        pw.println(":");
17132                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17133                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17134                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17135                        }
17136                    }
17137                }
17138            }
17139
17140            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17141                boolean printedSomething = false;
17142                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17143                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17144                        continue;
17145                    }
17146                    if (!printedSomething) {
17147                        if (dumpState.onTitlePrinted())
17148                            pw.println();
17149                        pw.println("Registered ContentProviders:");
17150                        printedSomething = true;
17151                    }
17152                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17153                    pw.print("    "); pw.println(p.toString());
17154                }
17155                printedSomething = false;
17156                for (Map.Entry<String, PackageParser.Provider> entry :
17157                        mProvidersByAuthority.entrySet()) {
17158                    PackageParser.Provider p = entry.getValue();
17159                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17160                        continue;
17161                    }
17162                    if (!printedSomething) {
17163                        if (dumpState.onTitlePrinted())
17164                            pw.println();
17165                        pw.println("ContentProvider Authorities:");
17166                        printedSomething = true;
17167                    }
17168                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17169                    pw.print("    "); pw.println(p.toString());
17170                    if (p.info != null && p.info.applicationInfo != null) {
17171                        final String appInfo = p.info.applicationInfo.toString();
17172                        pw.print("      applicationInfo="); pw.println(appInfo);
17173                    }
17174                }
17175            }
17176
17177            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17178                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17179            }
17180
17181            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17182                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17183            }
17184
17185            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17186                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17187            }
17188
17189            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17190                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17191            }
17192
17193            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17194                // XXX should handle packageName != null by dumping only install data that
17195                // the given package is involved with.
17196                if (dumpState.onTitlePrinted()) pw.println();
17197                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17198            }
17199
17200            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17201                if (dumpState.onTitlePrinted()) pw.println();
17202                mSettings.dumpReadMessagesLPr(pw, dumpState);
17203
17204                pw.println();
17205                pw.println("Package warning messages:");
17206                BufferedReader in = null;
17207                String line = null;
17208                try {
17209                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17210                    while ((line = in.readLine()) != null) {
17211                        if (line.contains("ignored: updated version")) continue;
17212                        pw.println(line);
17213                    }
17214                } catch (IOException ignored) {
17215                } finally {
17216                    IoUtils.closeQuietly(in);
17217                }
17218            }
17219
17220            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17221                BufferedReader in = null;
17222                String line = null;
17223                try {
17224                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17225                    while ((line = in.readLine()) != null) {
17226                        if (line.contains("ignored: updated version")) continue;
17227                        pw.print("msg,");
17228                        pw.println(line);
17229                    }
17230                } catch (IOException ignored) {
17231                } finally {
17232                    IoUtils.closeQuietly(in);
17233                }
17234            }
17235        }
17236    }
17237
17238    private String dumpDomainString(String packageName) {
17239        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
17240        List<IntentFilter> filters = getAllIntentFilters(packageName);
17241
17242        ArraySet<String> result = new ArraySet<>();
17243        if (iviList.size() > 0) {
17244            for (IntentFilterVerificationInfo ivi : iviList) {
17245                for (String host : ivi.getDomains()) {
17246                    result.add(host);
17247                }
17248            }
17249        }
17250        if (filters != null && filters.size() > 0) {
17251            for (IntentFilter filter : filters) {
17252                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17253                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17254                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17255                    result.addAll(filter.getHostsList());
17256                }
17257            }
17258        }
17259
17260        StringBuilder sb = new StringBuilder(result.size() * 16);
17261        for (String domain : result) {
17262            if (sb.length() > 0) sb.append(" ");
17263            sb.append(domain);
17264        }
17265        return sb.toString();
17266    }
17267
17268    // ------- apps on sdcard specific code -------
17269    static final boolean DEBUG_SD_INSTALL = false;
17270
17271    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17272
17273    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17274
17275    private boolean mMediaMounted = false;
17276
17277    static String getEncryptKey() {
17278        try {
17279            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17280                    SD_ENCRYPTION_KEYSTORE_NAME);
17281            if (sdEncKey == null) {
17282                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17283                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17284                if (sdEncKey == null) {
17285                    Slog.e(TAG, "Failed to create encryption keys");
17286                    return null;
17287                }
17288            }
17289            return sdEncKey;
17290        } catch (NoSuchAlgorithmException nsae) {
17291            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17292            return null;
17293        } catch (IOException ioe) {
17294            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17295            return null;
17296        }
17297    }
17298
17299    /*
17300     * Update media status on PackageManager.
17301     */
17302    @Override
17303    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17304        int callingUid = Binder.getCallingUid();
17305        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17306            throw new SecurityException("Media status can only be updated by the system");
17307        }
17308        // reader; this apparently protects mMediaMounted, but should probably
17309        // be a different lock in that case.
17310        synchronized (mPackages) {
17311            Log.i(TAG, "Updating external media status from "
17312                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17313                    + (mediaStatus ? "mounted" : "unmounted"));
17314            if (DEBUG_SD_INSTALL)
17315                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17316                        + ", mMediaMounted=" + mMediaMounted);
17317            if (mediaStatus == mMediaMounted) {
17318                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17319                        : 0, -1);
17320                mHandler.sendMessage(msg);
17321                return;
17322            }
17323            mMediaMounted = mediaStatus;
17324        }
17325        // Queue up an async operation since the package installation may take a
17326        // little while.
17327        mHandler.post(new Runnable() {
17328            public void run() {
17329                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17330            }
17331        });
17332    }
17333
17334    /**
17335     * Called by MountService when the initial ASECs to scan are available.
17336     * Should block until all the ASEC containers are finished being scanned.
17337     */
17338    public void scanAvailableAsecs() {
17339        updateExternalMediaStatusInner(true, false, false);
17340    }
17341
17342    /*
17343     * Collect information of applications on external media, map them against
17344     * existing containers and update information based on current mount status.
17345     * Please note that we always have to report status if reportStatus has been
17346     * set to true especially when unloading packages.
17347     */
17348    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17349            boolean externalStorage) {
17350        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17351        int[] uidArr = EmptyArray.INT;
17352
17353        final String[] list = PackageHelper.getSecureContainerList();
17354        if (ArrayUtils.isEmpty(list)) {
17355            Log.i(TAG, "No secure containers found");
17356        } else {
17357            // Process list of secure containers and categorize them
17358            // as active or stale based on their package internal state.
17359
17360            // reader
17361            synchronized (mPackages) {
17362                for (String cid : list) {
17363                    // Leave stages untouched for now; installer service owns them
17364                    if (PackageInstallerService.isStageName(cid)) continue;
17365
17366                    if (DEBUG_SD_INSTALL)
17367                        Log.i(TAG, "Processing container " + cid);
17368                    String pkgName = getAsecPackageName(cid);
17369                    if (pkgName == null) {
17370                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17371                        continue;
17372                    }
17373                    if (DEBUG_SD_INSTALL)
17374                        Log.i(TAG, "Looking for pkg : " + pkgName);
17375
17376                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17377                    if (ps == null) {
17378                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17379                        continue;
17380                    }
17381
17382                    /*
17383                     * Skip packages that are not external if we're unmounting
17384                     * external storage.
17385                     */
17386                    if (externalStorage && !isMounted && !isExternal(ps)) {
17387                        continue;
17388                    }
17389
17390                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17391                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17392                    // The package status is changed only if the code path
17393                    // matches between settings and the container id.
17394                    if (ps.codePathString != null
17395                            && ps.codePathString.startsWith(args.getCodePath())) {
17396                        if (DEBUG_SD_INSTALL) {
17397                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17398                                    + " at code path: " + ps.codePathString);
17399                        }
17400
17401                        // We do have a valid package installed on sdcard
17402                        processCids.put(args, ps.codePathString);
17403                        final int uid = ps.appId;
17404                        if (uid != -1) {
17405                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17406                        }
17407                    } else {
17408                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17409                                + ps.codePathString);
17410                    }
17411                }
17412            }
17413
17414            Arrays.sort(uidArr);
17415        }
17416
17417        // Process packages with valid entries.
17418        if (isMounted) {
17419            if (DEBUG_SD_INSTALL)
17420                Log.i(TAG, "Loading packages");
17421            loadMediaPackages(processCids, uidArr, externalStorage);
17422            startCleaningPackages();
17423            mInstallerService.onSecureContainersAvailable();
17424        } else {
17425            if (DEBUG_SD_INSTALL)
17426                Log.i(TAG, "Unloading packages");
17427            unloadMediaPackages(processCids, uidArr, reportStatus);
17428        }
17429    }
17430
17431    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17432            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17433        final int size = infos.size();
17434        final String[] packageNames = new String[size];
17435        final int[] packageUids = new int[size];
17436        for (int i = 0; i < size; i++) {
17437            final ApplicationInfo info = infos.get(i);
17438            packageNames[i] = info.packageName;
17439            packageUids[i] = info.uid;
17440        }
17441        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17442                finishedReceiver);
17443    }
17444
17445    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17446            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17447        sendResourcesChangedBroadcast(mediaStatus, replacing,
17448                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17449    }
17450
17451    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17452            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17453        int size = pkgList.length;
17454        if (size > 0) {
17455            // Send broadcasts here
17456            Bundle extras = new Bundle();
17457            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17458            if (uidArr != null) {
17459                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17460            }
17461            if (replacing) {
17462                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17463            }
17464            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17465                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17466            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17467        }
17468    }
17469
17470   /*
17471     * Look at potentially valid container ids from processCids If package
17472     * information doesn't match the one on record or package scanning fails,
17473     * the cid is added to list of removeCids. We currently don't delete stale
17474     * containers.
17475     */
17476    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17477            boolean externalStorage) {
17478        ArrayList<String> pkgList = new ArrayList<String>();
17479        Set<AsecInstallArgs> keys = processCids.keySet();
17480
17481        for (AsecInstallArgs args : keys) {
17482            String codePath = processCids.get(args);
17483            if (DEBUG_SD_INSTALL)
17484                Log.i(TAG, "Loading container : " + args.cid);
17485            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17486            try {
17487                // Make sure there are no container errors first.
17488                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17489                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17490                            + " when installing from sdcard");
17491                    continue;
17492                }
17493                // Check code path here.
17494                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17495                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17496                            + " does not match one in settings " + codePath);
17497                    continue;
17498                }
17499                // Parse package
17500                int parseFlags = mDefParseFlags;
17501                if (args.isExternalAsec()) {
17502                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17503                }
17504                if (args.isFwdLocked()) {
17505                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17506                }
17507
17508                synchronized (mInstallLock) {
17509                    PackageParser.Package pkg = null;
17510                    try {
17511                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17512                    } catch (PackageManagerException e) {
17513                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17514                    }
17515                    // Scan the package
17516                    if (pkg != null) {
17517                        /*
17518                         * TODO why is the lock being held? doPostInstall is
17519                         * called in other places without the lock. This needs
17520                         * to be straightened out.
17521                         */
17522                        // writer
17523                        synchronized (mPackages) {
17524                            retCode = PackageManager.INSTALL_SUCCEEDED;
17525                            pkgList.add(pkg.packageName);
17526                            // Post process args
17527                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17528                                    pkg.applicationInfo.uid);
17529                        }
17530                    } else {
17531                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17532                    }
17533                }
17534
17535            } finally {
17536                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17537                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17538                }
17539            }
17540        }
17541        // writer
17542        synchronized (mPackages) {
17543            // If the platform SDK has changed since the last time we booted,
17544            // we need to re-grant app permission to catch any new ones that
17545            // appear. This is really a hack, and means that apps can in some
17546            // cases get permissions that the user didn't initially explicitly
17547            // allow... it would be nice to have some better way to handle
17548            // this situation.
17549            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17550                    : mSettings.getInternalVersion();
17551            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17552                    : StorageManager.UUID_PRIVATE_INTERNAL;
17553
17554            int updateFlags = UPDATE_PERMISSIONS_ALL;
17555            if (ver.sdkVersion != mSdkVersion) {
17556                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17557                        + mSdkVersion + "; regranting permissions for external");
17558                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17559            }
17560            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17561
17562            // Yay, everything is now upgraded
17563            ver.forceCurrent();
17564
17565            // can downgrade to reader
17566            // Persist settings
17567            mSettings.writeLPr();
17568        }
17569        // Send a broadcast to let everyone know we are done processing
17570        if (pkgList.size() > 0) {
17571            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17572        }
17573    }
17574
17575   /*
17576     * Utility method to unload a list of specified containers
17577     */
17578    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17579        // Just unmount all valid containers.
17580        for (AsecInstallArgs arg : cidArgs) {
17581            synchronized (mInstallLock) {
17582                arg.doPostDeleteLI(false);
17583           }
17584       }
17585   }
17586
17587    /*
17588     * Unload packages mounted on external media. This involves deleting package
17589     * data from internal structures, sending broadcasts about disabled packages,
17590     * gc'ing to free up references, unmounting all secure containers
17591     * corresponding to packages on external media, and posting a
17592     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17593     * that we always have to post this message if status has been requested no
17594     * matter what.
17595     */
17596    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17597            final boolean reportStatus) {
17598        if (DEBUG_SD_INSTALL)
17599            Log.i(TAG, "unloading media packages");
17600        ArrayList<String> pkgList = new ArrayList<String>();
17601        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17602        final Set<AsecInstallArgs> keys = processCids.keySet();
17603        for (AsecInstallArgs args : keys) {
17604            String pkgName = args.getPackageName();
17605            if (DEBUG_SD_INSTALL)
17606                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17607            // Delete package internally
17608            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17609            synchronized (mInstallLock) {
17610                boolean res = deletePackageLI(pkgName, null, false, null,
17611                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17612                if (res) {
17613                    pkgList.add(pkgName);
17614                } else {
17615                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17616                    failedList.add(args);
17617                }
17618            }
17619        }
17620
17621        // reader
17622        synchronized (mPackages) {
17623            // We didn't update the settings after removing each package;
17624            // write them now for all packages.
17625            mSettings.writeLPr();
17626        }
17627
17628        // We have to absolutely send UPDATED_MEDIA_STATUS only
17629        // after confirming that all the receivers processed the ordered
17630        // broadcast when packages get disabled, force a gc to clean things up.
17631        // and unload all the containers.
17632        if (pkgList.size() > 0) {
17633            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17634                    new IIntentReceiver.Stub() {
17635                public void performReceive(Intent intent, int resultCode, String data,
17636                        Bundle extras, boolean ordered, boolean sticky,
17637                        int sendingUser) throws RemoteException {
17638                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17639                            reportStatus ? 1 : 0, 1, keys);
17640                    mHandler.sendMessage(msg);
17641                }
17642            });
17643        } else {
17644            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17645                    keys);
17646            mHandler.sendMessage(msg);
17647        }
17648    }
17649
17650    private void loadPrivatePackages(final VolumeInfo vol) {
17651        mHandler.post(new Runnable() {
17652            @Override
17653            public void run() {
17654                loadPrivatePackagesInner(vol);
17655            }
17656        });
17657    }
17658
17659    private void loadPrivatePackagesInner(VolumeInfo vol) {
17660        final String volumeUuid = vol.fsUuid;
17661        if (TextUtils.isEmpty(volumeUuid)) {
17662            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17663            return;
17664        }
17665
17666        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17667        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17668
17669        final VersionInfo ver;
17670        final List<PackageSetting> packages;
17671        synchronized (mPackages) {
17672            ver = mSettings.findOrCreateVersion(volumeUuid);
17673            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17674        }
17675
17676        // TODO: introduce a new concept similar to "frozen" to prevent these
17677        // apps from being launched until after data has been fully reconciled
17678        for (PackageSetting ps : packages) {
17679            synchronized (mInstallLock) {
17680                final PackageParser.Package pkg;
17681                try {
17682                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17683                    loaded.add(pkg.applicationInfo);
17684
17685                } catch (PackageManagerException e) {
17686                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17687                }
17688
17689                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17690                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17691                }
17692            }
17693        }
17694
17695        // Reconcile app data for all started/unlocked users
17696        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17697        final UserManager um = mContext.getSystemService(UserManager.class);
17698        for (UserInfo user : um.getUsers()) {
17699            final int flags;
17700            if (um.isUserUnlocked(user.id)) {
17701                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17702            } else if (um.isUserRunning(user.id)) {
17703                flags = StorageManager.FLAG_STORAGE_DE;
17704            } else {
17705                continue;
17706            }
17707
17708            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17709            reconcileAppsData(volumeUuid, user.id, flags);
17710        }
17711
17712        synchronized (mPackages) {
17713            int updateFlags = UPDATE_PERMISSIONS_ALL;
17714            if (ver.sdkVersion != mSdkVersion) {
17715                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17716                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17717                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17718            }
17719            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17720
17721            // Yay, everything is now upgraded
17722            ver.forceCurrent();
17723
17724            mSettings.writeLPr();
17725        }
17726
17727        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17728        sendResourcesChangedBroadcast(true, false, loaded, null);
17729    }
17730
17731    private void unloadPrivatePackages(final VolumeInfo vol) {
17732        mHandler.post(new Runnable() {
17733            @Override
17734            public void run() {
17735                unloadPrivatePackagesInner(vol);
17736            }
17737        });
17738    }
17739
17740    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17741        final String volumeUuid = vol.fsUuid;
17742        if (TextUtils.isEmpty(volumeUuid)) {
17743            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17744            return;
17745        }
17746
17747        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17748        synchronized (mInstallLock) {
17749        synchronized (mPackages) {
17750            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17751            for (PackageSetting ps : packages) {
17752                if (ps.pkg == null) continue;
17753
17754                final ApplicationInfo info = ps.pkg.applicationInfo;
17755                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17756                if (deletePackageLI(ps.name, null, false, null,
17757                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17758                    unloaded.add(info);
17759                } else {
17760                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17761                }
17762            }
17763
17764            mSettings.writeLPr();
17765        }
17766        }
17767
17768        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17769        sendResourcesChangedBroadcast(false, false, unloaded, null);
17770    }
17771
17772    /**
17773     * Examine all users present on given mounted volume, and destroy data
17774     * belonging to users that are no longer valid, or whose user ID has been
17775     * recycled.
17776     */
17777    private void reconcileUsers(String volumeUuid) {
17778        // TODO: also reconcile DE directories
17779        final File[] files = FileUtils
17780                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
17781        for (File file : files) {
17782            if (!file.isDirectory()) continue;
17783
17784            final int userId;
17785            final UserInfo info;
17786            try {
17787                userId = Integer.parseInt(file.getName());
17788                info = sUserManager.getUserInfo(userId);
17789            } catch (NumberFormatException e) {
17790                Slog.w(TAG, "Invalid user directory " + file);
17791                continue;
17792            }
17793
17794            boolean destroyUser = false;
17795            if (info == null) {
17796                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17797                        + " because no matching user was found");
17798                destroyUser = true;
17799            } else {
17800                try {
17801                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17802                } catch (IOException e) {
17803                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17804                            + " because we failed to enforce serial number: " + e);
17805                    destroyUser = true;
17806                }
17807            }
17808
17809            if (destroyUser) {
17810                synchronized (mInstallLock) {
17811                    try {
17812                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17813                    } catch (InstallerException e) {
17814                        Slog.w(TAG, "Failed to clean up user dirs", e);
17815                    }
17816                }
17817            }
17818        }
17819    }
17820
17821    private void assertPackageKnown(String volumeUuid, String packageName)
17822            throws PackageManagerException {
17823        synchronized (mPackages) {
17824            final PackageSetting ps = mSettings.mPackages.get(packageName);
17825            if (ps == null) {
17826                throw new PackageManagerException("Package " + packageName + " is unknown");
17827            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17828                throw new PackageManagerException(
17829                        "Package " + packageName + " found on unknown volume " + volumeUuid
17830                                + "; expected volume " + ps.volumeUuid);
17831            }
17832        }
17833    }
17834
17835    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17836            throws PackageManagerException {
17837        synchronized (mPackages) {
17838            final PackageSetting ps = mSettings.mPackages.get(packageName);
17839            if (ps == null) {
17840                throw new PackageManagerException("Package " + packageName + " is unknown");
17841            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17842                throw new PackageManagerException(
17843                        "Package " + packageName + " found on unknown volume " + volumeUuid
17844                                + "; expected volume " + ps.volumeUuid);
17845            } else if (!ps.getInstalled(userId)) {
17846                throw new PackageManagerException(
17847                        "Package " + packageName + " not installed for user " + userId);
17848            }
17849        }
17850    }
17851
17852    /**
17853     * Examine all apps present on given mounted volume, and destroy apps that
17854     * aren't expected, either due to uninstallation or reinstallation on
17855     * another volume.
17856     */
17857    private void reconcileApps(String volumeUuid) {
17858        final File[] files = FileUtils
17859                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
17860        for (File file : files) {
17861            final boolean isPackage = (isApkFile(file) || file.isDirectory())
17862                    && !PackageInstallerService.isStageName(file.getName());
17863            if (!isPackage) {
17864                // Ignore entries which are not packages
17865                continue;
17866            }
17867
17868            try {
17869                final PackageLite pkg = PackageParser.parsePackageLite(file,
17870                        PackageParser.PARSE_MUST_BE_APK);
17871                assertPackageKnown(volumeUuid, pkg.packageName);
17872
17873            } catch (PackageParserException | PackageManagerException e) {
17874                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17875                synchronized (mInstallLock) {
17876                    removeCodePathLI(file);
17877                }
17878            }
17879        }
17880    }
17881
17882    /**
17883     * Reconcile all app data for the given user.
17884     * <p>
17885     * Verifies that directories exist and that ownership and labeling is
17886     * correct for all installed apps on all mounted volumes.
17887     */
17888    void reconcileAppsData(int userId, int flags) {
17889        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17890        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17891            final String volumeUuid = vol.getFsUuid();
17892            reconcileAppsData(volumeUuid, userId, flags);
17893        }
17894    }
17895
17896    /**
17897     * Reconcile all app data on given mounted volume.
17898     * <p>
17899     * Destroys app data that isn't expected, either due to uninstallation or
17900     * reinstallation on another volume.
17901     * <p>
17902     * Verifies that directories exist and that ownership and labeling is
17903     * correct for all installed apps.
17904     */
17905    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
17906        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17907                + Integer.toHexString(flags));
17908
17909        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
17910        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
17911
17912        boolean restoreconNeeded = false;
17913
17914        // First look for stale data that doesn't belong, and check if things
17915        // have changed since we did our last restorecon
17916        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17917            if (!isUserKeyUnlocked(userId)) {
17918                throw new RuntimeException(
17919                        "Yikes, someone asked us to reconcile CE storage while " + userId
17920                                + " was still locked; this would have caused massive data loss!");
17921            }
17922
17923            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17924
17925            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17926            for (File file : files) {
17927                final String packageName = file.getName();
17928                try {
17929                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17930                } catch (PackageManagerException e) {
17931                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17932                    synchronized (mInstallLock) {
17933                        destroyAppDataLI(volumeUuid, packageName, userId,
17934                                StorageManager.FLAG_STORAGE_CE);
17935                    }
17936                }
17937            }
17938        }
17939        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17940            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17941
17942            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17943            for (File file : files) {
17944                final String packageName = file.getName();
17945                try {
17946                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17947                } catch (PackageManagerException e) {
17948                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17949                    synchronized (mInstallLock) {
17950                        destroyAppDataLI(volumeUuid, packageName, userId,
17951                                StorageManager.FLAG_STORAGE_DE);
17952                    }
17953                }
17954            }
17955        }
17956
17957        // Ensure that data directories are ready to roll for all packages
17958        // installed for this volume and user
17959        final List<PackageSetting> packages;
17960        synchronized (mPackages) {
17961            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17962        }
17963        int preparedCount = 0;
17964        for (PackageSetting ps : packages) {
17965            final String packageName = ps.name;
17966            if (ps.pkg == null) {
17967                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17968                // TODO: might be due to legacy ASEC apps; we should circle back
17969                // and reconcile again once they're scanned
17970                continue;
17971            }
17972
17973            if (ps.getInstalled(userId)) {
17974                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
17975                preparedCount++;
17976            }
17977        }
17978
17979        if (restoreconNeeded) {
17980            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17981                SELinuxMMAC.setRestoreconDone(ceDir);
17982            }
17983            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17984                SELinuxMMAC.setRestoreconDone(deDir);
17985            }
17986        }
17987
17988        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17989                + " packages; restoreconNeeded was " + restoreconNeeded);
17990    }
17991
17992    /**
17993     * Prepare app data for the given app just after it was installed or
17994     * upgraded. This method carefully only touches users that it's installed
17995     * for, and it forces a restorecon to handle any seinfo changes.
17996     * <p>
17997     * Verifies that directories exist and that ownership and labeling is
17998     * correct for all installed apps. If there is an ownership mismatch, it
17999     * will try recovering system apps by wiping data; third-party app data is
18000     * left intact.
18001     */
18002    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18003        prepareAppDataAfterInstallInternal(pkg);
18004        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18005        for (int i = 0; i < childCount; i++) {
18006            PackageParser.Package childPackage = pkg.childPackages.get(i);
18007            prepareAppDataAfterInstallInternal(childPackage);
18008        }
18009    }
18010
18011    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18012        final PackageSetting ps;
18013        synchronized (mPackages) {
18014            ps = mSettings.mPackages.get(pkg.packageName);
18015        }
18016
18017        final UserManager um = mContext.getSystemService(UserManager.class);
18018        for (UserInfo user : um.getUsers()) {
18019            final int flags;
18020            if (um.isUserUnlocked(user.id)) {
18021                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18022            } else if (um.isUserRunning(user.id)) {
18023                flags = StorageManager.FLAG_STORAGE_DE;
18024            } else {
18025                continue;
18026            }
18027
18028            if (ps.getInstalled(user.id)) {
18029                // Whenever an app changes, force a restorecon of its data
18030                // TODO: when user data is locked, mark that we're still dirty
18031                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18032            }
18033        }
18034    }
18035
18036    /**
18037     * Prepare app data for the given app.
18038     * <p>
18039     * Verifies that directories exist and that ownership and labeling is
18040     * correct for all installed apps. If there is an ownership mismatch, this
18041     * will try recovering system apps by wiping data; third-party app data is
18042     * left intact.
18043     */
18044    private void prepareAppData(String volumeUuid, int userId, int flags,
18045            PackageParser.Package pkg, boolean restoreconNeeded) {
18046        if (DEBUG_APP_DATA) {
18047            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18048                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18049        }
18050
18051        final String packageName = pkg.packageName;
18052        final ApplicationInfo app = pkg.applicationInfo;
18053        final int appId = UserHandle.getAppId(app.uid);
18054
18055        Preconditions.checkNotNull(app.seinfo);
18056
18057        synchronized (mInstallLock) {
18058            try {
18059                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18060                        appId, app.seinfo, app.targetSdkVersion);
18061            } catch (InstallerException e) {
18062                if (app.isSystemApp()) {
18063                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18064                            + ", but trying to recover: " + e);
18065                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18066                    try {
18067                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18068                                appId, app.seinfo, app.targetSdkVersion);
18069                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18070                    } catch (InstallerException e2) {
18071                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18072                    }
18073                } else {
18074                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18075                }
18076            }
18077
18078            if (restoreconNeeded) {
18079                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18080            }
18081
18082            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18083                // Create a native library symlink only if we have native libraries
18084                // and if the native libraries are 32 bit libraries. We do not provide
18085                // this symlink for 64 bit libraries.
18086                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18087                    final String nativeLibPath = app.nativeLibraryDir;
18088                    try {
18089                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18090                                nativeLibPath, userId);
18091                    } catch (InstallerException e) {
18092                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18093                    }
18094                }
18095            }
18096        }
18097    }
18098
18099    private void unfreezePackage(String packageName) {
18100        synchronized (mPackages) {
18101            final PackageSetting ps = mSettings.mPackages.get(packageName);
18102            if (ps != null) {
18103                ps.frozen = false;
18104            }
18105        }
18106    }
18107
18108    @Override
18109    public int movePackage(final String packageName, final String volumeUuid) {
18110        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18111
18112        final int moveId = mNextMoveId.getAndIncrement();
18113        mHandler.post(new Runnable() {
18114            @Override
18115            public void run() {
18116                try {
18117                    movePackageInternal(packageName, volumeUuid, moveId);
18118                } catch (PackageManagerException e) {
18119                    Slog.w(TAG, "Failed to move " + packageName, e);
18120                    mMoveCallbacks.notifyStatusChanged(moveId,
18121                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18122                }
18123            }
18124        });
18125        return moveId;
18126    }
18127
18128    private void movePackageInternal(final String packageName, final String volumeUuid,
18129            final int moveId) throws PackageManagerException {
18130        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18131        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18132        final PackageManager pm = mContext.getPackageManager();
18133
18134        final boolean currentAsec;
18135        final String currentVolumeUuid;
18136        final File codeFile;
18137        final String installerPackageName;
18138        final String packageAbiOverride;
18139        final int appId;
18140        final String seinfo;
18141        final String label;
18142        final int targetSdkVersion;
18143
18144        // reader
18145        synchronized (mPackages) {
18146            final PackageParser.Package pkg = mPackages.get(packageName);
18147            final PackageSetting ps = mSettings.mPackages.get(packageName);
18148            if (pkg == null || ps == null) {
18149                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18150            }
18151
18152            if (pkg.applicationInfo.isSystemApp()) {
18153                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18154                        "Cannot move system application");
18155            }
18156
18157            if (pkg.applicationInfo.isExternalAsec()) {
18158                currentAsec = true;
18159                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18160            } else if (pkg.applicationInfo.isForwardLocked()) {
18161                currentAsec = true;
18162                currentVolumeUuid = "forward_locked";
18163            } else {
18164                currentAsec = false;
18165                currentVolumeUuid = ps.volumeUuid;
18166
18167                final File probe = new File(pkg.codePath);
18168                final File probeOat = new File(probe, "oat");
18169                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18170                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18171                            "Move only supported for modern cluster style installs");
18172                }
18173            }
18174
18175            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18176                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18177                        "Package already moved to " + volumeUuid);
18178            }
18179            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18180                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18181                        "Device admin cannot be moved");
18182            }
18183
18184            if (ps.frozen) {
18185                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18186                        "Failed to move already frozen package");
18187            }
18188            ps.frozen = true;
18189
18190            codeFile = new File(pkg.codePath);
18191            installerPackageName = ps.installerPackageName;
18192            packageAbiOverride = ps.cpuAbiOverrideString;
18193            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18194            seinfo = pkg.applicationInfo.seinfo;
18195            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18196            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18197        }
18198
18199        // Now that we're guarded by frozen state, kill app during move
18200        final long token = Binder.clearCallingIdentity();
18201        try {
18202            killApplication(packageName, appId, "move pkg");
18203        } finally {
18204            Binder.restoreCallingIdentity(token);
18205        }
18206
18207        final Bundle extras = new Bundle();
18208        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18209        extras.putString(Intent.EXTRA_TITLE, label);
18210        mMoveCallbacks.notifyCreated(moveId, extras);
18211
18212        int installFlags;
18213        final boolean moveCompleteApp;
18214        final File measurePath;
18215
18216        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18217            installFlags = INSTALL_INTERNAL;
18218            moveCompleteApp = !currentAsec;
18219            measurePath = Environment.getDataAppDirectory(volumeUuid);
18220        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18221            installFlags = INSTALL_EXTERNAL;
18222            moveCompleteApp = false;
18223            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18224        } else {
18225            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18226            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18227                    || !volume.isMountedWritable()) {
18228                unfreezePackage(packageName);
18229                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18230                        "Move location not mounted private volume");
18231            }
18232
18233            Preconditions.checkState(!currentAsec);
18234
18235            installFlags = INSTALL_INTERNAL;
18236            moveCompleteApp = true;
18237            measurePath = Environment.getDataAppDirectory(volumeUuid);
18238        }
18239
18240        final PackageStats stats = new PackageStats(null, -1);
18241        synchronized (mInstaller) {
18242            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18243                unfreezePackage(packageName);
18244                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18245                        "Failed to measure package size");
18246            }
18247        }
18248
18249        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18250                + stats.dataSize);
18251
18252        final long startFreeBytes = measurePath.getFreeSpace();
18253        final long sizeBytes;
18254        if (moveCompleteApp) {
18255            sizeBytes = stats.codeSize + stats.dataSize;
18256        } else {
18257            sizeBytes = stats.codeSize;
18258        }
18259
18260        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18261            unfreezePackage(packageName);
18262            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18263                    "Not enough free space to move");
18264        }
18265
18266        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18267
18268        final CountDownLatch installedLatch = new CountDownLatch(1);
18269        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18270            @Override
18271            public void onUserActionRequired(Intent intent) throws RemoteException {
18272                throw new IllegalStateException();
18273            }
18274
18275            @Override
18276            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18277                    Bundle extras) throws RemoteException {
18278                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18279                        + PackageManager.installStatusToString(returnCode, msg));
18280
18281                installedLatch.countDown();
18282
18283                // Regardless of success or failure of the move operation,
18284                // always unfreeze the package
18285                unfreezePackage(packageName);
18286
18287                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18288                switch (status) {
18289                    case PackageInstaller.STATUS_SUCCESS:
18290                        mMoveCallbacks.notifyStatusChanged(moveId,
18291                                PackageManager.MOVE_SUCCEEDED);
18292                        break;
18293                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18294                        mMoveCallbacks.notifyStatusChanged(moveId,
18295                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18296                        break;
18297                    default:
18298                        mMoveCallbacks.notifyStatusChanged(moveId,
18299                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18300                        break;
18301                }
18302            }
18303        };
18304
18305        final MoveInfo move;
18306        if (moveCompleteApp) {
18307            // Kick off a thread to report progress estimates
18308            new Thread() {
18309                @Override
18310                public void run() {
18311                    while (true) {
18312                        try {
18313                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18314                                break;
18315                            }
18316                        } catch (InterruptedException ignored) {
18317                        }
18318
18319                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18320                        final int progress = 10 + (int) MathUtils.constrain(
18321                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18322                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18323                    }
18324                }
18325            }.start();
18326
18327            final String dataAppName = codeFile.getName();
18328            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18329                    dataAppName, appId, seinfo, targetSdkVersion);
18330        } else {
18331            move = null;
18332        }
18333
18334        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18335
18336        final Message msg = mHandler.obtainMessage(INIT_COPY);
18337        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18338        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18339                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
18340        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18341        msg.obj = params;
18342
18343        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18344                System.identityHashCode(msg.obj));
18345        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18346                System.identityHashCode(msg.obj));
18347
18348        mHandler.sendMessage(msg);
18349    }
18350
18351    @Override
18352    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18353        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18354
18355        final int realMoveId = mNextMoveId.getAndIncrement();
18356        final Bundle extras = new Bundle();
18357        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18358        mMoveCallbacks.notifyCreated(realMoveId, extras);
18359
18360        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18361            @Override
18362            public void onCreated(int moveId, Bundle extras) {
18363                // Ignored
18364            }
18365
18366            @Override
18367            public void onStatusChanged(int moveId, int status, long estMillis) {
18368                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18369            }
18370        };
18371
18372        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18373        storage.setPrimaryStorageUuid(volumeUuid, callback);
18374        return realMoveId;
18375    }
18376
18377    @Override
18378    public int getMoveStatus(int moveId) {
18379        mContext.enforceCallingOrSelfPermission(
18380                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18381        return mMoveCallbacks.mLastStatus.get(moveId);
18382    }
18383
18384    @Override
18385    public void registerMoveCallback(IPackageMoveObserver callback) {
18386        mContext.enforceCallingOrSelfPermission(
18387                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18388        mMoveCallbacks.register(callback);
18389    }
18390
18391    @Override
18392    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18393        mContext.enforceCallingOrSelfPermission(
18394                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18395        mMoveCallbacks.unregister(callback);
18396    }
18397
18398    @Override
18399    public boolean setInstallLocation(int loc) {
18400        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18401                null);
18402        if (getInstallLocation() == loc) {
18403            return true;
18404        }
18405        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18406                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18407            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18408                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18409            return true;
18410        }
18411        return false;
18412   }
18413
18414    @Override
18415    public int getInstallLocation() {
18416        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18417                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18418                PackageHelper.APP_INSTALL_AUTO);
18419    }
18420
18421    /** Called by UserManagerService */
18422    void cleanUpUser(UserManagerService userManager, int userHandle) {
18423        synchronized (mPackages) {
18424            mDirtyUsers.remove(userHandle);
18425            mUserNeedsBadging.delete(userHandle);
18426            mSettings.removeUserLPw(userHandle);
18427            mPendingBroadcasts.remove(userHandle);
18428            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18429        }
18430        synchronized (mInstallLock) {
18431            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18432            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18433                final String volumeUuid = vol.getFsUuid();
18434                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18435                try {
18436                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18437                } catch (InstallerException e) {
18438                    Slog.w(TAG, "Failed to remove user data", e);
18439                }
18440            }
18441            synchronized (mPackages) {
18442                removeUnusedPackagesLILPw(userManager, userHandle);
18443            }
18444        }
18445    }
18446
18447    /**
18448     * We're removing userHandle and would like to remove any downloaded packages
18449     * that are no longer in use by any other user.
18450     * @param userHandle the user being removed
18451     */
18452    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18453        final boolean DEBUG_CLEAN_APKS = false;
18454        int [] users = userManager.getUserIds();
18455        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18456        while (psit.hasNext()) {
18457            PackageSetting ps = psit.next();
18458            if (ps.pkg == null) {
18459                continue;
18460            }
18461            final String packageName = ps.pkg.packageName;
18462            // Skip over if system app
18463            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18464                continue;
18465            }
18466            if (DEBUG_CLEAN_APKS) {
18467                Slog.i(TAG, "Checking package " + packageName);
18468            }
18469            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18470            if (keep) {
18471                if (DEBUG_CLEAN_APKS) {
18472                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18473                }
18474            } else {
18475                for (int i = 0; i < users.length; i++) {
18476                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18477                        keep = true;
18478                        if (DEBUG_CLEAN_APKS) {
18479                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18480                                    + users[i]);
18481                        }
18482                        break;
18483                    }
18484                }
18485            }
18486            if (!keep) {
18487                if (DEBUG_CLEAN_APKS) {
18488                    Slog.i(TAG, "  Removing package " + packageName);
18489                }
18490                mHandler.post(new Runnable() {
18491                    public void run() {
18492                        deletePackageX(packageName, userHandle, 0);
18493                    } //end run
18494                });
18495            }
18496        }
18497    }
18498
18499    /** Called by UserManagerService */
18500    void createNewUser(int userHandle) {
18501        synchronized (mInstallLock) {
18502            try {
18503                mInstaller.createUserConfig(userHandle);
18504            } catch (InstallerException e) {
18505                Slog.w(TAG, "Failed to create user config", e);
18506            }
18507            mSettings.createNewUserLI(this, mInstaller, userHandle);
18508        }
18509        synchronized (mPackages) {
18510            applyFactoryDefaultBrowserLPw(userHandle);
18511            primeDomainVerificationsLPw(userHandle);
18512        }
18513    }
18514
18515    void newUserCreated(final int userHandle) {
18516        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18517        // If permission review for legacy apps is required, we represent
18518        // dagerous permissions for such apps as always granted runtime
18519        // permissions to keep per user flag state whether review is needed.
18520        // Hence, if a new user is added we have to propagate dangerous
18521        // permission grants for these legacy apps.
18522        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18523            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18524                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18525        }
18526    }
18527
18528    @Override
18529    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18530        mContext.enforceCallingOrSelfPermission(
18531                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18532                "Only package verification agents can read the verifier device identity");
18533
18534        synchronized (mPackages) {
18535            return mSettings.getVerifierDeviceIdentityLPw();
18536        }
18537    }
18538
18539    @Override
18540    public void setPermissionEnforced(String permission, boolean enforced) {
18541        // TODO: Now that we no longer change GID for storage, this should to away.
18542        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18543                "setPermissionEnforced");
18544        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18545            synchronized (mPackages) {
18546                if (mSettings.mReadExternalStorageEnforced == null
18547                        || mSettings.mReadExternalStorageEnforced != enforced) {
18548                    mSettings.mReadExternalStorageEnforced = enforced;
18549                    mSettings.writeLPr();
18550                }
18551            }
18552            // kill any non-foreground processes so we restart them and
18553            // grant/revoke the GID.
18554            final IActivityManager am = ActivityManagerNative.getDefault();
18555            if (am != null) {
18556                final long token = Binder.clearCallingIdentity();
18557                try {
18558                    am.killProcessesBelowForeground("setPermissionEnforcement");
18559                } catch (RemoteException e) {
18560                } finally {
18561                    Binder.restoreCallingIdentity(token);
18562                }
18563            }
18564        } else {
18565            throw new IllegalArgumentException("No selective enforcement for " + permission);
18566        }
18567    }
18568
18569    @Override
18570    @Deprecated
18571    public boolean isPermissionEnforced(String permission) {
18572        return true;
18573    }
18574
18575    @Override
18576    public boolean isStorageLow() {
18577        final long token = Binder.clearCallingIdentity();
18578        try {
18579            final DeviceStorageMonitorInternal
18580                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18581            if (dsm != null) {
18582                return dsm.isMemoryLow();
18583            } else {
18584                return false;
18585            }
18586        } finally {
18587            Binder.restoreCallingIdentity(token);
18588        }
18589    }
18590
18591    @Override
18592    public IPackageInstaller getPackageInstaller() {
18593        return mInstallerService;
18594    }
18595
18596    private boolean userNeedsBadging(int userId) {
18597        int index = mUserNeedsBadging.indexOfKey(userId);
18598        if (index < 0) {
18599            final UserInfo userInfo;
18600            final long token = Binder.clearCallingIdentity();
18601            try {
18602                userInfo = sUserManager.getUserInfo(userId);
18603            } finally {
18604                Binder.restoreCallingIdentity(token);
18605            }
18606            final boolean b;
18607            if (userInfo != null && userInfo.isManagedProfile()) {
18608                b = true;
18609            } else {
18610                b = false;
18611            }
18612            mUserNeedsBadging.put(userId, b);
18613            return b;
18614        }
18615        return mUserNeedsBadging.valueAt(index);
18616    }
18617
18618    @Override
18619    public KeySet getKeySetByAlias(String packageName, String alias) {
18620        if (packageName == null || alias == null) {
18621            return null;
18622        }
18623        synchronized(mPackages) {
18624            final PackageParser.Package pkg = mPackages.get(packageName);
18625            if (pkg == null) {
18626                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18627                throw new IllegalArgumentException("Unknown package: " + packageName);
18628            }
18629            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18630            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18631        }
18632    }
18633
18634    @Override
18635    public KeySet getSigningKeySet(String packageName) {
18636        if (packageName == null) {
18637            return null;
18638        }
18639        synchronized(mPackages) {
18640            final PackageParser.Package pkg = mPackages.get(packageName);
18641            if (pkg == null) {
18642                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18643                throw new IllegalArgumentException("Unknown package: " + packageName);
18644            }
18645            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18646                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18647                throw new SecurityException("May not access signing KeySet of other apps.");
18648            }
18649            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18650            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18651        }
18652    }
18653
18654    @Override
18655    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18656        if (packageName == null || ks == null) {
18657            return false;
18658        }
18659        synchronized(mPackages) {
18660            final PackageParser.Package pkg = mPackages.get(packageName);
18661            if (pkg == null) {
18662                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18663                throw new IllegalArgumentException("Unknown package: " + packageName);
18664            }
18665            IBinder ksh = ks.getToken();
18666            if (ksh instanceof KeySetHandle) {
18667                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18668                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18669            }
18670            return false;
18671        }
18672    }
18673
18674    @Override
18675    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18676        if (packageName == null || ks == null) {
18677            return false;
18678        }
18679        synchronized(mPackages) {
18680            final PackageParser.Package pkg = mPackages.get(packageName);
18681            if (pkg == null) {
18682                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18683                throw new IllegalArgumentException("Unknown package: " + packageName);
18684            }
18685            IBinder ksh = ks.getToken();
18686            if (ksh instanceof KeySetHandle) {
18687                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18688                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18689            }
18690            return false;
18691        }
18692    }
18693
18694    private void deletePackageIfUnusedLPr(final String packageName) {
18695        PackageSetting ps = mSettings.mPackages.get(packageName);
18696        if (ps == null) {
18697            return;
18698        }
18699        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18700            // TODO Implement atomic delete if package is unused
18701            // It is currently possible that the package will be deleted even if it is installed
18702            // after this method returns.
18703            mHandler.post(new Runnable() {
18704                public void run() {
18705                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18706                }
18707            });
18708        }
18709    }
18710
18711    /**
18712     * Check and throw if the given before/after packages would be considered a
18713     * downgrade.
18714     */
18715    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18716            throws PackageManagerException {
18717        if (after.versionCode < before.mVersionCode) {
18718            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18719                    "Update version code " + after.versionCode + " is older than current "
18720                    + before.mVersionCode);
18721        } else if (after.versionCode == before.mVersionCode) {
18722            if (after.baseRevisionCode < before.baseRevisionCode) {
18723                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18724                        "Update base revision code " + after.baseRevisionCode
18725                        + " is older than current " + before.baseRevisionCode);
18726            }
18727
18728            if (!ArrayUtils.isEmpty(after.splitNames)) {
18729                for (int i = 0; i < after.splitNames.length; i++) {
18730                    final String splitName = after.splitNames[i];
18731                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18732                    if (j != -1) {
18733                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18734                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18735                                    "Update split " + splitName + " revision code "
18736                                    + after.splitRevisionCodes[i] + " is older than current "
18737                                    + before.splitRevisionCodes[j]);
18738                        }
18739                    }
18740                }
18741            }
18742        }
18743    }
18744
18745    private static class MoveCallbacks extends Handler {
18746        private static final int MSG_CREATED = 1;
18747        private static final int MSG_STATUS_CHANGED = 2;
18748
18749        private final RemoteCallbackList<IPackageMoveObserver>
18750                mCallbacks = new RemoteCallbackList<>();
18751
18752        private final SparseIntArray mLastStatus = new SparseIntArray();
18753
18754        public MoveCallbacks(Looper looper) {
18755            super(looper);
18756        }
18757
18758        public void register(IPackageMoveObserver callback) {
18759            mCallbacks.register(callback);
18760        }
18761
18762        public void unregister(IPackageMoveObserver callback) {
18763            mCallbacks.unregister(callback);
18764        }
18765
18766        @Override
18767        public void handleMessage(Message msg) {
18768            final SomeArgs args = (SomeArgs) msg.obj;
18769            final int n = mCallbacks.beginBroadcast();
18770            for (int i = 0; i < n; i++) {
18771                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18772                try {
18773                    invokeCallback(callback, msg.what, args);
18774                } catch (RemoteException ignored) {
18775                }
18776            }
18777            mCallbacks.finishBroadcast();
18778            args.recycle();
18779        }
18780
18781        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18782                throws RemoteException {
18783            switch (what) {
18784                case MSG_CREATED: {
18785                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18786                    break;
18787                }
18788                case MSG_STATUS_CHANGED: {
18789                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18790                    break;
18791                }
18792            }
18793        }
18794
18795        private void notifyCreated(int moveId, Bundle extras) {
18796            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18797
18798            final SomeArgs args = SomeArgs.obtain();
18799            args.argi1 = moveId;
18800            args.arg2 = extras;
18801            obtainMessage(MSG_CREATED, args).sendToTarget();
18802        }
18803
18804        private void notifyStatusChanged(int moveId, int status) {
18805            notifyStatusChanged(moveId, status, -1);
18806        }
18807
18808        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18809            Slog.v(TAG, "Move " + moveId + " status " + status);
18810
18811            final SomeArgs args = SomeArgs.obtain();
18812            args.argi1 = moveId;
18813            args.argi2 = status;
18814            args.arg3 = estMillis;
18815            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
18816
18817            synchronized (mLastStatus) {
18818                mLastStatus.put(moveId, status);
18819            }
18820        }
18821    }
18822
18823    private final static class OnPermissionChangeListeners extends Handler {
18824        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
18825
18826        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
18827                new RemoteCallbackList<>();
18828
18829        public OnPermissionChangeListeners(Looper looper) {
18830            super(looper);
18831        }
18832
18833        @Override
18834        public void handleMessage(Message msg) {
18835            switch (msg.what) {
18836                case MSG_ON_PERMISSIONS_CHANGED: {
18837                    final int uid = msg.arg1;
18838                    handleOnPermissionsChanged(uid);
18839                } break;
18840            }
18841        }
18842
18843        public void addListenerLocked(IOnPermissionsChangeListener listener) {
18844            mPermissionListeners.register(listener);
18845
18846        }
18847
18848        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
18849            mPermissionListeners.unregister(listener);
18850        }
18851
18852        public void onPermissionsChanged(int uid) {
18853            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
18854                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
18855            }
18856        }
18857
18858        private void handleOnPermissionsChanged(int uid) {
18859            final int count = mPermissionListeners.beginBroadcast();
18860            try {
18861                for (int i = 0; i < count; i++) {
18862                    IOnPermissionsChangeListener callback = mPermissionListeners
18863                            .getBroadcastItem(i);
18864                    try {
18865                        callback.onPermissionsChanged(uid);
18866                    } catch (RemoteException e) {
18867                        Log.e(TAG, "Permission listener is dead", e);
18868                    }
18869                }
18870            } finally {
18871                mPermissionListeners.finishBroadcast();
18872            }
18873        }
18874    }
18875
18876    private class PackageManagerInternalImpl extends PackageManagerInternal {
18877        @Override
18878        public void setLocationPackagesProvider(PackagesProvider provider) {
18879            synchronized (mPackages) {
18880                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
18881            }
18882        }
18883
18884        @Override
18885        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
18886            synchronized (mPackages) {
18887                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
18888            }
18889        }
18890
18891        @Override
18892        public void setSmsAppPackagesProvider(PackagesProvider provider) {
18893            synchronized (mPackages) {
18894                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
18895            }
18896        }
18897
18898        @Override
18899        public void setDialerAppPackagesProvider(PackagesProvider provider) {
18900            synchronized (mPackages) {
18901                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
18902            }
18903        }
18904
18905        @Override
18906        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18907            synchronized (mPackages) {
18908                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18909            }
18910        }
18911
18912        @Override
18913        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18914            synchronized (mPackages) {
18915                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18916            }
18917        }
18918
18919        @Override
18920        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18921            synchronized (mPackages) {
18922                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18923                        packageName, userId);
18924            }
18925        }
18926
18927        @Override
18928        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18929            synchronized (mPackages) {
18930                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18931                        packageName, userId);
18932            }
18933        }
18934
18935        @Override
18936        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18937            synchronized (mPackages) {
18938                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18939                        packageName, userId);
18940            }
18941        }
18942
18943        @Override
18944        public void setKeepUninstalledPackages(final List<String> packageList) {
18945            Preconditions.checkNotNull(packageList);
18946            List<String> removedFromList = null;
18947            synchronized (mPackages) {
18948                if (mKeepUninstalledPackages != null) {
18949                    final int packagesCount = mKeepUninstalledPackages.size();
18950                    for (int i = 0; i < packagesCount; i++) {
18951                        String oldPackage = mKeepUninstalledPackages.get(i);
18952                        if (packageList != null && packageList.contains(oldPackage)) {
18953                            continue;
18954                        }
18955                        if (removedFromList == null) {
18956                            removedFromList = new ArrayList<>();
18957                        }
18958                        removedFromList.add(oldPackage);
18959                    }
18960                }
18961                mKeepUninstalledPackages = new ArrayList<>(packageList);
18962                if (removedFromList != null) {
18963                    final int removedCount = removedFromList.size();
18964                    for (int i = 0; i < removedCount; i++) {
18965                        deletePackageIfUnusedLPr(removedFromList.get(i));
18966                    }
18967                }
18968            }
18969        }
18970
18971        @Override
18972        public boolean isPermissionsReviewRequired(String packageName, int userId) {
18973            synchronized (mPackages) {
18974                // If we do not support permission review, done.
18975                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
18976                    return false;
18977                }
18978
18979                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
18980                if (packageSetting == null) {
18981                    return false;
18982                }
18983
18984                // Permission review applies only to apps not supporting the new permission model.
18985                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
18986                    return false;
18987                }
18988
18989                // Legacy apps have the permission and get user consent on launch.
18990                PermissionsState permissionsState = packageSetting.getPermissionsState();
18991                return permissionsState.isPermissionReviewRequired(userId);
18992            }
18993        }
18994    }
18995
18996    @Override
18997    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18998        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18999        synchronized (mPackages) {
19000            final long identity = Binder.clearCallingIdentity();
19001            try {
19002                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19003                        packageNames, userId);
19004            } finally {
19005                Binder.restoreCallingIdentity(identity);
19006            }
19007        }
19008    }
19009
19010    private static void enforceSystemOrPhoneCaller(String tag) {
19011        int callingUid = Binder.getCallingUid();
19012        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19013            throw new SecurityException(
19014                    "Cannot call " + tag + " from UID " + callingUid);
19015        }
19016    }
19017
19018    boolean isHistoricalPackageUsageAvailable() {
19019        return mPackageUsage.isHistoricalPackageUsageAvailable();
19020    }
19021}
19022