PackageManagerService.java revision 2ab076f611cecb771fe546580634583a27c61aa5
19b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang/*
29b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang * Copyright (C) 2006 The Android Open Source Project
39b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang *
49b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang * Licensed under the Apache License, Version 2.0 (the "License");
59b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang * you may not use this file except in compliance with the License.
69b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang * You may obtain a copy of the License at
79b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang *
89b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang *      http://www.apache.org/licenses/LICENSE-2.0
99b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang *
109b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang * Unless required by applicable law or agreed to in writing, software
119b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang * distributed under the License is distributed on an "AS IS" BASIS,
129b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
139b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang * See the License for the specific language governing permissions and
149b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang * limitations under the License.
159b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang */
169b44532d648d88732c6f17820cf6418c025aecaeTianyuJiang
179b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangpackage com.android.server.pm;
182cbf96ca84097b36a7ae58c494b9145877bf956dTianyuJiang
199b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.Manifest.permission.DELETE_PACKAGES;
209b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.Manifest.permission.INSTALL_PACKAGES;
219b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.Manifest.permission.READ_EXTERNAL_STORAGE;
222cbf96ca84097b36a7ae58c494b9145877bf956dTianyuJiangimport static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
239b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
249b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
259b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.Manifest.permission.WRITE_MEDIA_STORAGE;
269b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
279b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
289b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
299b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
309b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
319b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.DELETE_KEEP_DATA;
329b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
339b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
349b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
359b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
369b44532d648d88732c6f17820cf6418c025aecaeTianyuJiangimport static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppRequest;
132import android.content.pm.AuxiliaryResolveInfo;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.DeviceIdleController;
264import com.android.server.EventLogTags;
265import com.android.server.FgThread;
266import com.android.server.IntentResolver;
267import com.android.server.LocalServices;
268import com.android.server.LockGuard;
269import com.android.server.ServiceThread;
270import com.android.server.SystemConfig;
271import com.android.server.SystemServerInitThreadPool;
272import com.android.server.Watchdog;
273import com.android.server.net.NetworkPolicyManagerInternal;
274import com.android.server.pm.BackgroundDexOptService;
275import com.android.server.pm.Installer.InstallerException;
276import com.android.server.pm.PermissionsState.PermissionState;
277import com.android.server.pm.Settings.DatabaseVersion;
278import com.android.server.pm.Settings.VersionInfo;
279import com.android.server.pm.dex.DexManager;
280import com.android.server.storage.DeviceStorageMonitorInternal;
281
282import dalvik.system.CloseGuard;
283import dalvik.system.DexFile;
284import dalvik.system.VMRuntime;
285
286import libcore.io.IoUtils;
287import libcore.util.EmptyArray;
288
289import org.xmlpull.v1.XmlPullParser;
290import org.xmlpull.v1.XmlPullParserException;
291import org.xmlpull.v1.XmlSerializer;
292
293import java.io.BufferedOutputStream;
294import java.io.BufferedReader;
295import java.io.ByteArrayInputStream;
296import java.io.ByteArrayOutputStream;
297import java.io.File;
298import java.io.FileDescriptor;
299import java.io.FileInputStream;
300import java.io.FileNotFoundException;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub {
369    static final String TAG = "PackageManager";
370    static final boolean DEBUG_SETTINGS = false;
371    static final boolean DEBUG_PREFERRED = false;
372    static final boolean DEBUG_UPGRADE = false;
373    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
374    private static final boolean DEBUG_BACKUP = false;
375    private static final boolean DEBUG_INSTALL = false;
376    private static final boolean DEBUG_REMOVE = false;
377    private static final boolean DEBUG_BROADCASTS = false;
378    private static final boolean DEBUG_SHOW_INFO = false;
379    private static final boolean DEBUG_PACKAGE_INFO = false;
380    private static final boolean DEBUG_INTENT_MATCHING = false;
381    private static final boolean DEBUG_PACKAGE_SCANNING = false;
382    private static final boolean DEBUG_VERIFY = false;
383    private static final boolean DEBUG_FILTERS = false;
384
385    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
386    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
387    // user, but by default initialize to this.
388    public static final boolean DEBUG_DEXOPT = false;
389
390    private static final boolean DEBUG_ABI_SELECTION = false;
391    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
392    private static final boolean DEBUG_TRIAGED_MISSING = false;
393    private static final boolean DEBUG_APP_DATA = false;
394
395    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
396    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
397
398    private static final boolean DISABLE_EPHEMERAL_APPS = false;
399    private static final boolean HIDE_EPHEMERAL_APIS = false;
400
401    private static final boolean ENABLE_FREE_CACHE_V2 =
402            SystemProperties.getBoolean("fw.free_cache_v2", true);
403
404    private static final int RADIO_UID = Process.PHONE_UID;
405    private static final int LOG_UID = Process.LOG_UID;
406    private static final int NFC_UID = Process.NFC_UID;
407    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
408    private static final int SHELL_UID = Process.SHELL_UID;
409
410    // Cap the size of permission trees that 3rd party apps can define
411    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
412
413    // Suffix used during package installation when copying/moving
414    // package apks to install directory.
415    private static final String INSTALL_PACKAGE_SUFFIX = "-";
416
417    static final int SCAN_NO_DEX = 1<<1;
418    static final int SCAN_FORCE_DEX = 1<<2;
419    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
420    static final int SCAN_NEW_INSTALL = 1<<4;
421    static final int SCAN_UPDATE_TIME = 1<<5;
422    static final int SCAN_BOOTING = 1<<6;
423    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
424    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
425    static final int SCAN_REPLACING = 1<<9;
426    static final int SCAN_REQUIRE_KNOWN = 1<<10;
427    static final int SCAN_MOVE = 1<<11;
428    static final int SCAN_INITIAL = 1<<12;
429    static final int SCAN_CHECK_ONLY = 1<<13;
430    static final int SCAN_DONT_KILL_APP = 1<<14;
431    static final int SCAN_IGNORE_FROZEN = 1<<15;
432    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
433    static final int SCAN_AS_INSTANT_APP = 1<<17;
434    static final int SCAN_AS_FULL_APP = 1<<18;
435    /** Should not be with the scan flags */
436    static final int FLAGS_REMOVE_CHATTY = 1<<31;
437
438    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
439
440    private static final int[] EMPTY_INT_ARRAY = new int[0];
441
442    /**
443     * Timeout (in milliseconds) after which the watchdog should declare that
444     * our handler thread is wedged.  The usual default for such things is one
445     * minute but we sometimes do very lengthy I/O operations on this thread,
446     * such as installing multi-gigabyte applications, so ours needs to be longer.
447     */
448    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
449
450    /**
451     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
452     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
453     * settings entry if available, otherwise we use the hardcoded default.  If it's been
454     * more than this long since the last fstrim, we force one during the boot sequence.
455     *
456     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
457     * one gets run at the next available charging+idle time.  This final mandatory
458     * no-fstrim check kicks in only of the other scheduling criteria is never met.
459     */
460    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
461
462    /**
463     * Whether verification is enabled by default.
464     */
465    private static final boolean DEFAULT_VERIFY_ENABLE = true;
466
467    /**
468     * The default maximum time to wait for the verification agent to return in
469     * milliseconds.
470     */
471    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
472
473    /**
474     * The default response for package verification timeout.
475     *
476     * This can be either PackageManager.VERIFICATION_ALLOW or
477     * PackageManager.VERIFICATION_REJECT.
478     */
479    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
480
481    static final String PLATFORM_PACKAGE_NAME = "android";
482
483    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
484
485    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
486            DEFAULT_CONTAINER_PACKAGE,
487            "com.android.defcontainer.DefaultContainerService");
488
489    private static final String KILL_APP_REASON_GIDS_CHANGED =
490            "permission grant or revoke changed gids";
491
492    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
493            "permissions revoked";
494
495    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
496
497    private static final String PACKAGE_SCHEME = "package";
498
499    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
500
501    /** Permission grant: not grant the permission. */
502    private static final int GRANT_DENIED = 1;
503
504    /** Permission grant: grant the permission as an install permission. */
505    private static final int GRANT_INSTALL = 2;
506
507    /** Permission grant: grant the permission as a runtime one. */
508    private static final int GRANT_RUNTIME = 3;
509
510    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
511    private static final int GRANT_UPGRADE = 4;
512
513    /** Canonical intent used to identify what counts as a "web browser" app */
514    private static final Intent sBrowserIntent;
515    static {
516        sBrowserIntent = new Intent();
517        sBrowserIntent.setAction(Intent.ACTION_VIEW);
518        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
519        sBrowserIntent.setData(Uri.parse("http:"));
520    }
521
522    /**
523     * The set of all protected actions [i.e. those actions for which a high priority
524     * intent filter is disallowed].
525     */
526    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
527    static {
528        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
531        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
532    }
533
534    // Compilation reasons.
535    public static final int REASON_FIRST_BOOT = 0;
536    public static final int REASON_BOOT = 1;
537    public static final int REASON_INSTALL = 2;
538    public static final int REASON_BACKGROUND_DEXOPT = 3;
539    public static final int REASON_AB_OTA = 4;
540    public static final int REASON_FORCED_DEXOPT = 5;
541
542    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
543
544    /** All dangerous permission names in the same order as the events in MetricsEvent */
545    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
546            Manifest.permission.READ_CALENDAR,
547            Manifest.permission.WRITE_CALENDAR,
548            Manifest.permission.CAMERA,
549            Manifest.permission.READ_CONTACTS,
550            Manifest.permission.WRITE_CONTACTS,
551            Manifest.permission.GET_ACCOUNTS,
552            Manifest.permission.ACCESS_FINE_LOCATION,
553            Manifest.permission.ACCESS_COARSE_LOCATION,
554            Manifest.permission.RECORD_AUDIO,
555            Manifest.permission.READ_PHONE_STATE,
556            Manifest.permission.CALL_PHONE,
557            Manifest.permission.READ_CALL_LOG,
558            Manifest.permission.WRITE_CALL_LOG,
559            Manifest.permission.ADD_VOICEMAIL,
560            Manifest.permission.USE_SIP,
561            Manifest.permission.PROCESS_OUTGOING_CALLS,
562            Manifest.permission.READ_CELL_BROADCASTS,
563            Manifest.permission.BODY_SENSORS,
564            Manifest.permission.SEND_SMS,
565            Manifest.permission.RECEIVE_SMS,
566            Manifest.permission.READ_SMS,
567            Manifest.permission.RECEIVE_WAP_PUSH,
568            Manifest.permission.RECEIVE_MMS,
569            Manifest.permission.READ_EXTERNAL_STORAGE,
570            Manifest.permission.WRITE_EXTERNAL_STORAGE,
571            Manifest.permission.READ_PHONE_NUMBER,
572            Manifest.permission.ANSWER_PHONE_CALLS);
573
574
575    /**
576     * Version number for the package parser cache. Increment this whenever the format or
577     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
578     */
579    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
580
581    /**
582     * Whether the package parser cache is enabled.
583     */
584    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
585
586    final ServiceThread mHandlerThread;
587
588    final PackageHandler mHandler;
589
590    private final ProcessLoggingHandler mProcessLoggingHandler;
591
592    /**
593     * Messages for {@link #mHandler} that need to wait for system ready before
594     * being dispatched.
595     */
596    private ArrayList<Message> mPostSystemReadyMessages;
597
598    final int mSdkVersion = Build.VERSION.SDK_INT;
599
600    final Context mContext;
601    final boolean mFactoryTest;
602    final boolean mOnlyCore;
603    final DisplayMetrics mMetrics;
604    final int mDefParseFlags;
605    final String[] mSeparateProcesses;
606    final boolean mIsUpgrade;
607    final boolean mIsPreNUpgrade;
608    final boolean mIsPreNMR1Upgrade;
609
610    @GuardedBy("mPackages")
611    private boolean mDexOptDialogShown;
612
613    /** The location for ASEC container files on internal storage. */
614    final String mAsecInternalPath;
615
616    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
617    // LOCK HELD.  Can be called with mInstallLock held.
618    @GuardedBy("mInstallLock")
619    final Installer mInstaller;
620
621    /** Directory where installed third-party apps stored */
622    final File mAppInstallDir;
623
624    /**
625     * Directory to which applications installed internally have their
626     * 32 bit native libraries copied.
627     */
628    private File mAppLib32InstallDir;
629
630    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
631    // apps.
632    final File mDrmAppPrivateInstallDir;
633
634    // ----------------------------------------------------------------
635
636    // Lock for state used when installing and doing other long running
637    // operations.  Methods that must be called with this lock held have
638    // the suffix "LI".
639    final Object mInstallLock = new Object();
640
641    // ----------------------------------------------------------------
642
643    // Keys are String (package name), values are Package.  This also serves
644    // as the lock for the global state.  Methods that must be called with
645    // this lock held have the prefix "LP".
646    @GuardedBy("mPackages")
647    final ArrayMap<String, PackageParser.Package> mPackages =
648            new ArrayMap<String, PackageParser.Package>();
649
650    final ArrayMap<String, Set<String>> mKnownCodebase =
651            new ArrayMap<String, Set<String>>();
652
653    // List of APK paths to load for each user and package. This data is never
654    // persisted by the package manager. Instead, the overlay manager will
655    // ensure the data is up-to-date in runtime.
656    @GuardedBy("mPackages")
657    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
658        new SparseArray<ArrayMap<String, ArrayList<String>>>();
659
660    /**
661     * Tracks new system packages [received in an OTA] that we expect to
662     * find updated user-installed versions. Keys are package name, values
663     * are package location.
664     */
665    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
666    /**
667     * Tracks high priority intent filters for protected actions. During boot, certain
668     * filter actions are protected and should never be allowed to have a high priority
669     * intent filter for them. However, there is one, and only one exception -- the
670     * setup wizard. It must be able to define a high priority intent filter for these
671     * actions to ensure there are no escapes from the wizard. We need to delay processing
672     * of these during boot as we need to look at all of the system packages in order
673     * to know which component is the setup wizard.
674     */
675    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
676    /**
677     * Whether or not processing protected filters should be deferred.
678     */
679    private boolean mDeferProtectedFilters = true;
680
681    /**
682     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
683     */
684    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
685    /**
686     * Whether or not system app permissions should be promoted from install to runtime.
687     */
688    boolean mPromoteSystemApps;
689
690    @GuardedBy("mPackages")
691    final Settings mSettings;
692
693    /**
694     * Set of package names that are currently "frozen", which means active
695     * surgery is being done on the code/data for that package. The platform
696     * will refuse to launch frozen packages to avoid race conditions.
697     *
698     * @see PackageFreezer
699     */
700    @GuardedBy("mPackages")
701    final ArraySet<String> mFrozenPackages = new ArraySet<>();
702
703    final ProtectedPackages mProtectedPackages;
704
705    boolean mFirstBoot;
706
707    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
708
709    // System configuration read by SystemConfig.
710    final int[] mGlobalGids;
711    final SparseArray<ArraySet<String>> mSystemPermissions;
712    @GuardedBy("mAvailableFeatures")
713    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
714
715    // If mac_permissions.xml was found for seinfo labeling.
716    boolean mFoundPolicyFile;
717
718    private final InstantAppRegistry mInstantAppRegistry;
719
720    @GuardedBy("mPackages")
721    int mChangedPackagesSequenceNumber;
722    /**
723     * List of changed [installed, removed or updated] packages.
724     * mapping from user id -> sequence number -> package name
725     */
726    @GuardedBy("mPackages")
727    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
728    /**
729     * The sequence number of the last change to a package.
730     * mapping from user id -> package name -> sequence number
731     */
732    @GuardedBy("mPackages")
733    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
734
735    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
736        @Override public boolean hasFeature(String feature) {
737            return PackageManagerService.this.hasSystemFeature(feature, 0);
738        }
739    };
740
741    public static final class SharedLibraryEntry {
742        public final String path;
743        public final String apk;
744        public final SharedLibraryInfo info;
745
746        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
747                String declaringPackageName, int declaringPackageVersionCode) {
748            path = _path;
749            apk = _apk;
750            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
751                    declaringPackageName, declaringPackageVersionCode), null);
752        }
753    }
754
755    // Currently known shared libraries.
756    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
757    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
758            new ArrayMap<>();
759
760    // All available activities, for your resolving pleasure.
761    final ActivityIntentResolver mActivities =
762            new ActivityIntentResolver();
763
764    // All available receivers, for your resolving pleasure.
765    final ActivityIntentResolver mReceivers =
766            new ActivityIntentResolver();
767
768    // All available services, for your resolving pleasure.
769    final ServiceIntentResolver mServices = new ServiceIntentResolver();
770
771    // All available providers, for your resolving pleasure.
772    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
773
774    // Mapping from provider base names (first directory in content URI codePath)
775    // to the provider information.
776    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
777            new ArrayMap<String, PackageParser.Provider>();
778
779    // Mapping from instrumentation class names to info about them.
780    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
781            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
782
783    // Mapping from permission names to info about them.
784    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
785            new ArrayMap<String, PackageParser.PermissionGroup>();
786
787    // Packages whose data we have transfered into another package, thus
788    // should no longer exist.
789    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
790
791    // Broadcast actions that are only available to the system.
792    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
793
794    /** List of packages waiting for verification. */
795    final SparseArray<PackageVerificationState> mPendingVerification
796            = new SparseArray<PackageVerificationState>();
797
798    /** Set of packages associated with each app op permission. */
799    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
800
801    final PackageInstallerService mInstallerService;
802
803    private final PackageDexOptimizer mPackageDexOptimizer;
804    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
805    // is used by other apps).
806    private final DexManager mDexManager;
807
808    private AtomicInteger mNextMoveId = new AtomicInteger();
809    private final MoveCallbacks mMoveCallbacks;
810
811    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
812
813    // Cache of users who need badging.
814    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
815
816    /** Token for keys in mPendingVerification. */
817    private int mPendingVerificationToken = 0;
818
819    volatile boolean mSystemReady;
820    volatile boolean mSafeMode;
821    volatile boolean mHasSystemUidErrors;
822
823    ApplicationInfo mAndroidApplication;
824    final ActivityInfo mResolveActivity = new ActivityInfo();
825    final ResolveInfo mResolveInfo = new ResolveInfo();
826    ComponentName mResolveComponentName;
827    PackageParser.Package mPlatformPackage;
828    ComponentName mCustomResolverComponentName;
829
830    boolean mResolverReplaced = false;
831
832    private final @Nullable ComponentName mIntentFilterVerifierComponent;
833    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
834
835    private int mIntentFilterVerificationToken = 0;
836
837    /** The service connection to the ephemeral resolver */
838    final EphemeralResolverConnection mInstantAppResolverConnection;
839
840    /** Component used to install ephemeral applications */
841    ComponentName mInstantAppInstallerComponent;
842    /** Component used to show resolver settings for Instant Apps */
843    ComponentName mInstantAppResolverSettingsComponent;
844    ActivityInfo mInstantAppInstallerActivity;
845    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
846
847    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
848            = new SparseArray<IntentFilterVerificationState>();
849
850    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
851
852    // List of packages names to keep cached, even if they are uninstalled for all users
853    private List<String> mKeepUninstalledPackages;
854
855    private UserManagerInternal mUserManagerInternal;
856
857    private DeviceIdleController.LocalService mDeviceIdleController;
858
859    private File mCacheDir;
860
861    private ArraySet<String> mPrivappPermissionsViolations;
862
863    private Future<?> mPrepareAppDataFuture;
864
865    private static class IFVerificationParams {
866        PackageParser.Package pkg;
867        boolean replacing;
868        int userId;
869        int verifierUid;
870
871        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
872                int _userId, int _verifierUid) {
873            pkg = _pkg;
874            replacing = _replacing;
875            userId = _userId;
876            replacing = _replacing;
877            verifierUid = _verifierUid;
878        }
879    }
880
881    private interface IntentFilterVerifier<T extends IntentFilter> {
882        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
883                                               T filter, String packageName);
884        void startVerifications(int userId);
885        void receiveVerificationResponse(int verificationId);
886    }
887
888    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
889        private Context mContext;
890        private ComponentName mIntentFilterVerifierComponent;
891        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
892
893        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
894            mContext = context;
895            mIntentFilterVerifierComponent = verifierComponent;
896        }
897
898        private String getDefaultScheme() {
899            return IntentFilter.SCHEME_HTTPS;
900        }
901
902        @Override
903        public void startVerifications(int userId) {
904            // Launch verifications requests
905            int count = mCurrentIntentFilterVerifications.size();
906            for (int n=0; n<count; n++) {
907                int verificationId = mCurrentIntentFilterVerifications.get(n);
908                final IntentFilterVerificationState ivs =
909                        mIntentFilterVerificationStates.get(verificationId);
910
911                String packageName = ivs.getPackageName();
912
913                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
914                final int filterCount = filters.size();
915                ArraySet<String> domainsSet = new ArraySet<>();
916                for (int m=0; m<filterCount; m++) {
917                    PackageParser.ActivityIntentInfo filter = filters.get(m);
918                    domainsSet.addAll(filter.getHostsList());
919                }
920                synchronized (mPackages) {
921                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
922                            packageName, domainsSet) != null) {
923                        scheduleWriteSettingsLocked();
924                    }
925                }
926                sendVerificationRequest(userId, verificationId, ivs);
927            }
928            mCurrentIntentFilterVerifications.clear();
929        }
930
931        private void sendVerificationRequest(int userId, int verificationId,
932                IntentFilterVerificationState ivs) {
933
934            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
935            verificationIntent.putExtra(
936                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
937                    verificationId);
938            verificationIntent.putExtra(
939                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
940                    getDefaultScheme());
941            verificationIntent.putExtra(
942                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
943                    ivs.getHostsString());
944            verificationIntent.putExtra(
945                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
946                    ivs.getPackageName());
947            verificationIntent.setComponent(mIntentFilterVerifierComponent);
948            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
949
950            UserHandle user = new UserHandle(userId);
951            mContext.sendBroadcastAsUser(verificationIntent, user);
952            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
953                    "Sending IntentFilter verification broadcast");
954        }
955
956        public void receiveVerificationResponse(int verificationId) {
957            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
958
959            final boolean verified = ivs.isVerified();
960
961            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
962            final int count = filters.size();
963            if (DEBUG_DOMAIN_VERIFICATION) {
964                Slog.i(TAG, "Received verification response " + verificationId
965                        + " for " + count + " filters, verified=" + verified);
966            }
967            for (int n=0; n<count; n++) {
968                PackageParser.ActivityIntentInfo filter = filters.get(n);
969                filter.setVerified(verified);
970
971                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
972                        + " verified with result:" + verified + " and hosts:"
973                        + ivs.getHostsString());
974            }
975
976            mIntentFilterVerificationStates.remove(verificationId);
977
978            final String packageName = ivs.getPackageName();
979            IntentFilterVerificationInfo ivi = null;
980
981            synchronized (mPackages) {
982                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
983            }
984            if (ivi == null) {
985                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
986                        + verificationId + " packageName:" + packageName);
987                return;
988            }
989            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
990                    "Updating IntentFilterVerificationInfo for package " + packageName
991                            +" verificationId:" + verificationId);
992
993            synchronized (mPackages) {
994                if (verified) {
995                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
996                } else {
997                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
998                }
999                scheduleWriteSettingsLocked();
1000
1001                final int userId = ivs.getUserId();
1002                if (userId != UserHandle.USER_ALL) {
1003                    final int userStatus =
1004                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1005
1006                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1007                    boolean needUpdate = false;
1008
1009                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1010                    // already been set by the User thru the Disambiguation dialog
1011                    switch (userStatus) {
1012                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1013                            if (verified) {
1014                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1015                            } else {
1016                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1017                            }
1018                            needUpdate = true;
1019                            break;
1020
1021                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1022                            if (verified) {
1023                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1024                                needUpdate = true;
1025                            }
1026                            break;
1027
1028                        default:
1029                            // Nothing to do
1030                    }
1031
1032                    if (needUpdate) {
1033                        mSettings.updateIntentFilterVerificationStatusLPw(
1034                                packageName, updatedStatus, userId);
1035                        scheduleWritePackageRestrictionsLocked(userId);
1036                    }
1037                }
1038            }
1039        }
1040
1041        @Override
1042        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1043                    ActivityIntentInfo filter, String packageName) {
1044            if (!hasValidDomains(filter)) {
1045                return false;
1046            }
1047            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1048            if (ivs == null) {
1049                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1050                        packageName);
1051            }
1052            if (DEBUG_DOMAIN_VERIFICATION) {
1053                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1054            }
1055            ivs.addFilter(filter);
1056            return true;
1057        }
1058
1059        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1060                int userId, int verificationId, String packageName) {
1061            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1062                    verifierUid, userId, packageName);
1063            ivs.setPendingState();
1064            synchronized (mPackages) {
1065                mIntentFilterVerificationStates.append(verificationId, ivs);
1066                mCurrentIntentFilterVerifications.add(verificationId);
1067            }
1068            return ivs;
1069        }
1070    }
1071
1072    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1073        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1074                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1075                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1076    }
1077
1078    // Set of pending broadcasts for aggregating enable/disable of components.
1079    static class PendingPackageBroadcasts {
1080        // for each user id, a map of <package name -> components within that package>
1081        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1082
1083        public PendingPackageBroadcasts() {
1084            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1085        }
1086
1087        public ArrayList<String> get(int userId, String packageName) {
1088            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1089            return packages.get(packageName);
1090        }
1091
1092        public void put(int userId, String packageName, ArrayList<String> components) {
1093            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1094            packages.put(packageName, components);
1095        }
1096
1097        public void remove(int userId, String packageName) {
1098            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1099            if (packages != null) {
1100                packages.remove(packageName);
1101            }
1102        }
1103
1104        public void remove(int userId) {
1105            mUidMap.remove(userId);
1106        }
1107
1108        public int userIdCount() {
1109            return mUidMap.size();
1110        }
1111
1112        public int userIdAt(int n) {
1113            return mUidMap.keyAt(n);
1114        }
1115
1116        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1117            return mUidMap.get(userId);
1118        }
1119
1120        public int size() {
1121            // total number of pending broadcast entries across all userIds
1122            int num = 0;
1123            for (int i = 0; i< mUidMap.size(); i++) {
1124                num += mUidMap.valueAt(i).size();
1125            }
1126            return num;
1127        }
1128
1129        public void clear() {
1130            mUidMap.clear();
1131        }
1132
1133        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1134            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1135            if (map == null) {
1136                map = new ArrayMap<String, ArrayList<String>>();
1137                mUidMap.put(userId, map);
1138            }
1139            return map;
1140        }
1141    }
1142    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1143
1144    // Service Connection to remote media container service to copy
1145    // package uri's from external media onto secure containers
1146    // or internal storage.
1147    private IMediaContainerService mContainerService = null;
1148
1149    static final int SEND_PENDING_BROADCAST = 1;
1150    static final int MCS_BOUND = 3;
1151    static final int END_COPY = 4;
1152    static final int INIT_COPY = 5;
1153    static final int MCS_UNBIND = 6;
1154    static final int START_CLEANING_PACKAGE = 7;
1155    static final int FIND_INSTALL_LOC = 8;
1156    static final int POST_INSTALL = 9;
1157    static final int MCS_RECONNECT = 10;
1158    static final int MCS_GIVE_UP = 11;
1159    static final int UPDATED_MEDIA_STATUS = 12;
1160    static final int WRITE_SETTINGS = 13;
1161    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1162    static final int PACKAGE_VERIFIED = 15;
1163    static final int CHECK_PENDING_VERIFICATION = 16;
1164    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1165    static final int INTENT_FILTER_VERIFIED = 18;
1166    static final int WRITE_PACKAGE_LIST = 19;
1167    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1168
1169    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1170
1171    // Delay time in millisecs
1172    static final int BROADCAST_DELAY = 10 * 1000;
1173
1174    static UserManagerService sUserManager;
1175
1176    // Stores a list of users whose package restrictions file needs to be updated
1177    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1178
1179    final private DefaultContainerConnection mDefContainerConn =
1180            new DefaultContainerConnection();
1181    class DefaultContainerConnection implements ServiceConnection {
1182        public void onServiceConnected(ComponentName name, IBinder service) {
1183            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1184            final IMediaContainerService imcs = IMediaContainerService.Stub
1185                    .asInterface(Binder.allowBlocking(service));
1186            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1187        }
1188
1189        public void onServiceDisconnected(ComponentName name) {
1190            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1191        }
1192    }
1193
1194    // Recordkeeping of restore-after-install operations that are currently in flight
1195    // between the Package Manager and the Backup Manager
1196    static class PostInstallData {
1197        public InstallArgs args;
1198        public PackageInstalledInfo res;
1199
1200        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1201            args = _a;
1202            res = _r;
1203        }
1204    }
1205
1206    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1207    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1208
1209    // XML tags for backup/restore of various bits of state
1210    private static final String TAG_PREFERRED_BACKUP = "pa";
1211    private static final String TAG_DEFAULT_APPS = "da";
1212    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1213
1214    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1215    private static final String TAG_ALL_GRANTS = "rt-grants";
1216    private static final String TAG_GRANT = "grant";
1217    private static final String ATTR_PACKAGE_NAME = "pkg";
1218
1219    private static final String TAG_PERMISSION = "perm";
1220    private static final String ATTR_PERMISSION_NAME = "name";
1221    private static final String ATTR_IS_GRANTED = "g";
1222    private static final String ATTR_USER_SET = "set";
1223    private static final String ATTR_USER_FIXED = "fixed";
1224    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1225
1226    // System/policy permission grants are not backed up
1227    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1228            FLAG_PERMISSION_POLICY_FIXED
1229            | FLAG_PERMISSION_SYSTEM_FIXED
1230            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1231
1232    // And we back up these user-adjusted states
1233    private static final int USER_RUNTIME_GRANT_MASK =
1234            FLAG_PERMISSION_USER_SET
1235            | FLAG_PERMISSION_USER_FIXED
1236            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1237
1238    final @Nullable String mRequiredVerifierPackage;
1239    final @NonNull String mRequiredInstallerPackage;
1240    final @NonNull String mRequiredUninstallerPackage;
1241    final @Nullable String mSetupWizardPackage;
1242    final @Nullable String mStorageManagerPackage;
1243    final @NonNull String mServicesSystemSharedLibraryPackageName;
1244    final @NonNull String mSharedSystemSharedLibraryPackageName;
1245
1246    final boolean mPermissionReviewRequired;
1247
1248    private final PackageUsage mPackageUsage = new PackageUsage();
1249    private final CompilerStats mCompilerStats = new CompilerStats();
1250
1251    class PackageHandler extends Handler {
1252        private boolean mBound = false;
1253        final ArrayList<HandlerParams> mPendingInstalls =
1254            new ArrayList<HandlerParams>();
1255
1256        private boolean connectToService() {
1257            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1258                    " DefaultContainerService");
1259            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1260            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1261            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1262                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1263                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1264                mBound = true;
1265                return true;
1266            }
1267            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1268            return false;
1269        }
1270
1271        private void disconnectService() {
1272            mContainerService = null;
1273            mBound = false;
1274            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1275            mContext.unbindService(mDefContainerConn);
1276            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1277        }
1278
1279        PackageHandler(Looper looper) {
1280            super(looper);
1281        }
1282
1283        public void handleMessage(Message msg) {
1284            try {
1285                doHandleMessage(msg);
1286            } finally {
1287                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1288            }
1289        }
1290
1291        void doHandleMessage(Message msg) {
1292            switch (msg.what) {
1293                case INIT_COPY: {
1294                    HandlerParams params = (HandlerParams) msg.obj;
1295                    int idx = mPendingInstalls.size();
1296                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1297                    // If a bind was already initiated we dont really
1298                    // need to do anything. The pending install
1299                    // will be processed later on.
1300                    if (!mBound) {
1301                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1302                                System.identityHashCode(mHandler));
1303                        // If this is the only one pending we might
1304                        // have to bind to the service again.
1305                        if (!connectToService()) {
1306                            Slog.e(TAG, "Failed to bind to media container service");
1307                            params.serviceError();
1308                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1309                                    System.identityHashCode(mHandler));
1310                            if (params.traceMethod != null) {
1311                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1312                                        params.traceCookie);
1313                            }
1314                            return;
1315                        } else {
1316                            // Once we bind to the service, the first
1317                            // pending request will be processed.
1318                            mPendingInstalls.add(idx, params);
1319                        }
1320                    } else {
1321                        mPendingInstalls.add(idx, params);
1322                        // Already bound to the service. Just make
1323                        // sure we trigger off processing the first request.
1324                        if (idx == 0) {
1325                            mHandler.sendEmptyMessage(MCS_BOUND);
1326                        }
1327                    }
1328                    break;
1329                }
1330                case MCS_BOUND: {
1331                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1332                    if (msg.obj != null) {
1333                        mContainerService = (IMediaContainerService) msg.obj;
1334                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1335                                System.identityHashCode(mHandler));
1336                    }
1337                    if (mContainerService == null) {
1338                        if (!mBound) {
1339                            // Something seriously wrong since we are not bound and we are not
1340                            // waiting for connection. Bail out.
1341                            Slog.e(TAG, "Cannot bind to media container service");
1342                            for (HandlerParams params : mPendingInstalls) {
1343                                // Indicate service bind error
1344                                params.serviceError();
1345                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1346                                        System.identityHashCode(params));
1347                                if (params.traceMethod != null) {
1348                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1349                                            params.traceMethod, params.traceCookie);
1350                                }
1351                                return;
1352                            }
1353                            mPendingInstalls.clear();
1354                        } else {
1355                            Slog.w(TAG, "Waiting to connect to media container service");
1356                        }
1357                    } else if (mPendingInstalls.size() > 0) {
1358                        HandlerParams params = mPendingInstalls.get(0);
1359                        if (params != null) {
1360                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1361                                    System.identityHashCode(params));
1362                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1363                            if (params.startCopy()) {
1364                                // We are done...  look for more work or to
1365                                // go idle.
1366                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1367                                        "Checking for more work or unbind...");
1368                                // Delete pending install
1369                                if (mPendingInstalls.size() > 0) {
1370                                    mPendingInstalls.remove(0);
1371                                }
1372                                if (mPendingInstalls.size() == 0) {
1373                                    if (mBound) {
1374                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1375                                                "Posting delayed MCS_UNBIND");
1376                                        removeMessages(MCS_UNBIND);
1377                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1378                                        // Unbind after a little delay, to avoid
1379                                        // continual thrashing.
1380                                        sendMessageDelayed(ubmsg, 10000);
1381                                    }
1382                                } else {
1383                                    // There are more pending requests in queue.
1384                                    // Just post MCS_BOUND message to trigger processing
1385                                    // of next pending install.
1386                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1387                                            "Posting MCS_BOUND for next work");
1388                                    mHandler.sendEmptyMessage(MCS_BOUND);
1389                                }
1390                            }
1391                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1392                        }
1393                    } else {
1394                        // Should never happen ideally.
1395                        Slog.w(TAG, "Empty queue");
1396                    }
1397                    break;
1398                }
1399                case MCS_RECONNECT: {
1400                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1401                    if (mPendingInstalls.size() > 0) {
1402                        if (mBound) {
1403                            disconnectService();
1404                        }
1405                        if (!connectToService()) {
1406                            Slog.e(TAG, "Failed to bind to media container service");
1407                            for (HandlerParams params : mPendingInstalls) {
1408                                // Indicate service bind error
1409                                params.serviceError();
1410                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1411                                        System.identityHashCode(params));
1412                            }
1413                            mPendingInstalls.clear();
1414                        }
1415                    }
1416                    break;
1417                }
1418                case MCS_UNBIND: {
1419                    // If there is no actual work left, then time to unbind.
1420                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1421
1422                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1423                        if (mBound) {
1424                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1425
1426                            disconnectService();
1427                        }
1428                    } else if (mPendingInstalls.size() > 0) {
1429                        // There are more pending requests in queue.
1430                        // Just post MCS_BOUND message to trigger processing
1431                        // of next pending install.
1432                        mHandler.sendEmptyMessage(MCS_BOUND);
1433                    }
1434
1435                    break;
1436                }
1437                case MCS_GIVE_UP: {
1438                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1439                    HandlerParams params = mPendingInstalls.remove(0);
1440                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1441                            System.identityHashCode(params));
1442                    break;
1443                }
1444                case SEND_PENDING_BROADCAST: {
1445                    String packages[];
1446                    ArrayList<String> components[];
1447                    int size = 0;
1448                    int uids[];
1449                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1450                    synchronized (mPackages) {
1451                        if (mPendingBroadcasts == null) {
1452                            return;
1453                        }
1454                        size = mPendingBroadcasts.size();
1455                        if (size <= 0) {
1456                            // Nothing to be done. Just return
1457                            return;
1458                        }
1459                        packages = new String[size];
1460                        components = new ArrayList[size];
1461                        uids = new int[size];
1462                        int i = 0;  // filling out the above arrays
1463
1464                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1465                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1466                            Iterator<Map.Entry<String, ArrayList<String>>> it
1467                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1468                                            .entrySet().iterator();
1469                            while (it.hasNext() && i < size) {
1470                                Map.Entry<String, ArrayList<String>> ent = it.next();
1471                                packages[i] = ent.getKey();
1472                                components[i] = ent.getValue();
1473                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1474                                uids[i] = (ps != null)
1475                                        ? UserHandle.getUid(packageUserId, ps.appId)
1476                                        : -1;
1477                                i++;
1478                            }
1479                        }
1480                        size = i;
1481                        mPendingBroadcasts.clear();
1482                    }
1483                    // Send broadcasts
1484                    for (int i = 0; i < size; i++) {
1485                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1486                    }
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1488                    break;
1489                }
1490                case START_CLEANING_PACKAGE: {
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1492                    final String packageName = (String)msg.obj;
1493                    final int userId = msg.arg1;
1494                    final boolean andCode = msg.arg2 != 0;
1495                    synchronized (mPackages) {
1496                        if (userId == UserHandle.USER_ALL) {
1497                            int[] users = sUserManager.getUserIds();
1498                            for (int user : users) {
1499                                mSettings.addPackageToCleanLPw(
1500                                        new PackageCleanItem(user, packageName, andCode));
1501                            }
1502                        } else {
1503                            mSettings.addPackageToCleanLPw(
1504                                    new PackageCleanItem(userId, packageName, andCode));
1505                        }
1506                    }
1507                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1508                    startCleaningPackages();
1509                } break;
1510                case POST_INSTALL: {
1511                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1512
1513                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1514                    final boolean didRestore = (msg.arg2 != 0);
1515                    mRunningInstalls.delete(msg.arg1);
1516
1517                    if (data != null) {
1518                        InstallArgs args = data.args;
1519                        PackageInstalledInfo parentRes = data.res;
1520
1521                        final boolean grantPermissions = (args.installFlags
1522                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1523                        final boolean killApp = (args.installFlags
1524                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1525                        final String[] grantedPermissions = args.installGrantPermissions;
1526
1527                        // Handle the parent package
1528                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1529                                grantedPermissions, didRestore, args.installerPackageName,
1530                                args.observer);
1531
1532                        // Handle the child packages
1533                        final int childCount = (parentRes.addedChildPackages != null)
1534                                ? parentRes.addedChildPackages.size() : 0;
1535                        for (int i = 0; i < childCount; i++) {
1536                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1537                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1538                                    grantedPermissions, false, args.installerPackageName,
1539                                    args.observer);
1540                        }
1541
1542                        // Log tracing if needed
1543                        if (args.traceMethod != null) {
1544                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1545                                    args.traceCookie);
1546                        }
1547                    } else {
1548                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1549                    }
1550
1551                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1552                } break;
1553                case UPDATED_MEDIA_STATUS: {
1554                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1555                    boolean reportStatus = msg.arg1 == 1;
1556                    boolean doGc = msg.arg2 == 1;
1557                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1558                    if (doGc) {
1559                        // Force a gc to clear up stale containers.
1560                        Runtime.getRuntime().gc();
1561                    }
1562                    if (msg.obj != null) {
1563                        @SuppressWarnings("unchecked")
1564                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1565                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1566                        // Unload containers
1567                        unloadAllContainers(args);
1568                    }
1569                    if (reportStatus) {
1570                        try {
1571                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1572                                    "Invoking StorageManagerService call back");
1573                            PackageHelper.getStorageManager().finishMediaUpdate();
1574                        } catch (RemoteException e) {
1575                            Log.e(TAG, "StorageManagerService not running?");
1576                        }
1577                    }
1578                } break;
1579                case WRITE_SETTINGS: {
1580                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1581                    synchronized (mPackages) {
1582                        removeMessages(WRITE_SETTINGS);
1583                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1584                        mSettings.writeLPr();
1585                        mDirtyUsers.clear();
1586                    }
1587                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1588                } break;
1589                case WRITE_PACKAGE_RESTRICTIONS: {
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1591                    synchronized (mPackages) {
1592                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1593                        for (int userId : mDirtyUsers) {
1594                            mSettings.writePackageRestrictionsLPr(userId);
1595                        }
1596                        mDirtyUsers.clear();
1597                    }
1598                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1599                } break;
1600                case WRITE_PACKAGE_LIST: {
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1602                    synchronized (mPackages) {
1603                        removeMessages(WRITE_PACKAGE_LIST);
1604                        mSettings.writePackageListLPr(msg.arg1);
1605                    }
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1607                } break;
1608                case CHECK_PENDING_VERIFICATION: {
1609                    final int verificationId = msg.arg1;
1610                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1611
1612                    if ((state != null) && !state.timeoutExtended()) {
1613                        final InstallArgs args = state.getInstallArgs();
1614                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1615
1616                        Slog.i(TAG, "Verification timed out for " + originUri);
1617                        mPendingVerification.remove(verificationId);
1618
1619                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1620
1621                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1622                            Slog.i(TAG, "Continuing with installation of " + originUri);
1623                            state.setVerifierResponse(Binder.getCallingUid(),
1624                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1625                            broadcastPackageVerified(verificationId, originUri,
1626                                    PackageManager.VERIFICATION_ALLOW,
1627                                    state.getInstallArgs().getUser());
1628                            try {
1629                                ret = args.copyApk(mContainerService, true);
1630                            } catch (RemoteException e) {
1631                                Slog.e(TAG, "Could not contact the ContainerService");
1632                            }
1633                        } else {
1634                            broadcastPackageVerified(verificationId, originUri,
1635                                    PackageManager.VERIFICATION_REJECT,
1636                                    state.getInstallArgs().getUser());
1637                        }
1638
1639                        Trace.asyncTraceEnd(
1640                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1641
1642                        processPendingInstall(args, ret);
1643                        mHandler.sendEmptyMessage(MCS_UNBIND);
1644                    }
1645                    break;
1646                }
1647                case PACKAGE_VERIFIED: {
1648                    final int verificationId = msg.arg1;
1649
1650                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1651                    if (state == null) {
1652                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1653                        break;
1654                    }
1655
1656                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1657
1658                    state.setVerifierResponse(response.callerUid, response.code);
1659
1660                    if (state.isVerificationComplete()) {
1661                        mPendingVerification.remove(verificationId);
1662
1663                        final InstallArgs args = state.getInstallArgs();
1664                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1665
1666                        int ret;
1667                        if (state.isInstallAllowed()) {
1668                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1669                            broadcastPackageVerified(verificationId, originUri,
1670                                    response.code, state.getInstallArgs().getUser());
1671                            try {
1672                                ret = args.copyApk(mContainerService, true);
1673                            } catch (RemoteException e) {
1674                                Slog.e(TAG, "Could not contact the ContainerService");
1675                            }
1676                        } else {
1677                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1678                        }
1679
1680                        Trace.asyncTraceEnd(
1681                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1682
1683                        processPendingInstall(args, ret);
1684                        mHandler.sendEmptyMessage(MCS_UNBIND);
1685                    }
1686
1687                    break;
1688                }
1689                case START_INTENT_FILTER_VERIFICATIONS: {
1690                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1691                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1692                            params.replacing, params.pkg);
1693                    break;
1694                }
1695                case INTENT_FILTER_VERIFIED: {
1696                    final int verificationId = msg.arg1;
1697
1698                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1699                            verificationId);
1700                    if (state == null) {
1701                        Slog.w(TAG, "Invalid IntentFilter verification token "
1702                                + verificationId + " received");
1703                        break;
1704                    }
1705
1706                    final int userId = state.getUserId();
1707
1708                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1709                            "Processing IntentFilter verification with token:"
1710                            + verificationId + " and userId:" + userId);
1711
1712                    final IntentFilterVerificationResponse response =
1713                            (IntentFilterVerificationResponse) msg.obj;
1714
1715                    state.setVerifierResponse(response.callerUid, response.code);
1716
1717                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1718                            "IntentFilter verification with token:" + verificationId
1719                            + " and userId:" + userId
1720                            + " is settings verifier response with response code:"
1721                            + response.code);
1722
1723                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1724                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1725                                + response.getFailedDomainsString());
1726                    }
1727
1728                    if (state.isVerificationComplete()) {
1729                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1730                    } else {
1731                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1732                                "IntentFilter verification with token:" + verificationId
1733                                + " was not said to be complete");
1734                    }
1735
1736                    break;
1737                }
1738                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1739                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1740                            mInstantAppResolverConnection,
1741                            (InstantAppRequest) msg.obj,
1742                            mInstantAppInstallerActivity,
1743                            mHandler);
1744                }
1745            }
1746        }
1747    }
1748
1749    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1750            boolean killApp, String[] grantedPermissions,
1751            boolean launchedForRestore, String installerPackage,
1752            IPackageInstallObserver2 installObserver) {
1753        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1754            // Send the removed broadcasts
1755            if (res.removedInfo != null) {
1756                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1757            }
1758
1759            // Now that we successfully installed the package, grant runtime
1760            // permissions if requested before broadcasting the install. Also
1761            // for legacy apps in permission review mode we clear the permission
1762            // review flag which is used to emulate runtime permissions for
1763            // legacy apps.
1764            if (grantPermissions) {
1765                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1766            }
1767
1768            final boolean update = res.removedInfo != null
1769                    && res.removedInfo.removedPackage != null;
1770
1771            // If this is the first time we have child packages for a disabled privileged
1772            // app that had no children, we grant requested runtime permissions to the new
1773            // children if the parent on the system image had them already granted.
1774            if (res.pkg.parentPackage != null) {
1775                synchronized (mPackages) {
1776                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1777                }
1778            }
1779
1780            synchronized (mPackages) {
1781                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1782            }
1783
1784            final String packageName = res.pkg.applicationInfo.packageName;
1785
1786            // Determine the set of users who are adding this package for
1787            // the first time vs. those who are seeing an update.
1788            int[] firstUsers = EMPTY_INT_ARRAY;
1789            int[] updateUsers = EMPTY_INT_ARRAY;
1790            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1791            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1792            for (int newUser : res.newUsers) {
1793                if (ps.getInstantApp(newUser)) {
1794                    continue;
1795                }
1796                if (allNewUsers) {
1797                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1798                    continue;
1799                }
1800                boolean isNew = true;
1801                for (int origUser : res.origUsers) {
1802                    if (origUser == newUser) {
1803                        isNew = false;
1804                        break;
1805                    }
1806                }
1807                if (isNew) {
1808                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1809                } else {
1810                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1811                }
1812            }
1813
1814            // Send installed broadcasts if the package is not a static shared lib.
1815            if (res.pkg.staticSharedLibName == null) {
1816                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1817
1818                // Send added for users that see the package for the first time
1819                // sendPackageAddedForNewUsers also deals with system apps
1820                int appId = UserHandle.getAppId(res.uid);
1821                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1822                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1823
1824                // Send added for users that don't see the package for the first time
1825                Bundle extras = new Bundle(1);
1826                extras.putInt(Intent.EXTRA_UID, res.uid);
1827                if (update) {
1828                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1829                }
1830                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1831                        extras, 0 /*flags*/, null /*targetPackage*/,
1832                        null /*finishedReceiver*/, updateUsers);
1833
1834                // Send replaced for users that don't see the package for the first time
1835                if (update) {
1836                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1837                            packageName, extras, 0 /*flags*/,
1838                            null /*targetPackage*/, null /*finishedReceiver*/,
1839                            updateUsers);
1840                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1841                            null /*package*/, null /*extras*/, 0 /*flags*/,
1842                            packageName /*targetPackage*/,
1843                            null /*finishedReceiver*/, updateUsers);
1844                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1845                    // First-install and we did a restore, so we're responsible for the
1846                    // first-launch broadcast.
1847                    if (DEBUG_BACKUP) {
1848                        Slog.i(TAG, "Post-restore of " + packageName
1849                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1850                    }
1851                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1852                }
1853
1854                // Send broadcast package appeared if forward locked/external for all users
1855                // treat asec-hosted packages like removable media on upgrade
1856                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1857                    if (DEBUG_INSTALL) {
1858                        Slog.i(TAG, "upgrading pkg " + res.pkg
1859                                + " is ASEC-hosted -> AVAILABLE");
1860                    }
1861                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1862                    ArrayList<String> pkgList = new ArrayList<>(1);
1863                    pkgList.add(packageName);
1864                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1865                }
1866            }
1867
1868            // Work that needs to happen on first install within each user
1869            if (firstUsers != null && firstUsers.length > 0) {
1870                synchronized (mPackages) {
1871                    for (int userId : firstUsers) {
1872                        // If this app is a browser and it's newly-installed for some
1873                        // users, clear any default-browser state in those users. The
1874                        // app's nature doesn't depend on the user, so we can just check
1875                        // its browser nature in any user and generalize.
1876                        if (packageIsBrowser(packageName, userId)) {
1877                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1878                        }
1879
1880                        // We may also need to apply pending (restored) runtime
1881                        // permission grants within these users.
1882                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1883                    }
1884                }
1885            }
1886
1887            // Log current value of "unknown sources" setting
1888            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1889                    getUnknownSourcesSettings());
1890
1891            // Force a gc to clear up things
1892            Runtime.getRuntime().gc();
1893
1894            // Remove the replaced package's older resources safely now
1895            // We delete after a gc for applications  on sdcard.
1896            if (res.removedInfo != null && res.removedInfo.args != null) {
1897                synchronized (mInstallLock) {
1898                    res.removedInfo.args.doPostDeleteLI(true);
1899                }
1900            }
1901
1902            // Notify DexManager that the package was installed for new users.
1903            // The updated users should already be indexed and the package code paths
1904            // should not change.
1905            // Don't notify the manager for ephemeral apps as they are not expected to
1906            // survive long enough to benefit of background optimizations.
1907            for (int userId : firstUsers) {
1908                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1909                mDexManager.notifyPackageInstalled(info, userId);
1910            }
1911        }
1912
1913        // If someone is watching installs - notify them
1914        if (installObserver != null) {
1915            try {
1916                Bundle extras = extrasForInstallResult(res);
1917                installObserver.onPackageInstalled(res.name, res.returnCode,
1918                        res.returnMsg, extras);
1919            } catch (RemoteException e) {
1920                Slog.i(TAG, "Observer no longer exists.");
1921            }
1922        }
1923    }
1924
1925    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1926            PackageParser.Package pkg) {
1927        if (pkg.parentPackage == null) {
1928            return;
1929        }
1930        if (pkg.requestedPermissions == null) {
1931            return;
1932        }
1933        final PackageSetting disabledSysParentPs = mSettings
1934                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1935        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1936                || !disabledSysParentPs.isPrivileged()
1937                || (disabledSysParentPs.childPackageNames != null
1938                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1939            return;
1940        }
1941        final int[] allUserIds = sUserManager.getUserIds();
1942        final int permCount = pkg.requestedPermissions.size();
1943        for (int i = 0; i < permCount; i++) {
1944            String permission = pkg.requestedPermissions.get(i);
1945            BasePermission bp = mSettings.mPermissions.get(permission);
1946            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1947                continue;
1948            }
1949            for (int userId : allUserIds) {
1950                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1951                        permission, userId)) {
1952                    grantRuntimePermission(pkg.packageName, permission, userId);
1953                }
1954            }
1955        }
1956    }
1957
1958    private StorageEventListener mStorageListener = new StorageEventListener() {
1959        @Override
1960        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1961            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1962                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1963                    final String volumeUuid = vol.getFsUuid();
1964
1965                    // Clean up any users or apps that were removed or recreated
1966                    // while this volume was missing
1967                    sUserManager.reconcileUsers(volumeUuid);
1968                    reconcileApps(volumeUuid);
1969
1970                    // Clean up any install sessions that expired or were
1971                    // cancelled while this volume was missing
1972                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1973
1974                    loadPrivatePackages(vol);
1975
1976                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1977                    unloadPrivatePackages(vol);
1978                }
1979            }
1980
1981            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1982                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1983                    updateExternalMediaStatus(true, false);
1984                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1985                    updateExternalMediaStatus(false, false);
1986                }
1987            }
1988        }
1989
1990        @Override
1991        public void onVolumeForgotten(String fsUuid) {
1992            if (TextUtils.isEmpty(fsUuid)) {
1993                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1994                return;
1995            }
1996
1997            // Remove any apps installed on the forgotten volume
1998            synchronized (mPackages) {
1999                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2000                for (PackageSetting ps : packages) {
2001                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2002                    deletePackageVersioned(new VersionedPackage(ps.name,
2003                            PackageManager.VERSION_CODE_HIGHEST),
2004                            new LegacyPackageDeleteObserver(null).getBinder(),
2005                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2006                    // Try very hard to release any references to this package
2007                    // so we don't risk the system server being killed due to
2008                    // open FDs
2009                    AttributeCache.instance().removePackage(ps.name);
2010                }
2011
2012                mSettings.onVolumeForgotten(fsUuid);
2013                mSettings.writeLPr();
2014            }
2015        }
2016    };
2017
2018    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2019            String[] grantedPermissions) {
2020        for (int userId : userIds) {
2021            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2022        }
2023    }
2024
2025    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2026            String[] grantedPermissions) {
2027        SettingBase sb = (SettingBase) pkg.mExtras;
2028        if (sb == null) {
2029            return;
2030        }
2031
2032        PermissionsState permissionsState = sb.getPermissionsState();
2033
2034        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2035                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2036
2037        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2038                >= Build.VERSION_CODES.M;
2039
2040        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2041
2042        for (String permission : pkg.requestedPermissions) {
2043            final BasePermission bp;
2044            synchronized (mPackages) {
2045                bp = mSettings.mPermissions.get(permission);
2046            }
2047            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2048                    && (!instantApp || bp.isInstant())
2049                    && (grantedPermissions == null
2050                           || ArrayUtils.contains(grantedPermissions, permission))) {
2051                final int flags = permissionsState.getPermissionFlags(permission, userId);
2052                if (supportsRuntimePermissions) {
2053                    // Installer cannot change immutable permissions.
2054                    if ((flags & immutableFlags) == 0) {
2055                        grantRuntimePermission(pkg.packageName, permission, userId);
2056                    }
2057                } else if (mPermissionReviewRequired) {
2058                    // In permission review mode we clear the review flag when we
2059                    // are asked to install the app with all permissions granted.
2060                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2061                        updatePermissionFlags(permission, pkg.packageName,
2062                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2063                    }
2064                }
2065            }
2066        }
2067    }
2068
2069    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2070        Bundle extras = null;
2071        switch (res.returnCode) {
2072            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2073                extras = new Bundle();
2074                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2075                        res.origPermission);
2076                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2077                        res.origPackage);
2078                break;
2079            }
2080            case PackageManager.INSTALL_SUCCEEDED: {
2081                extras = new Bundle();
2082                extras.putBoolean(Intent.EXTRA_REPLACING,
2083                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2084                break;
2085            }
2086        }
2087        return extras;
2088    }
2089
2090    void scheduleWriteSettingsLocked() {
2091        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2092            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2093        }
2094    }
2095
2096    void scheduleWritePackageListLocked(int userId) {
2097        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2098            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2099            msg.arg1 = userId;
2100            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2101        }
2102    }
2103
2104    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2105        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2106        scheduleWritePackageRestrictionsLocked(userId);
2107    }
2108
2109    void scheduleWritePackageRestrictionsLocked(int userId) {
2110        final int[] userIds = (userId == UserHandle.USER_ALL)
2111                ? sUserManager.getUserIds() : new int[]{userId};
2112        for (int nextUserId : userIds) {
2113            if (!sUserManager.exists(nextUserId)) return;
2114            mDirtyUsers.add(nextUserId);
2115            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2116                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2117            }
2118        }
2119    }
2120
2121    public static PackageManagerService main(Context context, Installer installer,
2122            boolean factoryTest, boolean onlyCore) {
2123        // Self-check for initial settings.
2124        PackageManagerServiceCompilerMapping.checkProperties();
2125
2126        PackageManagerService m = new PackageManagerService(context, installer,
2127                factoryTest, onlyCore);
2128        m.enableSystemUserPackages();
2129        ServiceManager.addService("package", m);
2130        return m;
2131    }
2132
2133    private void enableSystemUserPackages() {
2134        if (!UserManager.isSplitSystemUser()) {
2135            return;
2136        }
2137        // For system user, enable apps based on the following conditions:
2138        // - app is whitelisted or belong to one of these groups:
2139        //   -- system app which has no launcher icons
2140        //   -- system app which has INTERACT_ACROSS_USERS permission
2141        //   -- system IME app
2142        // - app is not in the blacklist
2143        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2144        Set<String> enableApps = new ArraySet<>();
2145        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2146                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2147                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2148        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2149        enableApps.addAll(wlApps);
2150        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2151                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2152        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2153        enableApps.removeAll(blApps);
2154        Log.i(TAG, "Applications installed for system user: " + enableApps);
2155        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2156                UserHandle.SYSTEM);
2157        final int allAppsSize = allAps.size();
2158        synchronized (mPackages) {
2159            for (int i = 0; i < allAppsSize; i++) {
2160                String pName = allAps.get(i);
2161                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2162                // Should not happen, but we shouldn't be failing if it does
2163                if (pkgSetting == null) {
2164                    continue;
2165                }
2166                boolean install = enableApps.contains(pName);
2167                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2168                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2169                            + " for system user");
2170                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2171                }
2172            }
2173            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2174        }
2175    }
2176
2177    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2178        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2179                Context.DISPLAY_SERVICE);
2180        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2181    }
2182
2183    /**
2184     * Requests that files preopted on a secondary system partition be copied to the data partition
2185     * if possible.  Note that the actual copying of the files is accomplished by init for security
2186     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2187     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2188     */
2189    private static void requestCopyPreoptedFiles() {
2190        final int WAIT_TIME_MS = 100;
2191        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2192        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2193            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2194            // We will wait for up to 100 seconds.
2195            final long timeStart = SystemClock.uptimeMillis();
2196            final long timeEnd = timeStart + 100 * 1000;
2197            long timeNow = timeStart;
2198            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2199                try {
2200                    Thread.sleep(WAIT_TIME_MS);
2201                } catch (InterruptedException e) {
2202                    // Do nothing
2203                }
2204                timeNow = SystemClock.uptimeMillis();
2205                if (timeNow > timeEnd) {
2206                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2207                    Slog.wtf(TAG, "cppreopt did not finish!");
2208                    break;
2209                }
2210            }
2211
2212            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2213        }
2214    }
2215
2216    public PackageManagerService(Context context, Installer installer,
2217            boolean factoryTest, boolean onlyCore) {
2218        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2219        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2220        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2221                SystemClock.uptimeMillis());
2222
2223        if (mSdkVersion <= 0) {
2224            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2225        }
2226
2227        mContext = context;
2228
2229        mPermissionReviewRequired = context.getResources().getBoolean(
2230                R.bool.config_permissionReviewRequired);
2231
2232        mFactoryTest = factoryTest;
2233        mOnlyCore = onlyCore;
2234        mMetrics = new DisplayMetrics();
2235        mSettings = new Settings(mPackages);
2236        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2237                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2239                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2241                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2243                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2244        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2245                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2246        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2247                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2248
2249        String separateProcesses = SystemProperties.get("debug.separate_processes");
2250        if (separateProcesses != null && separateProcesses.length() > 0) {
2251            if ("*".equals(separateProcesses)) {
2252                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2253                mSeparateProcesses = null;
2254                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2255            } else {
2256                mDefParseFlags = 0;
2257                mSeparateProcesses = separateProcesses.split(",");
2258                Slog.w(TAG, "Running with debug.separate_processes: "
2259                        + separateProcesses);
2260            }
2261        } else {
2262            mDefParseFlags = 0;
2263            mSeparateProcesses = null;
2264        }
2265
2266        mInstaller = installer;
2267        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2268                "*dexopt*");
2269        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2270        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2271
2272        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2273                FgThread.get().getLooper());
2274
2275        getDefaultDisplayMetrics(context, mMetrics);
2276
2277        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2278        SystemConfig systemConfig = SystemConfig.getInstance();
2279        mGlobalGids = systemConfig.getGlobalGids();
2280        mSystemPermissions = systemConfig.getSystemPermissions();
2281        mAvailableFeatures = systemConfig.getAvailableFeatures();
2282        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2283
2284        mProtectedPackages = new ProtectedPackages(mContext);
2285
2286        synchronized (mInstallLock) {
2287        // writer
2288        synchronized (mPackages) {
2289            mHandlerThread = new ServiceThread(TAG,
2290                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2291            mHandlerThread.start();
2292            mHandler = new PackageHandler(mHandlerThread.getLooper());
2293            mProcessLoggingHandler = new ProcessLoggingHandler();
2294            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2295
2296            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2297            mInstantAppRegistry = new InstantAppRegistry(this);
2298
2299            File dataDir = Environment.getDataDirectory();
2300            mAppInstallDir = new File(dataDir, "app");
2301            mAppLib32InstallDir = new File(dataDir, "app-lib");
2302            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2303            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2304            sUserManager = new UserManagerService(context, this,
2305                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2306
2307            // Propagate permission configuration in to package manager.
2308            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2309                    = systemConfig.getPermissions();
2310            for (int i=0; i<permConfig.size(); i++) {
2311                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2312                BasePermission bp = mSettings.mPermissions.get(perm.name);
2313                if (bp == null) {
2314                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2315                    mSettings.mPermissions.put(perm.name, bp);
2316                }
2317                if (perm.gids != null) {
2318                    bp.setGids(perm.gids, perm.perUser);
2319                }
2320            }
2321
2322            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2323            final int builtInLibCount = libConfig.size();
2324            for (int i = 0; i < builtInLibCount; i++) {
2325                String name = libConfig.keyAt(i);
2326                String path = libConfig.valueAt(i);
2327                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2328                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2329            }
2330
2331            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2332
2333            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2334            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2335            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2336
2337            // Clean up orphaned packages for which the code path doesn't exist
2338            // and they are an update to a system app - caused by bug/32321269
2339            final int packageSettingCount = mSettings.mPackages.size();
2340            for (int i = packageSettingCount - 1; i >= 0; i--) {
2341                PackageSetting ps = mSettings.mPackages.valueAt(i);
2342                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2343                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2344                    mSettings.mPackages.removeAt(i);
2345                    mSettings.enableSystemPackageLPw(ps.name);
2346                }
2347            }
2348
2349            if (mFirstBoot) {
2350                requestCopyPreoptedFiles();
2351            }
2352
2353            String customResolverActivity = Resources.getSystem().getString(
2354                    R.string.config_customResolverActivity);
2355            if (TextUtils.isEmpty(customResolverActivity)) {
2356                customResolverActivity = null;
2357            } else {
2358                mCustomResolverComponentName = ComponentName.unflattenFromString(
2359                        customResolverActivity);
2360            }
2361
2362            long startTime = SystemClock.uptimeMillis();
2363
2364            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2365                    startTime);
2366
2367            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2368            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2369
2370            if (bootClassPath == null) {
2371                Slog.w(TAG, "No BOOTCLASSPATH found!");
2372            }
2373
2374            if (systemServerClassPath == null) {
2375                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2376            }
2377
2378            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2379
2380            final VersionInfo ver = mSettings.getInternalVersion();
2381            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2382
2383            // when upgrading from pre-M, promote system app permissions from install to runtime
2384            mPromoteSystemApps =
2385                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2386
2387            // When upgrading from pre-N, we need to handle package extraction like first boot,
2388            // as there is no profiling data available.
2389            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2390
2391            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2392
2393            // save off the names of pre-existing system packages prior to scanning; we don't
2394            // want to automatically grant runtime permissions for new system apps
2395            if (mPromoteSystemApps) {
2396                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2397                while (pkgSettingIter.hasNext()) {
2398                    PackageSetting ps = pkgSettingIter.next();
2399                    if (isSystemApp(ps)) {
2400                        mExistingSystemPackages.add(ps.name);
2401                    }
2402                }
2403            }
2404
2405            mCacheDir = preparePackageParserCache(mIsUpgrade);
2406
2407            // Set flag to monitor and not change apk file paths when
2408            // scanning install directories.
2409            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2410
2411            if (mIsUpgrade || mFirstBoot) {
2412                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2413            }
2414
2415            // Collect vendor overlay packages. (Do this before scanning any apps.)
2416            // For security and version matching reason, only consider
2417            // overlay packages if they reside in the right directory.
2418            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2419                    | PackageParser.PARSE_IS_SYSTEM
2420                    | PackageParser.PARSE_IS_SYSTEM_DIR
2421                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2422
2423            // Find base frameworks (resource packages without code).
2424            scanDirTracedLI(frameworkDir, mDefParseFlags
2425                    | PackageParser.PARSE_IS_SYSTEM
2426                    | PackageParser.PARSE_IS_SYSTEM_DIR
2427                    | PackageParser.PARSE_IS_PRIVILEGED,
2428                    scanFlags | SCAN_NO_DEX, 0);
2429
2430            // Collected privileged system packages.
2431            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2432            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2433                    | PackageParser.PARSE_IS_SYSTEM
2434                    | PackageParser.PARSE_IS_SYSTEM_DIR
2435                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2436
2437            // Collect ordinary system packages.
2438            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2439            scanDirTracedLI(systemAppDir, mDefParseFlags
2440                    | PackageParser.PARSE_IS_SYSTEM
2441                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2442
2443            // Collect all vendor packages.
2444            File vendorAppDir = new File("/vendor/app");
2445            try {
2446                vendorAppDir = vendorAppDir.getCanonicalFile();
2447            } catch (IOException e) {
2448                // failed to look up canonical path, continue with original one
2449            }
2450            scanDirTracedLI(vendorAppDir, mDefParseFlags
2451                    | PackageParser.PARSE_IS_SYSTEM
2452                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2453
2454            // Collect all OEM packages.
2455            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2456            scanDirTracedLI(oemAppDir, mDefParseFlags
2457                    | PackageParser.PARSE_IS_SYSTEM
2458                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2459
2460            // Prune any system packages that no longer exist.
2461            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2462            if (!mOnlyCore) {
2463                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2464                while (psit.hasNext()) {
2465                    PackageSetting ps = psit.next();
2466
2467                    /*
2468                     * If this is not a system app, it can't be a
2469                     * disable system app.
2470                     */
2471                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2472                        continue;
2473                    }
2474
2475                    /*
2476                     * If the package is scanned, it's not erased.
2477                     */
2478                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2479                    if (scannedPkg != null) {
2480                        /*
2481                         * If the system app is both scanned and in the
2482                         * disabled packages list, then it must have been
2483                         * added via OTA. Remove it from the currently
2484                         * scanned package so the previously user-installed
2485                         * application can be scanned.
2486                         */
2487                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2488                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2489                                    + ps.name + "; removing system app.  Last known codePath="
2490                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2491                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2492                                    + scannedPkg.mVersionCode);
2493                            removePackageLI(scannedPkg, true);
2494                            mExpectingBetter.put(ps.name, ps.codePath);
2495                        }
2496
2497                        continue;
2498                    }
2499
2500                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2501                        psit.remove();
2502                        logCriticalInfo(Log.WARN, "System package " + ps.name
2503                                + " no longer exists; it's data will be wiped");
2504                        // Actual deletion of code and data will be handled by later
2505                        // reconciliation step
2506                    } else {
2507                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2508                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2509                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2510                        }
2511                    }
2512                }
2513            }
2514
2515            //look for any incomplete package installations
2516            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2517            for (int i = 0; i < deletePkgsList.size(); i++) {
2518                // Actual deletion of code and data will be handled by later
2519                // reconciliation step
2520                final String packageName = deletePkgsList.get(i).name;
2521                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2522                synchronized (mPackages) {
2523                    mSettings.removePackageLPw(packageName);
2524                }
2525            }
2526
2527            //delete tmp files
2528            deleteTempPackageFiles();
2529
2530            // Remove any shared userIDs that have no associated packages
2531            mSettings.pruneSharedUsersLPw();
2532
2533            if (!mOnlyCore) {
2534                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2535                        SystemClock.uptimeMillis());
2536                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2537
2538                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2539                        | PackageParser.PARSE_FORWARD_LOCK,
2540                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2541
2542                /**
2543                 * Remove disable package settings for any updated system
2544                 * apps that were removed via an OTA. If they're not a
2545                 * previously-updated app, remove them completely.
2546                 * Otherwise, just revoke their system-level permissions.
2547                 */
2548                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2549                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2550                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2551
2552                    String msg;
2553                    if (deletedPkg == null) {
2554                        msg = "Updated system package " + deletedAppName
2555                                + " no longer exists; it's data will be wiped";
2556                        // Actual deletion of code and data will be handled by later
2557                        // reconciliation step
2558                    } else {
2559                        msg = "Updated system app + " + deletedAppName
2560                                + " no longer present; removing system privileges for "
2561                                + deletedAppName;
2562
2563                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2564
2565                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2566                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2567                    }
2568                    logCriticalInfo(Log.WARN, msg);
2569                }
2570
2571                /**
2572                 * Make sure all system apps that we expected to appear on
2573                 * the userdata partition actually showed up. If they never
2574                 * appeared, crawl back and revive the system version.
2575                 */
2576                for (int i = 0; i < mExpectingBetter.size(); i++) {
2577                    final String packageName = mExpectingBetter.keyAt(i);
2578                    if (!mPackages.containsKey(packageName)) {
2579                        final File scanFile = mExpectingBetter.valueAt(i);
2580
2581                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2582                                + " but never showed up; reverting to system");
2583
2584                        int reparseFlags = mDefParseFlags;
2585                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2586                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2587                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2588                                    | PackageParser.PARSE_IS_PRIVILEGED;
2589                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2590                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2591                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2592                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2593                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2594                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2595                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2596                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2597                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2598                        } else {
2599                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2600                            continue;
2601                        }
2602
2603                        mSettings.enableSystemPackageLPw(packageName);
2604
2605                        try {
2606                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2607                        } catch (PackageManagerException e) {
2608                            Slog.e(TAG, "Failed to parse original system package: "
2609                                    + e.getMessage());
2610                        }
2611                    }
2612                }
2613            }
2614            mExpectingBetter.clear();
2615
2616            // Resolve the storage manager.
2617            mStorageManagerPackage = getStorageManagerPackageName();
2618
2619            // Resolve protected action filters. Only the setup wizard is allowed to
2620            // have a high priority filter for these actions.
2621            mSetupWizardPackage = getSetupWizardPackageName();
2622            if (mProtectedFilters.size() > 0) {
2623                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2624                    Slog.i(TAG, "No setup wizard;"
2625                        + " All protected intents capped to priority 0");
2626                }
2627                for (ActivityIntentInfo filter : mProtectedFilters) {
2628                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2629                        if (DEBUG_FILTERS) {
2630                            Slog.i(TAG, "Found setup wizard;"
2631                                + " allow priority " + filter.getPriority() + ";"
2632                                + " package: " + filter.activity.info.packageName
2633                                + " activity: " + filter.activity.className
2634                                + " priority: " + filter.getPriority());
2635                        }
2636                        // skip setup wizard; allow it to keep the high priority filter
2637                        continue;
2638                    }
2639                    Slog.w(TAG, "Protected action; cap priority to 0;"
2640                            + " package: " + filter.activity.info.packageName
2641                            + " activity: " + filter.activity.className
2642                            + " origPrio: " + filter.getPriority());
2643                    filter.setPriority(0);
2644                }
2645            }
2646            mDeferProtectedFilters = false;
2647            mProtectedFilters.clear();
2648
2649            // Now that we know all of the shared libraries, update all clients to have
2650            // the correct library paths.
2651            updateAllSharedLibrariesLPw(null);
2652
2653            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2654                // NOTE: We ignore potential failures here during a system scan (like
2655                // the rest of the commands above) because there's precious little we
2656                // can do about it. A settings error is reported, though.
2657                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2658            }
2659
2660            // Now that we know all the packages we are keeping,
2661            // read and update their last usage times.
2662            mPackageUsage.read(mPackages);
2663            mCompilerStats.read();
2664
2665            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2666                    SystemClock.uptimeMillis());
2667            Slog.i(TAG, "Time to scan packages: "
2668                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2669                    + " seconds");
2670
2671            // If the platform SDK has changed since the last time we booted,
2672            // we need to re-grant app permission to catch any new ones that
2673            // appear.  This is really a hack, and means that apps can in some
2674            // cases get permissions that the user didn't initially explicitly
2675            // allow...  it would be nice to have some better way to handle
2676            // this situation.
2677            int updateFlags = UPDATE_PERMISSIONS_ALL;
2678            if (ver.sdkVersion != mSdkVersion) {
2679                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2680                        + mSdkVersion + "; regranting permissions for internal storage");
2681                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2682            }
2683            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2684            ver.sdkVersion = mSdkVersion;
2685
2686            // If this is the first boot or an update from pre-M, and it is a normal
2687            // boot, then we need to initialize the default preferred apps across
2688            // all defined users.
2689            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2690                for (UserInfo user : sUserManager.getUsers(true)) {
2691                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2692                    applyFactoryDefaultBrowserLPw(user.id);
2693                    primeDomainVerificationsLPw(user.id);
2694                }
2695            }
2696
2697            // Prepare storage for system user really early during boot,
2698            // since core system apps like SettingsProvider and SystemUI
2699            // can't wait for user to start
2700            final int storageFlags;
2701            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2702                storageFlags = StorageManager.FLAG_STORAGE_DE;
2703            } else {
2704                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2705            }
2706            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2707                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2708                    true /* onlyCoreApps */);
2709            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2710                if (deferPackages == null || deferPackages.isEmpty()) {
2711                    return;
2712                }
2713                int count = 0;
2714                for (String pkgName : deferPackages) {
2715                    PackageParser.Package pkg = null;
2716                    synchronized (mPackages) {
2717                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2718                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2719                            pkg = ps.pkg;
2720                        }
2721                    }
2722                    if (pkg != null) {
2723                        synchronized (mInstallLock) {
2724                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2725                                    true /* maybeMigrateAppData */);
2726                        }
2727                        count++;
2728                    }
2729                }
2730                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2731            }, "prepareAppData");
2732
2733            // If this is first boot after an OTA, and a normal boot, then
2734            // we need to clear code cache directories.
2735            // Note that we do *not* clear the application profiles. These remain valid
2736            // across OTAs and are used to drive profile verification (post OTA) and
2737            // profile compilation (without waiting to collect a fresh set of profiles).
2738            if (mIsUpgrade && !onlyCore) {
2739                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2740                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2741                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2742                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2743                        // No apps are running this early, so no need to freeze
2744                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2745                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2746                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2747                    }
2748                }
2749                ver.fingerprint = Build.FINGERPRINT;
2750            }
2751
2752            checkDefaultBrowser();
2753
2754            // clear only after permissions and other defaults have been updated
2755            mExistingSystemPackages.clear();
2756            mPromoteSystemApps = false;
2757
2758            // All the changes are done during package scanning.
2759            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2760
2761            // can downgrade to reader
2762            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2763            mSettings.writeLPr();
2764            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2765
2766            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2767                    SystemClock.uptimeMillis());
2768
2769            if (!mOnlyCore) {
2770                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2771                mRequiredInstallerPackage = getRequiredInstallerLPr();
2772                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2773                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2774                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2775                        mIntentFilterVerifierComponent);
2776                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2777                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2778                        SharedLibraryInfo.VERSION_UNDEFINED);
2779                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2780                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2781                        SharedLibraryInfo.VERSION_UNDEFINED);
2782            } else {
2783                mRequiredVerifierPackage = null;
2784                mRequiredInstallerPackage = null;
2785                mRequiredUninstallerPackage = null;
2786                mIntentFilterVerifierComponent = null;
2787                mIntentFilterVerifier = null;
2788                mServicesSystemSharedLibraryPackageName = null;
2789                mSharedSystemSharedLibraryPackageName = null;
2790            }
2791
2792            mInstallerService = new PackageInstallerService(context, this);
2793            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2794            if (ephemeralResolverComponent != null) {
2795                if (DEBUG_EPHEMERAL) {
2796                    Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent);
2797                }
2798                mInstantAppResolverConnection =
2799                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2800            } else {
2801                mInstantAppResolverConnection = null;
2802            }
2803            updateInstantAppInstallerLocked();
2804            mInstantAppResolverSettingsComponent = getEphemeralResolverSettingsLPr();
2805
2806            // Read and update the usage of dex files.
2807            // Do this at the end of PM init so that all the packages have their
2808            // data directory reconciled.
2809            // At this point we know the code paths of the packages, so we can validate
2810            // the disk file and build the internal cache.
2811            // The usage file is expected to be small so loading and verifying it
2812            // should take a fairly small time compare to the other activities (e.g. package
2813            // scanning).
2814            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2815            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2816            for (int userId : currentUserIds) {
2817                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2818            }
2819            mDexManager.load(userPackages);
2820        } // synchronized (mPackages)
2821        } // synchronized (mInstallLock)
2822
2823        // Now after opening every single application zip, make sure they
2824        // are all flushed.  Not really needed, but keeps things nice and
2825        // tidy.
2826        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2827        Runtime.getRuntime().gc();
2828        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2829
2830        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2831        FallbackCategoryProvider.loadFallbacks();
2832        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2833
2834        // The initial scanning above does many calls into installd while
2835        // holding the mPackages lock, but we're mostly interested in yelling
2836        // once we have a booted system.
2837        mInstaller.setWarnIfHeld(mPackages);
2838
2839        // Expose private service for system components to use.
2840        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2841        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2842    }
2843
2844    private void updateInstantAppInstallerLocked() {
2845        final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent;
2846        final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr();
2847        ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null
2848                ? null : newInstantAppInstaller.getComponentName();
2849
2850        if (newInstantAppInstallerComponent != null
2851                && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) {
2852            if (DEBUG_EPHEMERAL) {
2853                Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent);
2854            }
2855            setUpInstantAppInstallerActivityLP(newInstantAppInstaller);
2856        } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) {
2857            Slog.d(TAG, "Unset ephemeral installer; none available");
2858        }
2859        mInstantAppInstallerComponent = newInstantAppInstallerComponent;
2860    }
2861
2862    private static File preparePackageParserCache(boolean isUpgrade) {
2863        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2864            return null;
2865        }
2866
2867        // Disable package parsing on eng builds to allow for faster incremental development.
2868        if ("eng".equals(Build.TYPE)) {
2869            return null;
2870        }
2871
2872        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2873            Slog.i(TAG, "Disabling package parser cache due to system property.");
2874            return null;
2875        }
2876
2877        // The base directory for the package parser cache lives under /data/system/.
2878        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2879                "package_cache");
2880        if (cacheBaseDir == null) {
2881            return null;
2882        }
2883
2884        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2885        // This also serves to "GC" unused entries when the package cache version changes (which
2886        // can only happen during upgrades).
2887        if (isUpgrade) {
2888            FileUtils.deleteContents(cacheBaseDir);
2889        }
2890
2891
2892        // Return the versioned package cache directory. This is something like
2893        // "/data/system/package_cache/1"
2894        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2895
2896        // The following is a workaround to aid development on non-numbered userdebug
2897        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2898        // the system partition is newer.
2899        //
2900        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2901        // that starts with "eng." to signify that this is an engineering build and not
2902        // destined for release.
2903        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2904            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2905
2906            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2907            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2908            // in general and should not be used for production changes. In this specific case,
2909            // we know that they will work.
2910            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2911            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2912                FileUtils.deleteContents(cacheBaseDir);
2913                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2914            }
2915        }
2916
2917        return cacheDir;
2918    }
2919
2920    @Override
2921    public boolean isFirstBoot() {
2922        return mFirstBoot;
2923    }
2924
2925    @Override
2926    public boolean isOnlyCoreApps() {
2927        return mOnlyCore;
2928    }
2929
2930    @Override
2931    public boolean isUpgrade() {
2932        return mIsUpgrade;
2933    }
2934
2935    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2936        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2937
2938        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2939                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2940                UserHandle.USER_SYSTEM);
2941        if (matches.size() == 1) {
2942            return matches.get(0).getComponentInfo().packageName;
2943        } else if (matches.size() == 0) {
2944            Log.e(TAG, "There should probably be a verifier, but, none were found");
2945            return null;
2946        }
2947        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2948    }
2949
2950    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2951        synchronized (mPackages) {
2952            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2953            if (libraryEntry == null) {
2954                throw new IllegalStateException("Missing required shared library:" + name);
2955            }
2956            return libraryEntry.apk;
2957        }
2958    }
2959
2960    private @NonNull String getRequiredInstallerLPr() {
2961        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2962        intent.addCategory(Intent.CATEGORY_DEFAULT);
2963        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2964
2965        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2966                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2967                UserHandle.USER_SYSTEM);
2968        if (matches.size() == 1) {
2969            ResolveInfo resolveInfo = matches.get(0);
2970            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2971                throw new RuntimeException("The installer must be a privileged app");
2972            }
2973            return matches.get(0).getComponentInfo().packageName;
2974        } else {
2975            throw new RuntimeException("There must be exactly one installer; found " + matches);
2976        }
2977    }
2978
2979    private @NonNull String getRequiredUninstallerLPr() {
2980        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2981        intent.addCategory(Intent.CATEGORY_DEFAULT);
2982        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2983
2984        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2985                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2986                UserHandle.USER_SYSTEM);
2987        if (resolveInfo == null ||
2988                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2989            throw new RuntimeException("There must be exactly one uninstaller; found "
2990                    + resolveInfo);
2991        }
2992        return resolveInfo.getComponentInfo().packageName;
2993    }
2994
2995    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2996        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2997
2998        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2999                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3000                UserHandle.USER_SYSTEM);
3001        ResolveInfo best = null;
3002        final int N = matches.size();
3003        for (int i = 0; i < N; i++) {
3004            final ResolveInfo cur = matches.get(i);
3005            final String packageName = cur.getComponentInfo().packageName;
3006            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3007                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3008                continue;
3009            }
3010
3011            if (best == null || cur.priority > best.priority) {
3012                best = cur;
3013            }
3014        }
3015
3016        if (best != null) {
3017            return best.getComponentInfo().getComponentName();
3018        } else {
3019            throw new RuntimeException("There must be at least one intent filter verifier");
3020        }
3021    }
3022
3023    private @Nullable ComponentName getEphemeralResolverLPr() {
3024        final String[] packageArray =
3025                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3026        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3027            if (DEBUG_EPHEMERAL) {
3028                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3029            }
3030            return null;
3031        }
3032
3033        final int resolveFlags =
3034                MATCH_DIRECT_BOOT_AWARE
3035                | MATCH_DIRECT_BOOT_UNAWARE
3036                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3037        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3038        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3039                resolveFlags, UserHandle.USER_SYSTEM);
3040
3041        final int N = resolvers.size();
3042        if (N == 0) {
3043            if (DEBUG_EPHEMERAL) {
3044                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3045            }
3046            return null;
3047        }
3048
3049        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3050        for (int i = 0; i < N; i++) {
3051            final ResolveInfo info = resolvers.get(i);
3052
3053            if (info.serviceInfo == null) {
3054                continue;
3055            }
3056
3057            final String packageName = info.serviceInfo.packageName;
3058            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3059                if (DEBUG_EPHEMERAL) {
3060                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3061                            + " pkg: " + packageName + ", info:" + info);
3062                }
3063                continue;
3064            }
3065
3066            if (DEBUG_EPHEMERAL) {
3067                Slog.v(TAG, "Ephemeral resolver found;"
3068                        + " pkg: " + packageName + ", info:" + info);
3069            }
3070            return new ComponentName(packageName, info.serviceInfo.name);
3071        }
3072        if (DEBUG_EPHEMERAL) {
3073            Slog.v(TAG, "Ephemeral resolver NOT found");
3074        }
3075        return null;
3076    }
3077
3078    private @Nullable ActivityInfo getEphemeralInstallerLPr() {
3079        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3080        intent.addCategory(Intent.CATEGORY_DEFAULT);
3081        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3082
3083        final int resolveFlags =
3084                MATCH_DIRECT_BOOT_AWARE
3085                | MATCH_DIRECT_BOOT_UNAWARE
3086                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3087        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3088                resolveFlags, UserHandle.USER_SYSTEM);
3089        Iterator<ResolveInfo> iter = matches.iterator();
3090        while (iter.hasNext()) {
3091            final ResolveInfo rInfo = iter.next();
3092            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3093            if (ps != null) {
3094                final PermissionsState permissionsState = ps.getPermissionsState();
3095                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3096                    continue;
3097                }
3098            }
3099            iter.remove();
3100        }
3101        if (matches.size() == 0) {
3102            return null;
3103        } else if (matches.size() == 1) {
3104            return (ActivityInfo) matches.get(0).getComponentInfo();
3105        } else {
3106            throw new RuntimeException(
3107                    "There must be at most one ephemeral installer; found " + matches);
3108        }
3109    }
3110
3111    private @Nullable ComponentName getEphemeralResolverSettingsLPr() {
3112        final Intent intent = new Intent(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3113        intent.addCategory(Intent.CATEGORY_DEFAULT);
3114        final int resolveFlags =
3115                MATCH_DIRECT_BOOT_AWARE
3116                | MATCH_DIRECT_BOOT_UNAWARE
3117                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3118        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
3119                resolveFlags, UserHandle.USER_SYSTEM);
3120        Iterator<ResolveInfo> iter = matches.iterator();
3121        while (iter.hasNext()) {
3122            final ResolveInfo rInfo = iter.next();
3123            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3124            if (ps != null) {
3125                final PermissionsState permissionsState = ps.getPermissionsState();
3126                if (permissionsState.hasPermission(Manifest.permission.ACCESS_INSTANT_APPS, 0)) {
3127                    continue;
3128                }
3129            }
3130            iter.remove();
3131        }
3132        if (matches.size() == 0) {
3133            return null;
3134        } else if (matches.size() == 1) {
3135            return matches.get(0).getComponentInfo().getComponentName();
3136        } else {
3137            throw new RuntimeException(
3138                    "There must be at most one ephemeral resolver settings; found " + matches);
3139        }
3140    }
3141
3142    private void primeDomainVerificationsLPw(int userId) {
3143        if (DEBUG_DOMAIN_VERIFICATION) {
3144            Slog.d(TAG, "Priming domain verifications in user " + userId);
3145        }
3146
3147        SystemConfig systemConfig = SystemConfig.getInstance();
3148        ArraySet<String> packages = systemConfig.getLinkedApps();
3149
3150        for (String packageName : packages) {
3151            PackageParser.Package pkg = mPackages.get(packageName);
3152            if (pkg != null) {
3153                if (!pkg.isSystemApp()) {
3154                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3155                    continue;
3156                }
3157
3158                ArraySet<String> domains = null;
3159                for (PackageParser.Activity a : pkg.activities) {
3160                    for (ActivityIntentInfo filter : a.intents) {
3161                        if (hasValidDomains(filter)) {
3162                            if (domains == null) {
3163                                domains = new ArraySet<String>();
3164                            }
3165                            domains.addAll(filter.getHostsList());
3166                        }
3167                    }
3168                }
3169
3170                if (domains != null && domains.size() > 0) {
3171                    if (DEBUG_DOMAIN_VERIFICATION) {
3172                        Slog.v(TAG, "      + " + packageName);
3173                    }
3174                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3175                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3176                    // and then 'always' in the per-user state actually used for intent resolution.
3177                    final IntentFilterVerificationInfo ivi;
3178                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3179                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3180                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3181                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3182                } else {
3183                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3184                            + "' does not handle web links");
3185                }
3186            } else {
3187                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3188            }
3189        }
3190
3191        scheduleWritePackageRestrictionsLocked(userId);
3192        scheduleWriteSettingsLocked();
3193    }
3194
3195    private void applyFactoryDefaultBrowserLPw(int userId) {
3196        // The default browser app's package name is stored in a string resource,
3197        // with a product-specific overlay used for vendor customization.
3198        String browserPkg = mContext.getResources().getString(
3199                com.android.internal.R.string.default_browser);
3200        if (!TextUtils.isEmpty(browserPkg)) {
3201            // non-empty string => required to be a known package
3202            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3203            if (ps == null) {
3204                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3205                browserPkg = null;
3206            } else {
3207                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3208            }
3209        }
3210
3211        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3212        // default.  If there's more than one, just leave everything alone.
3213        if (browserPkg == null) {
3214            calculateDefaultBrowserLPw(userId);
3215        }
3216    }
3217
3218    private void calculateDefaultBrowserLPw(int userId) {
3219        List<String> allBrowsers = resolveAllBrowserApps(userId);
3220        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3221        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3222    }
3223
3224    private List<String> resolveAllBrowserApps(int userId) {
3225        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3226        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3227                PackageManager.MATCH_ALL, userId);
3228
3229        final int count = list.size();
3230        List<String> result = new ArrayList<String>(count);
3231        for (int i=0; i<count; i++) {
3232            ResolveInfo info = list.get(i);
3233            if (info.activityInfo == null
3234                    || !info.handleAllWebDataURI
3235                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3236                    || result.contains(info.activityInfo.packageName)) {
3237                continue;
3238            }
3239            result.add(info.activityInfo.packageName);
3240        }
3241
3242        return result;
3243    }
3244
3245    private boolean packageIsBrowser(String packageName, int userId) {
3246        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3247                PackageManager.MATCH_ALL, userId);
3248        final int N = list.size();
3249        for (int i = 0; i < N; i++) {
3250            ResolveInfo info = list.get(i);
3251            if (packageName.equals(info.activityInfo.packageName)) {
3252                return true;
3253            }
3254        }
3255        return false;
3256    }
3257
3258    private void checkDefaultBrowser() {
3259        final int myUserId = UserHandle.myUserId();
3260        final String packageName = getDefaultBrowserPackageName(myUserId);
3261        if (packageName != null) {
3262            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3263            if (info == null) {
3264                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3265                synchronized (mPackages) {
3266                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3267                }
3268            }
3269        }
3270    }
3271
3272    @Override
3273    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3274            throws RemoteException {
3275        try {
3276            return super.onTransact(code, data, reply, flags);
3277        } catch (RuntimeException e) {
3278            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3279                Slog.wtf(TAG, "Package Manager Crash", e);
3280            }
3281            throw e;
3282        }
3283    }
3284
3285    static int[] appendInts(int[] cur, int[] add) {
3286        if (add == null) return cur;
3287        if (cur == null) return add;
3288        final int N = add.length;
3289        for (int i=0; i<N; i++) {
3290            cur = appendInt(cur, add[i]);
3291        }
3292        return cur;
3293    }
3294
3295    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3296        if (!sUserManager.exists(userId)) return null;
3297        if (ps == null) {
3298            return null;
3299        }
3300        final PackageParser.Package p = ps.pkg;
3301        if (p == null) {
3302            return null;
3303        }
3304        // Filter out ephemeral app metadata:
3305        //   * The system/shell/root can see metadata for any app
3306        //   * An installed app can see metadata for 1) other installed apps
3307        //     and 2) ephemeral apps that have explicitly interacted with it
3308        //   * Ephemeral apps can only see their own data and exposed installed apps
3309        //   * Holding a signature permission allows seeing instant apps
3310        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3311        if (callingAppId != Process.SYSTEM_UID
3312                && callingAppId != Process.SHELL_UID
3313                && callingAppId != Process.ROOT_UID
3314                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3315                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3316            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3317            if (instantAppPackageName != null) {
3318                // ephemeral apps can only get information on themselves or
3319                // installed apps that are exposed.
3320                if (!instantAppPackageName.equals(p.packageName)
3321                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3322                    return null;
3323                }
3324            } else {
3325                if (ps.getInstantApp(userId)) {
3326                    // only get access to the ephemeral app if we've been granted access
3327                    if (!mInstantAppRegistry.isInstantAccessGranted(
3328                            userId, callingAppId, ps.appId)) {
3329                        return null;
3330                    }
3331                }
3332            }
3333        }
3334
3335        final PermissionsState permissionsState = ps.getPermissionsState();
3336
3337        // Compute GIDs only if requested
3338        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3339                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3340        // Compute granted permissions only if package has requested permissions
3341        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3342                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3343        final PackageUserState state = ps.readUserState(userId);
3344
3345        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3346                && ps.isSystem()) {
3347            flags |= MATCH_ANY_USER;
3348        }
3349
3350        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3351                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3352
3353        if (packageInfo == null) {
3354            return null;
3355        }
3356
3357        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3358
3359        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3360                resolveExternalPackageNameLPr(p);
3361
3362        return packageInfo;
3363    }
3364
3365    @Override
3366    public void checkPackageStartable(String packageName, int userId) {
3367        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3368
3369        synchronized (mPackages) {
3370            final PackageSetting ps = mSettings.mPackages.get(packageName);
3371            if (ps == null) {
3372                throw new SecurityException("Package " + packageName + " was not found!");
3373            }
3374
3375            if (!ps.getInstalled(userId)) {
3376                throw new SecurityException(
3377                        "Package " + packageName + " was not installed for user " + userId + "!");
3378            }
3379
3380            if (mSafeMode && !ps.isSystem()) {
3381                throw new SecurityException("Package " + packageName + " not a system app!");
3382            }
3383
3384            if (mFrozenPackages.contains(packageName)) {
3385                throw new SecurityException("Package " + packageName + " is currently frozen!");
3386            }
3387
3388            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3389                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3390                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3391            }
3392        }
3393    }
3394
3395    @Override
3396    public boolean isPackageAvailable(String packageName, int userId) {
3397        if (!sUserManager.exists(userId)) return false;
3398        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3399                false /* requireFullPermission */, false /* checkShell */, "is package available");
3400        synchronized (mPackages) {
3401            PackageParser.Package p = mPackages.get(packageName);
3402            if (p != null) {
3403                final PackageSetting ps = (PackageSetting) p.mExtras;
3404                if (ps != null) {
3405                    final PackageUserState state = ps.readUserState(userId);
3406                    if (state != null) {
3407                        return PackageParser.isAvailable(state);
3408                    }
3409                }
3410            }
3411        }
3412        return false;
3413    }
3414
3415    @Override
3416    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3417        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3418                flags, userId);
3419    }
3420
3421    @Override
3422    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3423            int flags, int userId) {
3424        return getPackageInfoInternal(versionedPackage.getPackageName(),
3425                // TODO: We will change version code to long, so in the new API it is long
3426                (int) versionedPackage.getVersionCode(), flags, userId);
3427    }
3428
3429    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3430            int flags, int userId) {
3431        if (!sUserManager.exists(userId)) return null;
3432        flags = updateFlagsForPackage(flags, userId, packageName);
3433        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3434                false /* requireFullPermission */, false /* checkShell */, "get package info");
3435
3436        // reader
3437        synchronized (mPackages) {
3438            // Normalize package name to handle renamed packages and static libs
3439            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3440
3441            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3442            if (matchFactoryOnly) {
3443                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3444                if (ps != null) {
3445                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3446                        return null;
3447                    }
3448                    return generatePackageInfo(ps, flags, userId);
3449                }
3450            }
3451
3452            PackageParser.Package p = mPackages.get(packageName);
3453            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3454                return null;
3455            }
3456            if (DEBUG_PACKAGE_INFO)
3457                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3458            if (p != null) {
3459                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3460                        Binder.getCallingUid(), userId)) {
3461                    return null;
3462                }
3463                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3464            }
3465            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3466                final PackageSetting ps = mSettings.mPackages.get(packageName);
3467                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3468                    return null;
3469                }
3470                return generatePackageInfo(ps, flags, userId);
3471            }
3472        }
3473        return null;
3474    }
3475
3476
3477    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3478        // System/shell/root get to see all static libs
3479        final int appId = UserHandle.getAppId(uid);
3480        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3481                || appId == Process.ROOT_UID) {
3482            return false;
3483        }
3484
3485        // No package means no static lib as it is always on internal storage
3486        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3487            return false;
3488        }
3489
3490        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3491                ps.pkg.staticSharedLibVersion);
3492        if (libEntry == null) {
3493            return false;
3494        }
3495
3496        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3497        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3498        if (uidPackageNames == null) {
3499            return true;
3500        }
3501
3502        for (String uidPackageName : uidPackageNames) {
3503            if (ps.name.equals(uidPackageName)) {
3504                return false;
3505            }
3506            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3507            if (uidPs != null) {
3508                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3509                        libEntry.info.getName());
3510                if (index < 0) {
3511                    continue;
3512                }
3513                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3514                    return false;
3515                }
3516            }
3517        }
3518        return true;
3519    }
3520
3521    @Override
3522    public String[] currentToCanonicalPackageNames(String[] names) {
3523        String[] out = new String[names.length];
3524        // reader
3525        synchronized (mPackages) {
3526            for (int i=names.length-1; i>=0; i--) {
3527                PackageSetting ps = mSettings.mPackages.get(names[i]);
3528                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3529            }
3530        }
3531        return out;
3532    }
3533
3534    @Override
3535    public String[] canonicalToCurrentPackageNames(String[] names) {
3536        String[] out = new String[names.length];
3537        // reader
3538        synchronized (mPackages) {
3539            for (int i=names.length-1; i>=0; i--) {
3540                String cur = mSettings.getRenamedPackageLPr(names[i]);
3541                out[i] = cur != null ? cur : names[i];
3542            }
3543        }
3544        return out;
3545    }
3546
3547    @Override
3548    public int getPackageUid(String packageName, int flags, int userId) {
3549        if (!sUserManager.exists(userId)) return -1;
3550        flags = updateFlagsForPackage(flags, userId, packageName);
3551        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3552                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3553
3554        // reader
3555        synchronized (mPackages) {
3556            final PackageParser.Package p = mPackages.get(packageName);
3557            if (p != null && p.isMatch(flags)) {
3558                return UserHandle.getUid(userId, p.applicationInfo.uid);
3559            }
3560            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3561                final PackageSetting ps = mSettings.mPackages.get(packageName);
3562                if (ps != null && ps.isMatch(flags)) {
3563                    return UserHandle.getUid(userId, ps.appId);
3564                }
3565            }
3566        }
3567
3568        return -1;
3569    }
3570
3571    @Override
3572    public int[] getPackageGids(String packageName, int flags, int userId) {
3573        if (!sUserManager.exists(userId)) return null;
3574        flags = updateFlagsForPackage(flags, userId, packageName);
3575        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3576                false /* requireFullPermission */, false /* checkShell */,
3577                "getPackageGids");
3578
3579        // reader
3580        synchronized (mPackages) {
3581            final PackageParser.Package p = mPackages.get(packageName);
3582            if (p != null && p.isMatch(flags)) {
3583                PackageSetting ps = (PackageSetting) p.mExtras;
3584                // TODO: Shouldn't this be checking for package installed state for userId and
3585                // return null?
3586                return ps.getPermissionsState().computeGids(userId);
3587            }
3588            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3589                final PackageSetting ps = mSettings.mPackages.get(packageName);
3590                if (ps != null && ps.isMatch(flags)) {
3591                    return ps.getPermissionsState().computeGids(userId);
3592                }
3593            }
3594        }
3595
3596        return null;
3597    }
3598
3599    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3600        if (bp.perm != null) {
3601            return PackageParser.generatePermissionInfo(bp.perm, flags);
3602        }
3603        PermissionInfo pi = new PermissionInfo();
3604        pi.name = bp.name;
3605        pi.packageName = bp.sourcePackage;
3606        pi.nonLocalizedLabel = bp.name;
3607        pi.protectionLevel = bp.protectionLevel;
3608        return pi;
3609    }
3610
3611    @Override
3612    public PermissionInfo getPermissionInfo(String name, int flags) {
3613        // reader
3614        synchronized (mPackages) {
3615            final BasePermission p = mSettings.mPermissions.get(name);
3616            if (p != null) {
3617                return generatePermissionInfo(p, flags);
3618            }
3619            return null;
3620        }
3621    }
3622
3623    @Override
3624    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3625            int flags) {
3626        // reader
3627        synchronized (mPackages) {
3628            if (group != null && !mPermissionGroups.containsKey(group)) {
3629                // This is thrown as NameNotFoundException
3630                return null;
3631            }
3632
3633            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3634            for (BasePermission p : mSettings.mPermissions.values()) {
3635                if (group == null) {
3636                    if (p.perm == null || p.perm.info.group == null) {
3637                        out.add(generatePermissionInfo(p, flags));
3638                    }
3639                } else {
3640                    if (p.perm != null && group.equals(p.perm.info.group)) {
3641                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3642                    }
3643                }
3644            }
3645            return new ParceledListSlice<>(out);
3646        }
3647    }
3648
3649    @Override
3650    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3651        // reader
3652        synchronized (mPackages) {
3653            return PackageParser.generatePermissionGroupInfo(
3654                    mPermissionGroups.get(name), flags);
3655        }
3656    }
3657
3658    @Override
3659    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3660        // reader
3661        synchronized (mPackages) {
3662            final int N = mPermissionGroups.size();
3663            ArrayList<PermissionGroupInfo> out
3664                    = new ArrayList<PermissionGroupInfo>(N);
3665            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3666                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3667            }
3668            return new ParceledListSlice<>(out);
3669        }
3670    }
3671
3672    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3673            int uid, int userId) {
3674        if (!sUserManager.exists(userId)) return null;
3675        PackageSetting ps = mSettings.mPackages.get(packageName);
3676        if (ps != null) {
3677            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3678                return null;
3679            }
3680            if (ps.pkg == null) {
3681                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3682                if (pInfo != null) {
3683                    return pInfo.applicationInfo;
3684                }
3685                return null;
3686            }
3687            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3688                    ps.readUserState(userId), userId);
3689            if (ai != null) {
3690                rebaseEnabledOverlays(ai, userId);
3691                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3692            }
3693            return ai;
3694        }
3695        return null;
3696    }
3697
3698    @Override
3699    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3700        if (!sUserManager.exists(userId)) return null;
3701        flags = updateFlagsForApplication(flags, userId, packageName);
3702        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3703                false /* requireFullPermission */, false /* checkShell */, "get application info");
3704
3705        // writer
3706        synchronized (mPackages) {
3707            // Normalize package name to handle renamed packages and static libs
3708            packageName = resolveInternalPackageNameLPr(packageName,
3709                    PackageManager.VERSION_CODE_HIGHEST);
3710
3711            PackageParser.Package p = mPackages.get(packageName);
3712            if (DEBUG_PACKAGE_INFO) Log.v(
3713                    TAG, "getApplicationInfo " + packageName
3714                    + ": " + p);
3715            if (p != null) {
3716                PackageSetting ps = mSettings.mPackages.get(packageName);
3717                if (ps == null) return null;
3718                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3719                    return null;
3720                }
3721                // Note: isEnabledLP() does not apply here - always return info
3722                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3723                        p, flags, ps.readUserState(userId), userId);
3724                if (ai != null) {
3725                    rebaseEnabledOverlays(ai, userId);
3726                    ai.packageName = resolveExternalPackageNameLPr(p);
3727                }
3728                return ai;
3729            }
3730            if ("android".equals(packageName)||"system".equals(packageName)) {
3731                return mAndroidApplication;
3732            }
3733            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3734                // Already generates the external package name
3735                return generateApplicationInfoFromSettingsLPw(packageName,
3736                        Binder.getCallingUid(), flags, userId);
3737            }
3738        }
3739        return null;
3740    }
3741
3742    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3743        List<String> paths = new ArrayList<>();
3744        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3745            mEnabledOverlayPaths.get(userId);
3746        if (userSpecificOverlays != null) {
3747            if (!"android".equals(ai.packageName)) {
3748                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3749                if (frameworkOverlays != null) {
3750                    paths.addAll(frameworkOverlays);
3751                }
3752            }
3753
3754            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3755            if (appOverlays != null) {
3756                paths.addAll(appOverlays);
3757            }
3758        }
3759        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3760    }
3761
3762    private String normalizePackageNameLPr(String packageName) {
3763        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3764        return normalizedPackageName != null ? normalizedPackageName : packageName;
3765    }
3766
3767    @Override
3768    public void deletePreloadsFileCache() {
3769        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3770            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3771        }
3772        File dir = Environment.getDataPreloadsFileCacheDirectory();
3773        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3774        FileUtils.deleteContents(dir);
3775    }
3776
3777    @Override
3778    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3779            final IPackageDataObserver observer) {
3780        mContext.enforceCallingOrSelfPermission(
3781                android.Manifest.permission.CLEAR_APP_CACHE, null);
3782        mHandler.post(() -> {
3783            boolean success = false;
3784            try {
3785                freeStorage(volumeUuid, freeStorageSize, 0);
3786                success = true;
3787            } catch (IOException e) {
3788                Slog.w(TAG, e);
3789            }
3790            if (observer != null) {
3791                try {
3792                    observer.onRemoveCompleted(null, success);
3793                } catch (RemoteException e) {
3794                    Slog.w(TAG, e);
3795                }
3796            }
3797        });
3798    }
3799
3800    @Override
3801    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3802            final IntentSender pi) {
3803        mContext.enforceCallingOrSelfPermission(
3804                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3805        mHandler.post(() -> {
3806            boolean success = false;
3807            try {
3808                freeStorage(volumeUuid, freeStorageSize, 0);
3809                success = true;
3810            } catch (IOException e) {
3811                Slog.w(TAG, e);
3812            }
3813            if (pi != null) {
3814                try {
3815                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3816                } catch (SendIntentException e) {
3817                    Slog.w(TAG, e);
3818                }
3819            }
3820        });
3821    }
3822
3823    /**
3824     * Blocking call to clear various types of cached data across the system
3825     * until the requested bytes are available.
3826     */
3827    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3828        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3829        final File file = storage.findPathForUuid(volumeUuid);
3830        if (file.getUsableSpace() >= bytes) return;
3831
3832        if (ENABLE_FREE_CACHE_V2) {
3833            final boolean aggressive = (storageFlags
3834                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3835            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3836                    volumeUuid);
3837
3838            // 1. Pre-flight to determine if we have any chance to succeed
3839            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3840            if (internalVolume && (aggressive || SystemProperties
3841                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3842                deletePreloadsFileCache();
3843                if (file.getUsableSpace() >= bytes) return;
3844            }
3845
3846            // 3. Consider parsed APK data (aggressive only)
3847            if (internalVolume && aggressive) {
3848                FileUtils.deleteContents(mCacheDir);
3849                if (file.getUsableSpace() >= bytes) return;
3850            }
3851
3852            // 4. Consider cached app data (above quotas)
3853            try {
3854                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3855            } catch (InstallerException ignored) {
3856            }
3857            if (file.getUsableSpace() >= bytes) return;
3858
3859            // 5. Consider shared libraries with refcount=0 and age>2h
3860            // 6. Consider dexopt output (aggressive only)
3861            // 7. Consider ephemeral apps not used in last week
3862
3863            // 8. Consider cached app data (below quotas)
3864            try {
3865                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3866                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3867            } catch (InstallerException ignored) {
3868            }
3869            if (file.getUsableSpace() >= bytes) return;
3870
3871            // 9. Consider DropBox entries
3872            // 10. Consider ephemeral cookies
3873
3874        } else {
3875            try {
3876                mInstaller.freeCache(volumeUuid, bytes, 0);
3877            } catch (InstallerException ignored) {
3878            }
3879            if (file.getUsableSpace() >= bytes) return;
3880        }
3881
3882        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3883    }
3884
3885    /**
3886     * Update given flags based on encryption status of current user.
3887     */
3888    private int updateFlags(int flags, int userId) {
3889        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3890                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3891            // Caller expressed an explicit opinion about what encryption
3892            // aware/unaware components they want to see, so fall through and
3893            // give them what they want
3894        } else {
3895            // Caller expressed no opinion, so match based on user state
3896            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3897                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3898            } else {
3899                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3900            }
3901        }
3902        return flags;
3903    }
3904
3905    private UserManagerInternal getUserManagerInternal() {
3906        if (mUserManagerInternal == null) {
3907            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3908        }
3909        return mUserManagerInternal;
3910    }
3911
3912    private DeviceIdleController.LocalService getDeviceIdleController() {
3913        if (mDeviceIdleController == null) {
3914            mDeviceIdleController =
3915                    LocalServices.getService(DeviceIdleController.LocalService.class);
3916        }
3917        return mDeviceIdleController;
3918    }
3919
3920    /**
3921     * Update given flags when being used to request {@link PackageInfo}.
3922     */
3923    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3924        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3925        boolean triaged = true;
3926        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3927                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3928            // Caller is asking for component details, so they'd better be
3929            // asking for specific encryption matching behavior, or be triaged
3930            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3931                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3932                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3933                triaged = false;
3934            }
3935        }
3936        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3937                | PackageManager.MATCH_SYSTEM_ONLY
3938                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3939            triaged = false;
3940        }
3941        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3942            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3943                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3944                    + Debug.getCallers(5));
3945        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3946                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3947            // If the caller wants all packages and has a restricted profile associated with it,
3948            // then match all users. This is to make sure that launchers that need to access work
3949            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3950            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3951            flags |= PackageManager.MATCH_ANY_USER;
3952        }
3953        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3954            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3955                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3956        }
3957        return updateFlags(flags, userId);
3958    }
3959
3960    /**
3961     * Update given flags when being used to request {@link ApplicationInfo}.
3962     */
3963    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3964        return updateFlagsForPackage(flags, userId, cookie);
3965    }
3966
3967    /**
3968     * Update given flags when being used to request {@link ComponentInfo}.
3969     */
3970    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3971        if (cookie instanceof Intent) {
3972            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3973                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3974            }
3975        }
3976
3977        boolean triaged = true;
3978        // Caller is asking for component details, so they'd better be
3979        // asking for specific encryption matching behavior, or be triaged
3980        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3981                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3982                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3983            triaged = false;
3984        }
3985        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3986            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3987                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3988        }
3989
3990        return updateFlags(flags, userId);
3991    }
3992
3993    /**
3994     * Update given intent when being used to request {@link ResolveInfo}.
3995     */
3996    private Intent updateIntentForResolve(Intent intent) {
3997        if (intent.getSelector() != null) {
3998            intent = intent.getSelector();
3999        }
4000        if (DEBUG_PREFERRED) {
4001            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4002        }
4003        return intent;
4004    }
4005
4006    /**
4007     * Update given flags when being used to request {@link ResolveInfo}.
4008     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4009     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4010     * flag set. However, this flag is only honoured in three circumstances:
4011     * <ul>
4012     * <li>when called from a system process</li>
4013     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4014     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4015     * action and a {@code android.intent.category.BROWSABLE} category</li>
4016     * </ul>
4017     */
4018    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4019        // Safe mode means we shouldn't match any third-party components
4020        if (mSafeMode) {
4021            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4022        }
4023        final int callingUid = Binder.getCallingUid();
4024        if (getInstantAppPackageName(callingUid) != null) {
4025            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4026            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4027            flags |= PackageManager.MATCH_INSTANT;
4028        } else {
4029            // Otherwise, prevent leaking ephemeral components
4030            final boolean isSpecialProcess =
4031                    callingUid == Process.SYSTEM_UID
4032                    || callingUid == Process.SHELL_UID
4033                    || callingUid == 0;
4034            final boolean allowMatchInstant =
4035                    (includeInstantApp
4036                            && Intent.ACTION_VIEW.equals(intent.getAction())
4037                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4038                            && hasWebURI(intent))
4039                    || isSpecialProcess
4040                    || mContext.checkCallingOrSelfPermission(
4041                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4042            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4043            if (!allowMatchInstant) {
4044                flags &= ~PackageManager.MATCH_INSTANT;
4045            }
4046        }
4047        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4048    }
4049
4050    @Override
4051    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4052        if (!sUserManager.exists(userId)) return null;
4053        flags = updateFlagsForComponent(flags, userId, component);
4054        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4055                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4056        synchronized (mPackages) {
4057            PackageParser.Activity a = mActivities.mActivities.get(component);
4058
4059            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4060            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4061                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4062                if (ps == null) return null;
4063                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4064                        userId);
4065            }
4066            if (mResolveComponentName.equals(component)) {
4067                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4068                        new PackageUserState(), userId);
4069            }
4070        }
4071        return null;
4072    }
4073
4074    @Override
4075    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4076            String resolvedType) {
4077        synchronized (mPackages) {
4078            if (component.equals(mResolveComponentName)) {
4079                // The resolver supports EVERYTHING!
4080                return true;
4081            }
4082            PackageParser.Activity a = mActivities.mActivities.get(component);
4083            if (a == null) {
4084                return false;
4085            }
4086            for (int i=0; i<a.intents.size(); i++) {
4087                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4088                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4089                    return true;
4090                }
4091            }
4092            return false;
4093        }
4094    }
4095
4096    @Override
4097    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4098        if (!sUserManager.exists(userId)) return null;
4099        flags = updateFlagsForComponent(flags, userId, component);
4100        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4101                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4102        synchronized (mPackages) {
4103            PackageParser.Activity a = mReceivers.mActivities.get(component);
4104            if (DEBUG_PACKAGE_INFO) Log.v(
4105                TAG, "getReceiverInfo " + component + ": " + a);
4106            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4107                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4108                if (ps == null) return null;
4109                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4110                        ps.readUserState(userId), userId);
4111                if (ri != null) {
4112                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4113                }
4114                return ri;
4115            }
4116        }
4117        return null;
4118    }
4119
4120    @Override
4121    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4122        if (!sUserManager.exists(userId)) return null;
4123        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4124
4125        flags = updateFlagsForPackage(flags, userId, null);
4126
4127        final boolean canSeeStaticLibraries =
4128                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4129                        == PERMISSION_GRANTED
4130                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4131                        == PERMISSION_GRANTED
4132                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4133                        == PERMISSION_GRANTED
4134                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4135                        == PERMISSION_GRANTED;
4136
4137        synchronized (mPackages) {
4138            List<SharedLibraryInfo> result = null;
4139
4140            final int libCount = mSharedLibraries.size();
4141            for (int i = 0; i < libCount; i++) {
4142                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4143                if (versionedLib == null) {
4144                    continue;
4145                }
4146
4147                final int versionCount = versionedLib.size();
4148                for (int j = 0; j < versionCount; j++) {
4149                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4150                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4151                        break;
4152                    }
4153                    final long identity = Binder.clearCallingIdentity();
4154                    try {
4155                        // TODO: We will change version code to long, so in the new API it is long
4156                        PackageInfo packageInfo = getPackageInfoVersioned(
4157                                libInfo.getDeclaringPackage(), flags, userId);
4158                        if (packageInfo == null) {
4159                            continue;
4160                        }
4161                    } finally {
4162                        Binder.restoreCallingIdentity(identity);
4163                    }
4164
4165                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4166                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4167                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4168
4169                    if (result == null) {
4170                        result = new ArrayList<>();
4171                    }
4172                    result.add(resLibInfo);
4173                }
4174            }
4175
4176            return result != null ? new ParceledListSlice<>(result) : null;
4177        }
4178    }
4179
4180    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4181            SharedLibraryInfo libInfo, int flags, int userId) {
4182        List<VersionedPackage> versionedPackages = null;
4183        final int packageCount = mSettings.mPackages.size();
4184        for (int i = 0; i < packageCount; i++) {
4185            PackageSetting ps = mSettings.mPackages.valueAt(i);
4186
4187            if (ps == null) {
4188                continue;
4189            }
4190
4191            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4192                continue;
4193            }
4194
4195            final String libName = libInfo.getName();
4196            if (libInfo.isStatic()) {
4197                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4198                if (libIdx < 0) {
4199                    continue;
4200                }
4201                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4202                    continue;
4203                }
4204                if (versionedPackages == null) {
4205                    versionedPackages = new ArrayList<>();
4206                }
4207                // If the dependent is a static shared lib, use the public package name
4208                String dependentPackageName = ps.name;
4209                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4210                    dependentPackageName = ps.pkg.manifestPackageName;
4211                }
4212                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4213            } else if (ps.pkg != null) {
4214                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4215                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4216                    if (versionedPackages == null) {
4217                        versionedPackages = new ArrayList<>();
4218                    }
4219                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4220                }
4221            }
4222        }
4223
4224        return versionedPackages;
4225    }
4226
4227    @Override
4228    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4229        if (!sUserManager.exists(userId)) return null;
4230        flags = updateFlagsForComponent(flags, userId, component);
4231        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4232                false /* requireFullPermission */, false /* checkShell */, "get service info");
4233        synchronized (mPackages) {
4234            PackageParser.Service s = mServices.mServices.get(component);
4235            if (DEBUG_PACKAGE_INFO) Log.v(
4236                TAG, "getServiceInfo " + component + ": " + s);
4237            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4238                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4239                if (ps == null) return null;
4240                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4241                        ps.readUserState(userId), userId);
4242                if (si != null) {
4243                    rebaseEnabledOverlays(si.applicationInfo, userId);
4244                }
4245                return si;
4246            }
4247        }
4248        return null;
4249    }
4250
4251    @Override
4252    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4253        if (!sUserManager.exists(userId)) return null;
4254        flags = updateFlagsForComponent(flags, userId, component);
4255        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4256                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4257        synchronized (mPackages) {
4258            PackageParser.Provider p = mProviders.mProviders.get(component);
4259            if (DEBUG_PACKAGE_INFO) Log.v(
4260                TAG, "getProviderInfo " + component + ": " + p);
4261            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4262                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4263                if (ps == null) return null;
4264                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4265                        ps.readUserState(userId), userId);
4266                if (pi != null) {
4267                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4268                }
4269                return pi;
4270            }
4271        }
4272        return null;
4273    }
4274
4275    @Override
4276    public String[] getSystemSharedLibraryNames() {
4277        synchronized (mPackages) {
4278            Set<String> libs = null;
4279            final int libCount = mSharedLibraries.size();
4280            for (int i = 0; i < libCount; i++) {
4281                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4282                if (versionedLib == null) {
4283                    continue;
4284                }
4285                final int versionCount = versionedLib.size();
4286                for (int j = 0; j < versionCount; j++) {
4287                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4288                    if (!libEntry.info.isStatic()) {
4289                        if (libs == null) {
4290                            libs = new ArraySet<>();
4291                        }
4292                        libs.add(libEntry.info.getName());
4293                        break;
4294                    }
4295                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4296                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4297                            UserHandle.getUserId(Binder.getCallingUid()))) {
4298                        if (libs == null) {
4299                            libs = new ArraySet<>();
4300                        }
4301                        libs.add(libEntry.info.getName());
4302                        break;
4303                    }
4304                }
4305            }
4306
4307            if (libs != null) {
4308                String[] libsArray = new String[libs.size()];
4309                libs.toArray(libsArray);
4310                return libsArray;
4311            }
4312
4313            return null;
4314        }
4315    }
4316
4317    @Override
4318    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4319        synchronized (mPackages) {
4320            return mServicesSystemSharedLibraryPackageName;
4321        }
4322    }
4323
4324    @Override
4325    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4326        synchronized (mPackages) {
4327            return mSharedSystemSharedLibraryPackageName;
4328        }
4329    }
4330
4331    private void updateSequenceNumberLP(String packageName, int[] userList) {
4332        for (int i = userList.length - 1; i >= 0; --i) {
4333            final int userId = userList[i];
4334            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4335            if (changedPackages == null) {
4336                changedPackages = new SparseArray<>();
4337                mChangedPackages.put(userId, changedPackages);
4338            }
4339            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4340            if (sequenceNumbers == null) {
4341                sequenceNumbers = new HashMap<>();
4342                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4343            }
4344            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4345            if (sequenceNumber != null) {
4346                changedPackages.remove(sequenceNumber);
4347            }
4348            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4349            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4350        }
4351        mChangedPackagesSequenceNumber++;
4352    }
4353
4354    @Override
4355    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4356        synchronized (mPackages) {
4357            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4358                return null;
4359            }
4360            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4361            if (changedPackages == null) {
4362                return null;
4363            }
4364            final List<String> packageNames =
4365                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4366            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4367                final String packageName = changedPackages.get(i);
4368                if (packageName != null) {
4369                    packageNames.add(packageName);
4370                }
4371            }
4372            return packageNames.isEmpty()
4373                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4374        }
4375    }
4376
4377    @Override
4378    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4379        ArrayList<FeatureInfo> res;
4380        synchronized (mAvailableFeatures) {
4381            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4382            res.addAll(mAvailableFeatures.values());
4383        }
4384        final FeatureInfo fi = new FeatureInfo();
4385        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4386                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4387        res.add(fi);
4388
4389        return new ParceledListSlice<>(res);
4390    }
4391
4392    @Override
4393    public boolean hasSystemFeature(String name, int version) {
4394        synchronized (mAvailableFeatures) {
4395            final FeatureInfo feat = mAvailableFeatures.get(name);
4396            if (feat == null) {
4397                return false;
4398            } else {
4399                return feat.version >= version;
4400            }
4401        }
4402    }
4403
4404    @Override
4405    public int checkPermission(String permName, String pkgName, int userId) {
4406        if (!sUserManager.exists(userId)) {
4407            return PackageManager.PERMISSION_DENIED;
4408        }
4409
4410        synchronized (mPackages) {
4411            final PackageParser.Package p = mPackages.get(pkgName);
4412            if (p != null && p.mExtras != null) {
4413                final PackageSetting ps = (PackageSetting) p.mExtras;
4414                final PermissionsState permissionsState = ps.getPermissionsState();
4415                if (permissionsState.hasPermission(permName, userId)) {
4416                    return PackageManager.PERMISSION_GRANTED;
4417                }
4418                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4419                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4420                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4421                    return PackageManager.PERMISSION_GRANTED;
4422                }
4423            }
4424        }
4425
4426        return PackageManager.PERMISSION_DENIED;
4427    }
4428
4429    @Override
4430    public int checkUidPermission(String permName, int uid) {
4431        final int userId = UserHandle.getUserId(uid);
4432
4433        if (!sUserManager.exists(userId)) {
4434            return PackageManager.PERMISSION_DENIED;
4435        }
4436
4437        synchronized (mPackages) {
4438            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4439            if (obj != null) {
4440                final SettingBase ps = (SettingBase) obj;
4441                final PermissionsState permissionsState = ps.getPermissionsState();
4442                if (permissionsState.hasPermission(permName, userId)) {
4443                    return PackageManager.PERMISSION_GRANTED;
4444                }
4445                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4446                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4447                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4448                    return PackageManager.PERMISSION_GRANTED;
4449                }
4450            } else {
4451                ArraySet<String> perms = mSystemPermissions.get(uid);
4452                if (perms != null) {
4453                    if (perms.contains(permName)) {
4454                        return PackageManager.PERMISSION_GRANTED;
4455                    }
4456                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4457                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4458                        return PackageManager.PERMISSION_GRANTED;
4459                    }
4460                }
4461            }
4462        }
4463
4464        return PackageManager.PERMISSION_DENIED;
4465    }
4466
4467    @Override
4468    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4469        if (UserHandle.getCallingUserId() != userId) {
4470            mContext.enforceCallingPermission(
4471                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4472                    "isPermissionRevokedByPolicy for user " + userId);
4473        }
4474
4475        if (checkPermission(permission, packageName, userId)
4476                == PackageManager.PERMISSION_GRANTED) {
4477            return false;
4478        }
4479
4480        final long identity = Binder.clearCallingIdentity();
4481        try {
4482            final int flags = getPermissionFlags(permission, packageName, userId);
4483            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4484        } finally {
4485            Binder.restoreCallingIdentity(identity);
4486        }
4487    }
4488
4489    @Override
4490    public String getPermissionControllerPackageName() {
4491        synchronized (mPackages) {
4492            return mRequiredInstallerPackage;
4493        }
4494    }
4495
4496    /**
4497     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4498     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4499     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4500     * @param message the message to log on security exception
4501     */
4502    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4503            boolean checkShell, String message) {
4504        if (userId < 0) {
4505            throw new IllegalArgumentException("Invalid userId " + userId);
4506        }
4507        if (checkShell) {
4508            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4509        }
4510        if (userId == UserHandle.getUserId(callingUid)) return;
4511        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4512            if (requireFullPermission) {
4513                mContext.enforceCallingOrSelfPermission(
4514                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4515            } else {
4516                try {
4517                    mContext.enforceCallingOrSelfPermission(
4518                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4519                } catch (SecurityException se) {
4520                    mContext.enforceCallingOrSelfPermission(
4521                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4522                }
4523            }
4524        }
4525    }
4526
4527    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4528        if (callingUid == Process.SHELL_UID) {
4529            if (userHandle >= 0
4530                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4531                throw new SecurityException("Shell does not have permission to access user "
4532                        + userHandle);
4533            } else if (userHandle < 0) {
4534                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4535                        + Debug.getCallers(3));
4536            }
4537        }
4538    }
4539
4540    private BasePermission findPermissionTreeLP(String permName) {
4541        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4542            if (permName.startsWith(bp.name) &&
4543                    permName.length() > bp.name.length() &&
4544                    permName.charAt(bp.name.length()) == '.') {
4545                return bp;
4546            }
4547        }
4548        return null;
4549    }
4550
4551    private BasePermission checkPermissionTreeLP(String permName) {
4552        if (permName != null) {
4553            BasePermission bp = findPermissionTreeLP(permName);
4554            if (bp != null) {
4555                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4556                    return bp;
4557                }
4558                throw new SecurityException("Calling uid "
4559                        + Binder.getCallingUid()
4560                        + " is not allowed to add to permission tree "
4561                        + bp.name + " owned by uid " + bp.uid);
4562            }
4563        }
4564        throw new SecurityException("No permission tree found for " + permName);
4565    }
4566
4567    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4568        if (s1 == null) {
4569            return s2 == null;
4570        }
4571        if (s2 == null) {
4572            return false;
4573        }
4574        if (s1.getClass() != s2.getClass()) {
4575            return false;
4576        }
4577        return s1.equals(s2);
4578    }
4579
4580    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4581        if (pi1.icon != pi2.icon) return false;
4582        if (pi1.logo != pi2.logo) return false;
4583        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4584        if (!compareStrings(pi1.name, pi2.name)) return false;
4585        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4586        // We'll take care of setting this one.
4587        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4588        // These are not currently stored in settings.
4589        //if (!compareStrings(pi1.group, pi2.group)) return false;
4590        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4591        //if (pi1.labelRes != pi2.labelRes) return false;
4592        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4593        return true;
4594    }
4595
4596    int permissionInfoFootprint(PermissionInfo info) {
4597        int size = info.name.length();
4598        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4599        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4600        return size;
4601    }
4602
4603    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4604        int size = 0;
4605        for (BasePermission perm : mSettings.mPermissions.values()) {
4606            if (perm.uid == tree.uid) {
4607                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4608            }
4609        }
4610        return size;
4611    }
4612
4613    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4614        // We calculate the max size of permissions defined by this uid and throw
4615        // if that plus the size of 'info' would exceed our stated maximum.
4616        if (tree.uid != Process.SYSTEM_UID) {
4617            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4618            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4619                throw new SecurityException("Permission tree size cap exceeded");
4620            }
4621        }
4622    }
4623
4624    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4625        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4626            throw new SecurityException("Label must be specified in permission");
4627        }
4628        BasePermission tree = checkPermissionTreeLP(info.name);
4629        BasePermission bp = mSettings.mPermissions.get(info.name);
4630        boolean added = bp == null;
4631        boolean changed = true;
4632        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4633        if (added) {
4634            enforcePermissionCapLocked(info, tree);
4635            bp = new BasePermission(info.name, tree.sourcePackage,
4636                    BasePermission.TYPE_DYNAMIC);
4637        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4638            throw new SecurityException(
4639                    "Not allowed to modify non-dynamic permission "
4640                    + info.name);
4641        } else {
4642            if (bp.protectionLevel == fixedLevel
4643                    && bp.perm.owner.equals(tree.perm.owner)
4644                    && bp.uid == tree.uid
4645                    && comparePermissionInfos(bp.perm.info, info)) {
4646                changed = false;
4647            }
4648        }
4649        bp.protectionLevel = fixedLevel;
4650        info = new PermissionInfo(info);
4651        info.protectionLevel = fixedLevel;
4652        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4653        bp.perm.info.packageName = tree.perm.info.packageName;
4654        bp.uid = tree.uid;
4655        if (added) {
4656            mSettings.mPermissions.put(info.name, bp);
4657        }
4658        if (changed) {
4659            if (!async) {
4660                mSettings.writeLPr();
4661            } else {
4662                scheduleWriteSettingsLocked();
4663            }
4664        }
4665        return added;
4666    }
4667
4668    @Override
4669    public boolean addPermission(PermissionInfo info) {
4670        synchronized (mPackages) {
4671            return addPermissionLocked(info, false);
4672        }
4673    }
4674
4675    @Override
4676    public boolean addPermissionAsync(PermissionInfo info) {
4677        synchronized (mPackages) {
4678            return addPermissionLocked(info, true);
4679        }
4680    }
4681
4682    @Override
4683    public void removePermission(String name) {
4684        synchronized (mPackages) {
4685            checkPermissionTreeLP(name);
4686            BasePermission bp = mSettings.mPermissions.get(name);
4687            if (bp != null) {
4688                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4689                    throw new SecurityException(
4690                            "Not allowed to modify non-dynamic permission "
4691                            + name);
4692                }
4693                mSettings.mPermissions.remove(name);
4694                mSettings.writeLPr();
4695            }
4696        }
4697    }
4698
4699    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4700            BasePermission bp) {
4701        int index = pkg.requestedPermissions.indexOf(bp.name);
4702        if (index == -1) {
4703            throw new SecurityException("Package " + pkg.packageName
4704                    + " has not requested permission " + bp.name);
4705        }
4706        if (!bp.isRuntime() && !bp.isDevelopment()) {
4707            throw new SecurityException("Permission " + bp.name
4708                    + " is not a changeable permission type");
4709        }
4710    }
4711
4712    @Override
4713    public void grantRuntimePermission(String packageName, String name, final int userId) {
4714        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4715    }
4716
4717    private void grantRuntimePermission(String packageName, String name, final int userId,
4718            boolean overridePolicy) {
4719        if (!sUserManager.exists(userId)) {
4720            Log.e(TAG, "No such user:" + userId);
4721            return;
4722        }
4723
4724        mContext.enforceCallingOrSelfPermission(
4725                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4726                "grantRuntimePermission");
4727
4728        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4729                true /* requireFullPermission */, true /* checkShell */,
4730                "grantRuntimePermission");
4731
4732        final int uid;
4733        final SettingBase sb;
4734
4735        synchronized (mPackages) {
4736            final PackageParser.Package pkg = mPackages.get(packageName);
4737            if (pkg == null) {
4738                throw new IllegalArgumentException("Unknown package: " + packageName);
4739            }
4740
4741            final BasePermission bp = mSettings.mPermissions.get(name);
4742            if (bp == null) {
4743                throw new IllegalArgumentException("Unknown permission: " + name);
4744            }
4745
4746            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4747
4748            // If a permission review is required for legacy apps we represent
4749            // their permissions as always granted runtime ones since we need
4750            // to keep the review required permission flag per user while an
4751            // install permission's state is shared across all users.
4752            if (mPermissionReviewRequired
4753                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4754                    && bp.isRuntime()) {
4755                return;
4756            }
4757
4758            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4759            sb = (SettingBase) pkg.mExtras;
4760            if (sb == null) {
4761                throw new IllegalArgumentException("Unknown package: " + packageName);
4762            }
4763
4764            final PermissionsState permissionsState = sb.getPermissionsState();
4765
4766            final int flags = permissionsState.getPermissionFlags(name, userId);
4767            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4768                throw new SecurityException("Cannot grant system fixed permission "
4769                        + name + " for package " + packageName);
4770            }
4771            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4772                throw new SecurityException("Cannot grant policy fixed permission "
4773                        + name + " for package " + packageName);
4774            }
4775
4776            if (bp.isDevelopment()) {
4777                // Development permissions must be handled specially, since they are not
4778                // normal runtime permissions.  For now they apply to all users.
4779                if (permissionsState.grantInstallPermission(bp) !=
4780                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4781                    scheduleWriteSettingsLocked();
4782                }
4783                return;
4784            }
4785
4786            final PackageSetting ps = mSettings.mPackages.get(packageName);
4787            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4788                throw new SecurityException("Cannot grant non-ephemeral permission"
4789                        + name + " for package " + packageName);
4790            }
4791
4792            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4793                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4794                return;
4795            }
4796
4797            final int result = permissionsState.grantRuntimePermission(bp, userId);
4798            switch (result) {
4799                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4800                    return;
4801                }
4802
4803                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4804                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4805                    mHandler.post(new Runnable() {
4806                        @Override
4807                        public void run() {
4808                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4809                        }
4810                    });
4811                }
4812                break;
4813            }
4814
4815            if (bp.isRuntime()) {
4816                logPermissionGranted(mContext, name, packageName);
4817            }
4818
4819            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4820
4821            // Not critical if that is lost - app has to request again.
4822            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4823        }
4824
4825        // Only need to do this if user is initialized. Otherwise it's a new user
4826        // and there are no processes running as the user yet and there's no need
4827        // to make an expensive call to remount processes for the changed permissions.
4828        if (READ_EXTERNAL_STORAGE.equals(name)
4829                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4830            final long token = Binder.clearCallingIdentity();
4831            try {
4832                if (sUserManager.isInitialized(userId)) {
4833                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4834                            StorageManagerInternal.class);
4835                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4836                }
4837            } finally {
4838                Binder.restoreCallingIdentity(token);
4839            }
4840        }
4841    }
4842
4843    @Override
4844    public void revokeRuntimePermission(String packageName, String name, int userId) {
4845        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4846    }
4847
4848    private void revokeRuntimePermission(String packageName, String name, int userId,
4849            boolean overridePolicy) {
4850        if (!sUserManager.exists(userId)) {
4851            Log.e(TAG, "No such user:" + userId);
4852            return;
4853        }
4854
4855        mContext.enforceCallingOrSelfPermission(
4856                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4857                "revokeRuntimePermission");
4858
4859        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4860                true /* requireFullPermission */, true /* checkShell */,
4861                "revokeRuntimePermission");
4862
4863        final int appId;
4864
4865        synchronized (mPackages) {
4866            final PackageParser.Package pkg = mPackages.get(packageName);
4867            if (pkg == null) {
4868                throw new IllegalArgumentException("Unknown package: " + packageName);
4869            }
4870
4871            final BasePermission bp = mSettings.mPermissions.get(name);
4872            if (bp == null) {
4873                throw new IllegalArgumentException("Unknown permission: " + name);
4874            }
4875
4876            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4877
4878            // If a permission review is required for legacy apps we represent
4879            // their permissions as always granted runtime ones since we need
4880            // to keep the review required permission flag per user while an
4881            // install permission's state is shared across all users.
4882            if (mPermissionReviewRequired
4883                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4884                    && bp.isRuntime()) {
4885                return;
4886            }
4887
4888            SettingBase sb = (SettingBase) pkg.mExtras;
4889            if (sb == null) {
4890                throw new IllegalArgumentException("Unknown package: " + packageName);
4891            }
4892
4893            final PermissionsState permissionsState = sb.getPermissionsState();
4894
4895            final int flags = permissionsState.getPermissionFlags(name, userId);
4896            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4897                throw new SecurityException("Cannot revoke system fixed permission "
4898                        + name + " for package " + packageName);
4899            }
4900            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4901                throw new SecurityException("Cannot revoke policy fixed permission "
4902                        + name + " for package " + packageName);
4903            }
4904
4905            if (bp.isDevelopment()) {
4906                // Development permissions must be handled specially, since they are not
4907                // normal runtime permissions.  For now they apply to all users.
4908                if (permissionsState.revokeInstallPermission(bp) !=
4909                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4910                    scheduleWriteSettingsLocked();
4911                }
4912                return;
4913            }
4914
4915            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4916                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4917                return;
4918            }
4919
4920            if (bp.isRuntime()) {
4921                logPermissionRevoked(mContext, name, packageName);
4922            }
4923
4924            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4925
4926            // Critical, after this call app should never have the permission.
4927            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4928
4929            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4930        }
4931
4932        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4933    }
4934
4935    /**
4936     * Get the first event id for the permission.
4937     *
4938     * <p>There are four events for each permission: <ul>
4939     *     <li>Request permission: first id + 0</li>
4940     *     <li>Grant permission: first id + 1</li>
4941     *     <li>Request for permission denied: first id + 2</li>
4942     *     <li>Revoke permission: first id + 3</li>
4943     * </ul></p>
4944     *
4945     * @param name name of the permission
4946     *
4947     * @return The first event id for the permission
4948     */
4949    private static int getBaseEventId(@NonNull String name) {
4950        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4951
4952        if (eventIdIndex == -1) {
4953            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4954                    || "user".equals(Build.TYPE)) {
4955                Log.i(TAG, "Unknown permission " + name);
4956
4957                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4958            } else {
4959                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4960                //
4961                // Also update
4962                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4963                // - metrics_constants.proto
4964                throw new IllegalStateException("Unknown permission " + name);
4965            }
4966        }
4967
4968        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4969    }
4970
4971    /**
4972     * Log that a permission was revoked.
4973     *
4974     * @param context Context of the caller
4975     * @param name name of the permission
4976     * @param packageName package permission if for
4977     */
4978    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4979            @NonNull String packageName) {
4980        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4981    }
4982
4983    /**
4984     * Log that a permission request was granted.
4985     *
4986     * @param context Context of the caller
4987     * @param name name of the permission
4988     * @param packageName package permission if for
4989     */
4990    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4991            @NonNull String packageName) {
4992        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4993    }
4994
4995    @Override
4996    public void resetRuntimePermissions() {
4997        mContext.enforceCallingOrSelfPermission(
4998                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4999                "revokeRuntimePermission");
5000
5001        int callingUid = Binder.getCallingUid();
5002        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5003            mContext.enforceCallingOrSelfPermission(
5004                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5005                    "resetRuntimePermissions");
5006        }
5007
5008        synchronized (mPackages) {
5009            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5010            for (int userId : UserManagerService.getInstance().getUserIds()) {
5011                final int packageCount = mPackages.size();
5012                for (int i = 0; i < packageCount; i++) {
5013                    PackageParser.Package pkg = mPackages.valueAt(i);
5014                    if (!(pkg.mExtras instanceof PackageSetting)) {
5015                        continue;
5016                    }
5017                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5018                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5019                }
5020            }
5021        }
5022    }
5023
5024    @Override
5025    public int getPermissionFlags(String name, String packageName, int userId) {
5026        if (!sUserManager.exists(userId)) {
5027            return 0;
5028        }
5029
5030        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5031
5032        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5033                true /* requireFullPermission */, false /* checkShell */,
5034                "getPermissionFlags");
5035
5036        synchronized (mPackages) {
5037            final PackageParser.Package pkg = mPackages.get(packageName);
5038            if (pkg == null) {
5039                return 0;
5040            }
5041
5042            final BasePermission bp = mSettings.mPermissions.get(name);
5043            if (bp == null) {
5044                return 0;
5045            }
5046
5047            SettingBase sb = (SettingBase) pkg.mExtras;
5048            if (sb == null) {
5049                return 0;
5050            }
5051
5052            PermissionsState permissionsState = sb.getPermissionsState();
5053            return permissionsState.getPermissionFlags(name, userId);
5054        }
5055    }
5056
5057    @Override
5058    public void updatePermissionFlags(String name, String packageName, int flagMask,
5059            int flagValues, int userId) {
5060        if (!sUserManager.exists(userId)) {
5061            return;
5062        }
5063
5064        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5065
5066        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5067                true /* requireFullPermission */, true /* checkShell */,
5068                "updatePermissionFlags");
5069
5070        // Only the system can change these flags and nothing else.
5071        if (getCallingUid() != Process.SYSTEM_UID) {
5072            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5073            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5074            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5075            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5076            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5077        }
5078
5079        synchronized (mPackages) {
5080            final PackageParser.Package pkg = mPackages.get(packageName);
5081            if (pkg == null) {
5082                throw new IllegalArgumentException("Unknown package: " + packageName);
5083            }
5084
5085            final BasePermission bp = mSettings.mPermissions.get(name);
5086            if (bp == null) {
5087                throw new IllegalArgumentException("Unknown permission: " + name);
5088            }
5089
5090            SettingBase sb = (SettingBase) pkg.mExtras;
5091            if (sb == null) {
5092                throw new IllegalArgumentException("Unknown package: " + packageName);
5093            }
5094
5095            PermissionsState permissionsState = sb.getPermissionsState();
5096
5097            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5098
5099            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5100                // Install and runtime permissions are stored in different places,
5101                // so figure out what permission changed and persist the change.
5102                if (permissionsState.getInstallPermissionState(name) != null) {
5103                    scheduleWriteSettingsLocked();
5104                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5105                        || hadState) {
5106                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5107                }
5108            }
5109        }
5110    }
5111
5112    /**
5113     * Update the permission flags for all packages and runtime permissions of a user in order
5114     * to allow device or profile owner to remove POLICY_FIXED.
5115     */
5116    @Override
5117    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5118        if (!sUserManager.exists(userId)) {
5119            return;
5120        }
5121
5122        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5123
5124        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5125                true /* requireFullPermission */, true /* checkShell */,
5126                "updatePermissionFlagsForAllApps");
5127
5128        // Only the system can change system fixed flags.
5129        if (getCallingUid() != Process.SYSTEM_UID) {
5130            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5131            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5132        }
5133
5134        synchronized (mPackages) {
5135            boolean changed = false;
5136            final int packageCount = mPackages.size();
5137            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5138                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5139                SettingBase sb = (SettingBase) pkg.mExtras;
5140                if (sb == null) {
5141                    continue;
5142                }
5143                PermissionsState permissionsState = sb.getPermissionsState();
5144                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5145                        userId, flagMask, flagValues);
5146            }
5147            if (changed) {
5148                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5149            }
5150        }
5151    }
5152
5153    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5154        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5155                != PackageManager.PERMISSION_GRANTED
5156            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5157                != PackageManager.PERMISSION_GRANTED) {
5158            throw new SecurityException(message + " requires "
5159                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5160                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5161        }
5162    }
5163
5164    @Override
5165    public boolean shouldShowRequestPermissionRationale(String permissionName,
5166            String packageName, int userId) {
5167        if (UserHandle.getCallingUserId() != userId) {
5168            mContext.enforceCallingPermission(
5169                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5170                    "canShowRequestPermissionRationale for user " + userId);
5171        }
5172
5173        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5174        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5175            return false;
5176        }
5177
5178        if (checkPermission(permissionName, packageName, userId)
5179                == PackageManager.PERMISSION_GRANTED) {
5180            return false;
5181        }
5182
5183        final int flags;
5184
5185        final long identity = Binder.clearCallingIdentity();
5186        try {
5187            flags = getPermissionFlags(permissionName,
5188                    packageName, userId);
5189        } finally {
5190            Binder.restoreCallingIdentity(identity);
5191        }
5192
5193        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5194                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5195                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5196
5197        if ((flags & fixedFlags) != 0) {
5198            return false;
5199        }
5200
5201        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5202    }
5203
5204    @Override
5205    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5206        mContext.enforceCallingOrSelfPermission(
5207                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5208                "addOnPermissionsChangeListener");
5209
5210        synchronized (mPackages) {
5211            mOnPermissionChangeListeners.addListenerLocked(listener);
5212        }
5213    }
5214
5215    @Override
5216    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5217        synchronized (mPackages) {
5218            mOnPermissionChangeListeners.removeListenerLocked(listener);
5219        }
5220    }
5221
5222    @Override
5223    public boolean isProtectedBroadcast(String actionName) {
5224        synchronized (mPackages) {
5225            if (mProtectedBroadcasts.contains(actionName)) {
5226                return true;
5227            } else if (actionName != null) {
5228                // TODO: remove these terrible hacks
5229                if (actionName.startsWith("android.net.netmon.lingerExpired")
5230                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5231                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5232                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5233                    return true;
5234                }
5235            }
5236        }
5237        return false;
5238    }
5239
5240    @Override
5241    public int checkSignatures(String pkg1, String pkg2) {
5242        synchronized (mPackages) {
5243            final PackageParser.Package p1 = mPackages.get(pkg1);
5244            final PackageParser.Package p2 = mPackages.get(pkg2);
5245            if (p1 == null || p1.mExtras == null
5246                    || p2 == null || p2.mExtras == null) {
5247                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5248            }
5249            return compareSignatures(p1.mSignatures, p2.mSignatures);
5250        }
5251    }
5252
5253    @Override
5254    public int checkUidSignatures(int uid1, int uid2) {
5255        // Map to base uids.
5256        uid1 = UserHandle.getAppId(uid1);
5257        uid2 = UserHandle.getAppId(uid2);
5258        // reader
5259        synchronized (mPackages) {
5260            Signature[] s1;
5261            Signature[] s2;
5262            Object obj = mSettings.getUserIdLPr(uid1);
5263            if (obj != null) {
5264                if (obj instanceof SharedUserSetting) {
5265                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5266                } else if (obj instanceof PackageSetting) {
5267                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5268                } else {
5269                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5270                }
5271            } else {
5272                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5273            }
5274            obj = mSettings.getUserIdLPr(uid2);
5275            if (obj != null) {
5276                if (obj instanceof SharedUserSetting) {
5277                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5278                } else if (obj instanceof PackageSetting) {
5279                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5280                } else {
5281                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5282                }
5283            } else {
5284                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5285            }
5286            return compareSignatures(s1, s2);
5287        }
5288    }
5289
5290    /**
5291     * This method should typically only be used when granting or revoking
5292     * permissions, since the app may immediately restart after this call.
5293     * <p>
5294     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5295     * guard your work against the app being relaunched.
5296     */
5297    private void killUid(int appId, int userId, String reason) {
5298        final long identity = Binder.clearCallingIdentity();
5299        try {
5300            IActivityManager am = ActivityManager.getService();
5301            if (am != null) {
5302                try {
5303                    am.killUid(appId, userId, reason);
5304                } catch (RemoteException e) {
5305                    /* ignore - same process */
5306                }
5307            }
5308        } finally {
5309            Binder.restoreCallingIdentity(identity);
5310        }
5311    }
5312
5313    /**
5314     * Compares two sets of signatures. Returns:
5315     * <br />
5316     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5317     * <br />
5318     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5319     * <br />
5320     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5321     * <br />
5322     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5323     * <br />
5324     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5325     */
5326    static int compareSignatures(Signature[] s1, Signature[] s2) {
5327        if (s1 == null) {
5328            return s2 == null
5329                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5330                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5331        }
5332
5333        if (s2 == null) {
5334            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5335        }
5336
5337        if (s1.length != s2.length) {
5338            return PackageManager.SIGNATURE_NO_MATCH;
5339        }
5340
5341        // Since both signature sets are of size 1, we can compare without HashSets.
5342        if (s1.length == 1) {
5343            return s1[0].equals(s2[0]) ?
5344                    PackageManager.SIGNATURE_MATCH :
5345                    PackageManager.SIGNATURE_NO_MATCH;
5346        }
5347
5348        ArraySet<Signature> set1 = new ArraySet<Signature>();
5349        for (Signature sig : s1) {
5350            set1.add(sig);
5351        }
5352        ArraySet<Signature> set2 = new ArraySet<Signature>();
5353        for (Signature sig : s2) {
5354            set2.add(sig);
5355        }
5356        // Make sure s2 contains all signatures in s1.
5357        if (set1.equals(set2)) {
5358            return PackageManager.SIGNATURE_MATCH;
5359        }
5360        return PackageManager.SIGNATURE_NO_MATCH;
5361    }
5362
5363    /**
5364     * If the database version for this type of package (internal storage or
5365     * external storage) is less than the version where package signatures
5366     * were updated, return true.
5367     */
5368    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5369        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5370        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5371    }
5372
5373    /**
5374     * Used for backward compatibility to make sure any packages with
5375     * certificate chains get upgraded to the new style. {@code existingSigs}
5376     * will be in the old format (since they were stored on disk from before the
5377     * system upgrade) and {@code scannedSigs} will be in the newer format.
5378     */
5379    private int compareSignaturesCompat(PackageSignatures existingSigs,
5380            PackageParser.Package scannedPkg) {
5381        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5382            return PackageManager.SIGNATURE_NO_MATCH;
5383        }
5384
5385        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5386        for (Signature sig : existingSigs.mSignatures) {
5387            existingSet.add(sig);
5388        }
5389        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5390        for (Signature sig : scannedPkg.mSignatures) {
5391            try {
5392                Signature[] chainSignatures = sig.getChainSignatures();
5393                for (Signature chainSig : chainSignatures) {
5394                    scannedCompatSet.add(chainSig);
5395                }
5396            } catch (CertificateEncodingException e) {
5397                scannedCompatSet.add(sig);
5398            }
5399        }
5400        /*
5401         * Make sure the expanded scanned set contains all signatures in the
5402         * existing one.
5403         */
5404        if (scannedCompatSet.equals(existingSet)) {
5405            // Migrate the old signatures to the new scheme.
5406            existingSigs.assignSignatures(scannedPkg.mSignatures);
5407            // The new KeySets will be re-added later in the scanning process.
5408            synchronized (mPackages) {
5409                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5410            }
5411            return PackageManager.SIGNATURE_MATCH;
5412        }
5413        return PackageManager.SIGNATURE_NO_MATCH;
5414    }
5415
5416    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5417        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5418        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5419    }
5420
5421    private int compareSignaturesRecover(PackageSignatures existingSigs,
5422            PackageParser.Package scannedPkg) {
5423        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5424            return PackageManager.SIGNATURE_NO_MATCH;
5425        }
5426
5427        String msg = null;
5428        try {
5429            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5430                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5431                        + scannedPkg.packageName);
5432                return PackageManager.SIGNATURE_MATCH;
5433            }
5434        } catch (CertificateException e) {
5435            msg = e.getMessage();
5436        }
5437
5438        logCriticalInfo(Log.INFO,
5439                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5440        return PackageManager.SIGNATURE_NO_MATCH;
5441    }
5442
5443    @Override
5444    public List<String> getAllPackages() {
5445        synchronized (mPackages) {
5446            return new ArrayList<String>(mPackages.keySet());
5447        }
5448    }
5449
5450    @Override
5451    public String[] getPackagesForUid(int uid) {
5452        final int userId = UserHandle.getUserId(uid);
5453        uid = UserHandle.getAppId(uid);
5454        // reader
5455        synchronized (mPackages) {
5456            Object obj = mSettings.getUserIdLPr(uid);
5457            if (obj instanceof SharedUserSetting) {
5458                final SharedUserSetting sus = (SharedUserSetting) obj;
5459                final int N = sus.packages.size();
5460                String[] res = new String[N];
5461                final Iterator<PackageSetting> it = sus.packages.iterator();
5462                int i = 0;
5463                while (it.hasNext()) {
5464                    PackageSetting ps = it.next();
5465                    if (ps.getInstalled(userId)) {
5466                        res[i++] = ps.name;
5467                    } else {
5468                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5469                    }
5470                }
5471                return res;
5472            } else if (obj instanceof PackageSetting) {
5473                final PackageSetting ps = (PackageSetting) obj;
5474                if (ps.getInstalled(userId)) {
5475                    return new String[]{ps.name};
5476                }
5477            }
5478        }
5479        return null;
5480    }
5481
5482    @Override
5483    public String getNameForUid(int uid) {
5484        // reader
5485        synchronized (mPackages) {
5486            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5487            if (obj instanceof SharedUserSetting) {
5488                final SharedUserSetting sus = (SharedUserSetting) obj;
5489                return sus.name + ":" + sus.userId;
5490            } else if (obj instanceof PackageSetting) {
5491                final PackageSetting ps = (PackageSetting) obj;
5492                return ps.name;
5493            }
5494        }
5495        return null;
5496    }
5497
5498    @Override
5499    public int getUidForSharedUser(String sharedUserName) {
5500        if(sharedUserName == null) {
5501            return -1;
5502        }
5503        // reader
5504        synchronized (mPackages) {
5505            SharedUserSetting suid;
5506            try {
5507                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5508                if (suid != null) {
5509                    return suid.userId;
5510                }
5511            } catch (PackageManagerException ignore) {
5512                // can't happen, but, still need to catch it
5513            }
5514            return -1;
5515        }
5516    }
5517
5518    @Override
5519    public int getFlagsForUid(int uid) {
5520        synchronized (mPackages) {
5521            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5522            if (obj instanceof SharedUserSetting) {
5523                final SharedUserSetting sus = (SharedUserSetting) obj;
5524                return sus.pkgFlags;
5525            } else if (obj instanceof PackageSetting) {
5526                final PackageSetting ps = (PackageSetting) obj;
5527                return ps.pkgFlags;
5528            }
5529        }
5530        return 0;
5531    }
5532
5533    @Override
5534    public int getPrivateFlagsForUid(int uid) {
5535        synchronized (mPackages) {
5536            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5537            if (obj instanceof SharedUserSetting) {
5538                final SharedUserSetting sus = (SharedUserSetting) obj;
5539                return sus.pkgPrivateFlags;
5540            } else if (obj instanceof PackageSetting) {
5541                final PackageSetting ps = (PackageSetting) obj;
5542                return ps.pkgPrivateFlags;
5543            }
5544        }
5545        return 0;
5546    }
5547
5548    @Override
5549    public boolean isUidPrivileged(int uid) {
5550        uid = UserHandle.getAppId(uid);
5551        // reader
5552        synchronized (mPackages) {
5553            Object obj = mSettings.getUserIdLPr(uid);
5554            if (obj instanceof SharedUserSetting) {
5555                final SharedUserSetting sus = (SharedUserSetting) obj;
5556                final Iterator<PackageSetting> it = sus.packages.iterator();
5557                while (it.hasNext()) {
5558                    if (it.next().isPrivileged()) {
5559                        return true;
5560                    }
5561                }
5562            } else if (obj instanceof PackageSetting) {
5563                final PackageSetting ps = (PackageSetting) obj;
5564                return ps.isPrivileged();
5565            }
5566        }
5567        return false;
5568    }
5569
5570    @Override
5571    public String[] getAppOpPermissionPackages(String permissionName) {
5572        synchronized (mPackages) {
5573            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5574            if (pkgs == null) {
5575                return null;
5576            }
5577            return pkgs.toArray(new String[pkgs.size()]);
5578        }
5579    }
5580
5581    @Override
5582    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5583            int flags, int userId) {
5584        return resolveIntentInternal(
5585                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5586    }
5587
5588    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5589            int flags, int userId, boolean includeInstantApp) {
5590        try {
5591            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5592
5593            if (!sUserManager.exists(userId)) return null;
5594            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5595            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5596                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5597
5598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5599            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5600                    flags, userId, includeInstantApp);
5601            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5602
5603            final ResolveInfo bestChoice =
5604                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5605            return bestChoice;
5606        } finally {
5607            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5608        }
5609    }
5610
5611    @Override
5612    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5613        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5614            throw new SecurityException(
5615                    "findPersistentPreferredActivity can only be run by the system");
5616        }
5617        if (!sUserManager.exists(userId)) {
5618            return null;
5619        }
5620        intent = updateIntentForResolve(intent);
5621        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5622        final int flags = updateFlagsForResolve(0, userId, intent, false);
5623        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5624                userId);
5625        synchronized (mPackages) {
5626            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5627                    userId);
5628        }
5629    }
5630
5631    @Override
5632    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5633            IntentFilter filter, int match, ComponentName activity) {
5634        final int userId = UserHandle.getCallingUserId();
5635        if (DEBUG_PREFERRED) {
5636            Log.v(TAG, "setLastChosenActivity intent=" + intent
5637                + " resolvedType=" + resolvedType
5638                + " flags=" + flags
5639                + " filter=" + filter
5640                + " match=" + match
5641                + " activity=" + activity);
5642            filter.dump(new PrintStreamPrinter(System.out), "    ");
5643        }
5644        intent.setComponent(null);
5645        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5646                userId);
5647        // Find any earlier preferred or last chosen entries and nuke them
5648        findPreferredActivity(intent, resolvedType,
5649                flags, query, 0, false, true, false, userId);
5650        // Add the new activity as the last chosen for this filter
5651        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5652                "Setting last chosen");
5653    }
5654
5655    @Override
5656    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5657        final int userId = UserHandle.getCallingUserId();
5658        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5659        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5660                userId);
5661        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5662                false, false, false, userId);
5663    }
5664
5665    /**
5666     * Returns whether or not instant apps have been disabled remotely.
5667     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5668     * held. Otherwise we run the risk of deadlock.
5669     */
5670    private boolean isEphemeralDisabled() {
5671        // ephemeral apps have been disabled across the board
5672        if (DISABLE_EPHEMERAL_APPS) {
5673            return true;
5674        }
5675        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5676        if (!mSystemReady) {
5677            return true;
5678        }
5679        // we can't get a content resolver until the system is ready; these checks must happen last
5680        final ContentResolver resolver = mContext.getContentResolver();
5681        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5682            return true;
5683        }
5684        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5685    }
5686
5687    private boolean isEphemeralAllowed(
5688            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5689            boolean skipPackageCheck) {
5690        final int callingUser = UserHandle.getCallingUserId();
5691        if (callingUser != UserHandle.USER_SYSTEM) {
5692            return false;
5693        }
5694        if (mInstantAppResolverConnection == null) {
5695            return false;
5696        }
5697        if (mInstantAppInstallerComponent == null) {
5698            return false;
5699        }
5700        if (intent.getComponent() != null) {
5701            return false;
5702        }
5703        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5704            return false;
5705        }
5706        if (!skipPackageCheck && intent.getPackage() != null) {
5707            return false;
5708        }
5709        final boolean isWebUri = hasWebURI(intent);
5710        if (!isWebUri || intent.getData().getHost() == null) {
5711            return false;
5712        }
5713        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5714        // Or if there's already an ephemeral app installed that handles the action
5715        synchronized (mPackages) {
5716            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5717            for (int n = 0; n < count; n++) {
5718                ResolveInfo info = resolvedActivities.get(n);
5719                String packageName = info.activityInfo.packageName;
5720                PackageSetting ps = mSettings.mPackages.get(packageName);
5721                if (ps != null) {
5722                    // Try to get the status from User settings first
5723                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5724                    int status = (int) (packedStatus >> 32);
5725                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5726                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5727                        if (DEBUG_EPHEMERAL) {
5728                            Slog.v(TAG, "DENY ephemeral apps;"
5729                                + " pkg: " + packageName + ", status: " + status);
5730                        }
5731                        return false;
5732                    }
5733                    if (ps.getInstantApp(userId)) {
5734                        if (DEBUG_EPHEMERAL) {
5735                            Slog.v(TAG, "DENY instant app installed;"
5736                                    + " pkg: " + packageName);
5737                        }
5738                        return false;
5739                    }
5740                }
5741            }
5742        }
5743        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5744        return true;
5745    }
5746
5747    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5748            Intent origIntent, String resolvedType, String callingPackage,
5749            int userId) {
5750        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5751                new InstantAppRequest(responseObj, origIntent, resolvedType,
5752                        callingPackage, userId));
5753        mHandler.sendMessage(msg);
5754    }
5755
5756    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5757            int flags, List<ResolveInfo> query, int userId) {
5758        if (query != null) {
5759            final int N = query.size();
5760            if (N == 1) {
5761                return query.get(0);
5762            } else if (N > 1) {
5763                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5764                // If there is more than one activity with the same priority,
5765                // then let the user decide between them.
5766                ResolveInfo r0 = query.get(0);
5767                ResolveInfo r1 = query.get(1);
5768                if (DEBUG_INTENT_MATCHING || debug) {
5769                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5770                            + r1.activityInfo.name + "=" + r1.priority);
5771                }
5772                // If the first activity has a higher priority, or a different
5773                // default, then it is always desirable to pick it.
5774                if (r0.priority != r1.priority
5775                        || r0.preferredOrder != r1.preferredOrder
5776                        || r0.isDefault != r1.isDefault) {
5777                    return query.get(0);
5778                }
5779                // If we have saved a preference for a preferred activity for
5780                // this Intent, use that.
5781                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5782                        flags, query, r0.priority, true, false, debug, userId);
5783                if (ri != null) {
5784                    return ri;
5785                }
5786                // If we have an ephemeral app, use it
5787                for (int i = 0; i < N; i++) {
5788                    ri = query.get(i);
5789                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5790                        return ri;
5791                    }
5792                }
5793                ri = new ResolveInfo(mResolveInfo);
5794                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5795                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5796                // If all of the options come from the same package, show the application's
5797                // label and icon instead of the generic resolver's.
5798                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5799                // and then throw away the ResolveInfo itself, meaning that the caller loses
5800                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5801                // a fallback for this case; we only set the target package's resources on
5802                // the ResolveInfo, not the ActivityInfo.
5803                final String intentPackage = intent.getPackage();
5804                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5805                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5806                    ri.resolvePackageName = intentPackage;
5807                    if (userNeedsBadging(userId)) {
5808                        ri.noResourceId = true;
5809                    } else {
5810                        ri.icon = appi.icon;
5811                    }
5812                    ri.iconResourceId = appi.icon;
5813                    ri.labelRes = appi.labelRes;
5814                }
5815                ri.activityInfo.applicationInfo = new ApplicationInfo(
5816                        ri.activityInfo.applicationInfo);
5817                if (userId != 0) {
5818                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5819                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5820                }
5821                // Make sure that the resolver is displayable in car mode
5822                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5823                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5824                return ri;
5825            }
5826        }
5827        return null;
5828    }
5829
5830    /**
5831     * Return true if the given list is not empty and all of its contents have
5832     * an activityInfo with the given package name.
5833     */
5834    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5835        if (ArrayUtils.isEmpty(list)) {
5836            return false;
5837        }
5838        for (int i = 0, N = list.size(); i < N; i++) {
5839            final ResolveInfo ri = list.get(i);
5840            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5841            if (ai == null || !packageName.equals(ai.packageName)) {
5842                return false;
5843            }
5844        }
5845        return true;
5846    }
5847
5848    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5849            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5850        final int N = query.size();
5851        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5852                .get(userId);
5853        // Get the list of persistent preferred activities that handle the intent
5854        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5855        List<PersistentPreferredActivity> pprefs = ppir != null
5856                ? ppir.queryIntent(intent, resolvedType,
5857                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5858                        userId)
5859                : null;
5860        if (pprefs != null && pprefs.size() > 0) {
5861            final int M = pprefs.size();
5862            for (int i=0; i<M; i++) {
5863                final PersistentPreferredActivity ppa = pprefs.get(i);
5864                if (DEBUG_PREFERRED || debug) {
5865                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5866                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5867                            + "\n  component=" + ppa.mComponent);
5868                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5869                }
5870                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5871                        flags | MATCH_DISABLED_COMPONENTS, userId);
5872                if (DEBUG_PREFERRED || debug) {
5873                    Slog.v(TAG, "Found persistent preferred activity:");
5874                    if (ai != null) {
5875                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5876                    } else {
5877                        Slog.v(TAG, "  null");
5878                    }
5879                }
5880                if (ai == null) {
5881                    // This previously registered persistent preferred activity
5882                    // component is no longer known. Ignore it and do NOT remove it.
5883                    continue;
5884                }
5885                for (int j=0; j<N; j++) {
5886                    final ResolveInfo ri = query.get(j);
5887                    if (!ri.activityInfo.applicationInfo.packageName
5888                            .equals(ai.applicationInfo.packageName)) {
5889                        continue;
5890                    }
5891                    if (!ri.activityInfo.name.equals(ai.name)) {
5892                        continue;
5893                    }
5894                    //  Found a persistent preference that can handle the intent.
5895                    if (DEBUG_PREFERRED || debug) {
5896                        Slog.v(TAG, "Returning persistent preferred activity: " +
5897                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5898                    }
5899                    return ri;
5900                }
5901            }
5902        }
5903        return null;
5904    }
5905
5906    // TODO: handle preferred activities missing while user has amnesia
5907    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5908            List<ResolveInfo> query, int priority, boolean always,
5909            boolean removeMatches, boolean debug, int userId) {
5910        if (!sUserManager.exists(userId)) return null;
5911        flags = updateFlagsForResolve(flags, userId, intent, false);
5912        intent = updateIntentForResolve(intent);
5913        // writer
5914        synchronized (mPackages) {
5915            // Try to find a matching persistent preferred activity.
5916            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5917                    debug, userId);
5918
5919            // If a persistent preferred activity matched, use it.
5920            if (pri != null) {
5921                return pri;
5922            }
5923
5924            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5925            // Get the list of preferred activities that handle the intent
5926            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5927            List<PreferredActivity> prefs = pir != null
5928                    ? pir.queryIntent(intent, resolvedType,
5929                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5930                            userId)
5931                    : null;
5932            if (prefs != null && prefs.size() > 0) {
5933                boolean changed = false;
5934                try {
5935                    // First figure out how good the original match set is.
5936                    // We will only allow preferred activities that came
5937                    // from the same match quality.
5938                    int match = 0;
5939
5940                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5941
5942                    final int N = query.size();
5943                    for (int j=0; j<N; j++) {
5944                        final ResolveInfo ri = query.get(j);
5945                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5946                                + ": 0x" + Integer.toHexString(match));
5947                        if (ri.match > match) {
5948                            match = ri.match;
5949                        }
5950                    }
5951
5952                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5953                            + Integer.toHexString(match));
5954
5955                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5956                    final int M = prefs.size();
5957                    for (int i=0; i<M; i++) {
5958                        final PreferredActivity pa = prefs.get(i);
5959                        if (DEBUG_PREFERRED || debug) {
5960                            Slog.v(TAG, "Checking PreferredActivity ds="
5961                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5962                                    + "\n  component=" + pa.mPref.mComponent);
5963                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5964                        }
5965                        if (pa.mPref.mMatch != match) {
5966                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5967                                    + Integer.toHexString(pa.mPref.mMatch));
5968                            continue;
5969                        }
5970                        // If it's not an "always" type preferred activity and that's what we're
5971                        // looking for, skip it.
5972                        if (always && !pa.mPref.mAlways) {
5973                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5974                            continue;
5975                        }
5976                        final ActivityInfo ai = getActivityInfo(
5977                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5978                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5979                                userId);
5980                        if (DEBUG_PREFERRED || debug) {
5981                            Slog.v(TAG, "Found preferred activity:");
5982                            if (ai != null) {
5983                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5984                            } else {
5985                                Slog.v(TAG, "  null");
5986                            }
5987                        }
5988                        if (ai == null) {
5989                            // This previously registered preferred activity
5990                            // component is no longer known.  Most likely an update
5991                            // to the app was installed and in the new version this
5992                            // component no longer exists.  Clean it up by removing
5993                            // it from the preferred activities list, and skip it.
5994                            Slog.w(TAG, "Removing dangling preferred activity: "
5995                                    + pa.mPref.mComponent);
5996                            pir.removeFilter(pa);
5997                            changed = true;
5998                            continue;
5999                        }
6000                        for (int j=0; j<N; j++) {
6001                            final ResolveInfo ri = query.get(j);
6002                            if (!ri.activityInfo.applicationInfo.packageName
6003                                    .equals(ai.applicationInfo.packageName)) {
6004                                continue;
6005                            }
6006                            if (!ri.activityInfo.name.equals(ai.name)) {
6007                                continue;
6008                            }
6009
6010                            if (removeMatches) {
6011                                pir.removeFilter(pa);
6012                                changed = true;
6013                                if (DEBUG_PREFERRED) {
6014                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6015                                }
6016                                break;
6017                            }
6018
6019                            // Okay we found a previously set preferred or last chosen app.
6020                            // If the result set is different from when this
6021                            // was created, we need to clear it and re-ask the
6022                            // user their preference, if we're looking for an "always" type entry.
6023                            if (always && !pa.mPref.sameSet(query)) {
6024                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6025                                        + intent + " type " + resolvedType);
6026                                if (DEBUG_PREFERRED) {
6027                                    Slog.v(TAG, "Removing preferred activity since set changed "
6028                                            + pa.mPref.mComponent);
6029                                }
6030                                pir.removeFilter(pa);
6031                                // Re-add the filter as a "last chosen" entry (!always)
6032                                PreferredActivity lastChosen = new PreferredActivity(
6033                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6034                                pir.addFilter(lastChosen);
6035                                changed = true;
6036                                return null;
6037                            }
6038
6039                            // Yay! Either the set matched or we're looking for the last chosen
6040                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6041                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6042                            return ri;
6043                        }
6044                    }
6045                } finally {
6046                    if (changed) {
6047                        if (DEBUG_PREFERRED) {
6048                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6049                        }
6050                        scheduleWritePackageRestrictionsLocked(userId);
6051                    }
6052                }
6053            }
6054        }
6055        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6056        return null;
6057    }
6058
6059    /*
6060     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6061     */
6062    @Override
6063    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6064            int targetUserId) {
6065        mContext.enforceCallingOrSelfPermission(
6066                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6067        List<CrossProfileIntentFilter> matches =
6068                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6069        if (matches != null) {
6070            int size = matches.size();
6071            for (int i = 0; i < size; i++) {
6072                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6073            }
6074        }
6075        if (hasWebURI(intent)) {
6076            // cross-profile app linking works only towards the parent.
6077            final UserInfo parent = getProfileParent(sourceUserId);
6078            synchronized(mPackages) {
6079                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6080                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6081                        intent, resolvedType, flags, sourceUserId, parent.id);
6082                return xpDomainInfo != null;
6083            }
6084        }
6085        return false;
6086    }
6087
6088    private UserInfo getProfileParent(int userId) {
6089        final long identity = Binder.clearCallingIdentity();
6090        try {
6091            return sUserManager.getProfileParent(userId);
6092        } finally {
6093            Binder.restoreCallingIdentity(identity);
6094        }
6095    }
6096
6097    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6098            String resolvedType, int userId) {
6099        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6100        if (resolver != null) {
6101            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6102        }
6103        return null;
6104    }
6105
6106    @Override
6107    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6108            String resolvedType, int flags, int userId) {
6109        try {
6110            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6111
6112            return new ParceledListSlice<>(
6113                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6114        } finally {
6115            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6116        }
6117    }
6118
6119    /**
6120     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6121     * instant, returns {@code null}.
6122     */
6123    private String getInstantAppPackageName(int callingUid) {
6124        final int appId = UserHandle.getAppId(callingUid);
6125        synchronized (mPackages) {
6126            final Object obj = mSettings.getUserIdLPr(appId);
6127            if (obj instanceof PackageSetting) {
6128                final PackageSetting ps = (PackageSetting) obj;
6129                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6130                return isInstantApp ? ps.pkg.packageName : null;
6131            }
6132        }
6133        return null;
6134    }
6135
6136    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6137            String resolvedType, int flags, int userId) {
6138        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6139    }
6140
6141    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6142            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6143        if (!sUserManager.exists(userId)) return Collections.emptyList();
6144        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6145        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6146        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6147                false /* requireFullPermission */, false /* checkShell */,
6148                "query intent activities");
6149        ComponentName comp = intent.getComponent();
6150        if (comp == null) {
6151            if (intent.getSelector() != null) {
6152                intent = intent.getSelector();
6153                comp = intent.getComponent();
6154            }
6155        }
6156
6157        if (comp != null) {
6158            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6159            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6160            if (ai != null) {
6161                // When specifying an explicit component, we prevent the activity from being
6162                // used when either 1) the calling package is normal and the activity is within
6163                // an ephemeral application or 2) the calling package is ephemeral and the
6164                // activity is not visible to ephemeral applications.
6165                final boolean matchInstantApp =
6166                        (flags & PackageManager.MATCH_INSTANT) != 0;
6167                final boolean matchVisibleToInstantAppOnly =
6168                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6169                final boolean isCallerInstantApp =
6170                        instantAppPkgName != null;
6171                final boolean isTargetSameInstantApp =
6172                        comp.getPackageName().equals(instantAppPkgName);
6173                final boolean isTargetInstantApp =
6174                        (ai.applicationInfo.privateFlags
6175                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6176                final boolean isTargetHiddenFromInstantApp =
6177                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6178                final boolean blockResolution =
6179                        !isTargetSameInstantApp
6180                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6181                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6182                                        && isTargetHiddenFromInstantApp));
6183                if (!blockResolution) {
6184                    final ResolveInfo ri = new ResolveInfo();
6185                    ri.activityInfo = ai;
6186                    list.add(ri);
6187                }
6188            }
6189            return applyPostResolutionFilter(list, instantAppPkgName);
6190        }
6191
6192        // reader
6193        boolean sortResult = false;
6194        boolean addEphemeral = false;
6195        List<ResolveInfo> result;
6196        final String pkgName = intent.getPackage();
6197        final boolean ephemeralDisabled = isEphemeralDisabled();
6198        synchronized (mPackages) {
6199            if (pkgName == null) {
6200                List<CrossProfileIntentFilter> matchingFilters =
6201                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6202                // Check for results that need to skip the current profile.
6203                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6204                        resolvedType, flags, userId);
6205                if (xpResolveInfo != null) {
6206                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6207                    xpResult.add(xpResolveInfo);
6208                    return applyPostResolutionFilter(
6209                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6210                }
6211
6212                // Check for results in the current profile.
6213                result = filterIfNotSystemUser(mActivities.queryIntent(
6214                        intent, resolvedType, flags, userId), userId);
6215                addEphemeral = !ephemeralDisabled
6216                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6217                // Check for cross profile results.
6218                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6219                xpResolveInfo = queryCrossProfileIntents(
6220                        matchingFilters, intent, resolvedType, flags, userId,
6221                        hasNonNegativePriorityResult);
6222                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6223                    boolean isVisibleToUser = filterIfNotSystemUser(
6224                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6225                    if (isVisibleToUser) {
6226                        result.add(xpResolveInfo);
6227                        sortResult = true;
6228                    }
6229                }
6230                if (hasWebURI(intent)) {
6231                    CrossProfileDomainInfo xpDomainInfo = null;
6232                    final UserInfo parent = getProfileParent(userId);
6233                    if (parent != null) {
6234                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6235                                flags, userId, parent.id);
6236                    }
6237                    if (xpDomainInfo != null) {
6238                        if (xpResolveInfo != null) {
6239                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6240                            // in the result.
6241                            result.remove(xpResolveInfo);
6242                        }
6243                        if (result.size() == 0 && !addEphemeral) {
6244                            // No result in current profile, but found candidate in parent user.
6245                            // And we are not going to add emphemeral app, so we can return the
6246                            // result straight away.
6247                            result.add(xpDomainInfo.resolveInfo);
6248                            return applyPostResolutionFilter(result, instantAppPkgName);
6249                        }
6250                    } else if (result.size() <= 1 && !addEphemeral) {
6251                        // No result in parent user and <= 1 result in current profile, and we
6252                        // are not going to add emphemeral app, so we can return the result without
6253                        // further processing.
6254                        return applyPostResolutionFilter(result, instantAppPkgName);
6255                    }
6256                    // We have more than one candidate (combining results from current and parent
6257                    // profile), so we need filtering and sorting.
6258                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6259                            intent, flags, result, xpDomainInfo, userId);
6260                    sortResult = true;
6261                }
6262            } else {
6263                final PackageParser.Package pkg = mPackages.get(pkgName);
6264                if (pkg != null) {
6265                    return applyPostResolutionFilter(filterIfNotSystemUser(
6266                            mActivities.queryIntentForPackage(
6267                                    intent, resolvedType, flags, pkg.activities, userId),
6268                            userId), instantAppPkgName);
6269                } else {
6270                    // the caller wants to resolve for a particular package; however, there
6271                    // were no installed results, so, try to find an ephemeral result
6272                    addEphemeral = !ephemeralDisabled
6273                            && isEphemeralAllowed(
6274                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6275                    result = new ArrayList<ResolveInfo>();
6276                }
6277            }
6278        }
6279        if (addEphemeral) {
6280            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6281            final InstantAppRequest requestObject = new InstantAppRequest(
6282                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6283                    null /*callingPackage*/, userId);
6284            final AuxiliaryResolveInfo auxiliaryResponse =
6285                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6286                            mContext, mInstantAppResolverConnection, requestObject);
6287            if (auxiliaryResponse != null) {
6288                if (DEBUG_EPHEMERAL) {
6289                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6290                }
6291                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6292                ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity);
6293                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6294                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6295                // make sure this resolver is the default
6296                ephemeralInstaller.isDefault = true;
6297                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6298                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6299                // add a non-generic filter
6300                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6301                ephemeralInstaller.filter.addDataPath(
6302                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6303                ephemeralInstaller.instantAppAvailable = true;
6304                result.add(ephemeralInstaller);
6305            }
6306            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6307        }
6308        if (sortResult) {
6309            Collections.sort(result, mResolvePrioritySorter);
6310        }
6311        return applyPostResolutionFilter(result, instantAppPkgName);
6312    }
6313
6314    private static class CrossProfileDomainInfo {
6315        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6316        ResolveInfo resolveInfo;
6317        /* Best domain verification status of the activities found in the other profile */
6318        int bestDomainVerificationStatus;
6319    }
6320
6321    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6322            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6323        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6324                sourceUserId)) {
6325            return null;
6326        }
6327        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6328                resolvedType, flags, parentUserId);
6329
6330        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6331            return null;
6332        }
6333        CrossProfileDomainInfo result = null;
6334        int size = resultTargetUser.size();
6335        for (int i = 0; i < size; i++) {
6336            ResolveInfo riTargetUser = resultTargetUser.get(i);
6337            // Intent filter verification is only for filters that specify a host. So don't return
6338            // those that handle all web uris.
6339            if (riTargetUser.handleAllWebDataURI) {
6340                continue;
6341            }
6342            String packageName = riTargetUser.activityInfo.packageName;
6343            PackageSetting ps = mSettings.mPackages.get(packageName);
6344            if (ps == null) {
6345                continue;
6346            }
6347            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6348            int status = (int)(verificationState >> 32);
6349            if (result == null) {
6350                result = new CrossProfileDomainInfo();
6351                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6352                        sourceUserId, parentUserId);
6353                result.bestDomainVerificationStatus = status;
6354            } else {
6355                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6356                        result.bestDomainVerificationStatus);
6357            }
6358        }
6359        // Don't consider matches with status NEVER across profiles.
6360        if (result != null && result.bestDomainVerificationStatus
6361                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6362            return null;
6363        }
6364        return result;
6365    }
6366
6367    /**
6368     * Verification statuses are ordered from the worse to the best, except for
6369     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6370     */
6371    private int bestDomainVerificationStatus(int status1, int status2) {
6372        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6373            return status2;
6374        }
6375        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6376            return status1;
6377        }
6378        return (int) MathUtils.max(status1, status2);
6379    }
6380
6381    private boolean isUserEnabled(int userId) {
6382        long callingId = Binder.clearCallingIdentity();
6383        try {
6384            UserInfo userInfo = sUserManager.getUserInfo(userId);
6385            return userInfo != null && userInfo.isEnabled();
6386        } finally {
6387            Binder.restoreCallingIdentity(callingId);
6388        }
6389    }
6390
6391    /**
6392     * Filter out activities with systemUserOnly flag set, when current user is not System.
6393     *
6394     * @return filtered list
6395     */
6396    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6397        if (userId == UserHandle.USER_SYSTEM) {
6398            return resolveInfos;
6399        }
6400        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6401            ResolveInfo info = resolveInfos.get(i);
6402            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6403                resolveInfos.remove(i);
6404            }
6405        }
6406        return resolveInfos;
6407    }
6408
6409    /**
6410     * Filters out ephemeral activities.
6411     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6412     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6413     *
6414     * @param resolveInfos The pre-filtered list of resolved activities
6415     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6416     *          is performed.
6417     * @return A filtered list of resolved activities.
6418     */
6419    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6420            String ephemeralPkgName) {
6421        // TODO: When adding on-demand split support for non-instant apps, remove this check
6422        // and always apply post filtering
6423        if (ephemeralPkgName == null) {
6424            return resolveInfos;
6425        }
6426        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6427            final ResolveInfo info = resolveInfos.get(i);
6428            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6429            // allow activities that are defined in the provided package
6430            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6431                if (info.activityInfo.splitName != null
6432                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6433                                info.activityInfo.splitName)) {
6434                    // requested activity is defined in a split that hasn't been installed yet.
6435                    // add the installer to the resolve list
6436                    if (DEBUG_EPHEMERAL) {
6437                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6438                    }
6439                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6440                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6441                            info.activityInfo.packageName, info.activityInfo.splitName,
6442                            info.activityInfo.applicationInfo.versionCode);
6443                    // make sure this resolver is the default
6444                    installerInfo.isDefault = true;
6445                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6446                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6447                    // add a non-generic filter
6448                    installerInfo.filter = new IntentFilter();
6449                    // load resources from the correct package
6450                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6451                    resolveInfos.set(i, installerInfo);
6452                }
6453                continue;
6454            }
6455            // allow activities that have been explicitly exposed to ephemeral apps
6456            if (!isEphemeralApp
6457                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6458                continue;
6459            }
6460            resolveInfos.remove(i);
6461        }
6462        return resolveInfos;
6463    }
6464
6465    /**
6466     * @param resolveInfos list of resolve infos in descending priority order
6467     * @return if the list contains a resolve info with non-negative priority
6468     */
6469    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6470        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6471    }
6472
6473    private static boolean hasWebURI(Intent intent) {
6474        if (intent.getData() == null) {
6475            return false;
6476        }
6477        final String scheme = intent.getScheme();
6478        if (TextUtils.isEmpty(scheme)) {
6479            return false;
6480        }
6481        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6482    }
6483
6484    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6485            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6486            int userId) {
6487        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6488
6489        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6490            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6491                    candidates.size());
6492        }
6493
6494        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6495        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6496        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6497        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6498        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6499        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6500
6501        synchronized (mPackages) {
6502            final int count = candidates.size();
6503            // First, try to use linked apps. Partition the candidates into four lists:
6504            // one for the final results, one for the "do not use ever", one for "undefined status"
6505            // and finally one for "browser app type".
6506            for (int n=0; n<count; n++) {
6507                ResolveInfo info = candidates.get(n);
6508                String packageName = info.activityInfo.packageName;
6509                PackageSetting ps = mSettings.mPackages.get(packageName);
6510                if (ps != null) {
6511                    // Add to the special match all list (Browser use case)
6512                    if (info.handleAllWebDataURI) {
6513                        matchAllList.add(info);
6514                        continue;
6515                    }
6516                    // Try to get the status from User settings first
6517                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6518                    int status = (int)(packedStatus >> 32);
6519                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6520                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6521                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6522                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6523                                    + " : linkgen=" + linkGeneration);
6524                        }
6525                        // Use link-enabled generation as preferredOrder, i.e.
6526                        // prefer newly-enabled over earlier-enabled.
6527                        info.preferredOrder = linkGeneration;
6528                        alwaysList.add(info);
6529                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6530                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6531                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6532                        }
6533                        neverList.add(info);
6534                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6535                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6536                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6537                        }
6538                        alwaysAskList.add(info);
6539                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6540                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6541                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6542                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6543                        }
6544                        undefinedList.add(info);
6545                    }
6546                }
6547            }
6548
6549            // We'll want to include browser possibilities in a few cases
6550            boolean includeBrowser = false;
6551
6552            // First try to add the "always" resolution(s) for the current user, if any
6553            if (alwaysList.size() > 0) {
6554                result.addAll(alwaysList);
6555            } else {
6556                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6557                result.addAll(undefinedList);
6558                // Maybe add one for the other profile.
6559                if (xpDomainInfo != null && (
6560                        xpDomainInfo.bestDomainVerificationStatus
6561                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6562                    result.add(xpDomainInfo.resolveInfo);
6563                }
6564                includeBrowser = true;
6565            }
6566
6567            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6568            // If there were 'always' entries their preferred order has been set, so we also
6569            // back that off to make the alternatives equivalent
6570            if (alwaysAskList.size() > 0) {
6571                for (ResolveInfo i : result) {
6572                    i.preferredOrder = 0;
6573                }
6574                result.addAll(alwaysAskList);
6575                includeBrowser = true;
6576            }
6577
6578            if (includeBrowser) {
6579                // Also add browsers (all of them or only the default one)
6580                if (DEBUG_DOMAIN_VERIFICATION) {
6581                    Slog.v(TAG, "   ...including browsers in candidate set");
6582                }
6583                if ((matchFlags & MATCH_ALL) != 0) {
6584                    result.addAll(matchAllList);
6585                } else {
6586                    // Browser/generic handling case.  If there's a default browser, go straight
6587                    // to that (but only if there is no other higher-priority match).
6588                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6589                    int maxMatchPrio = 0;
6590                    ResolveInfo defaultBrowserMatch = null;
6591                    final int numCandidates = matchAllList.size();
6592                    for (int n = 0; n < numCandidates; n++) {
6593                        ResolveInfo info = matchAllList.get(n);
6594                        // track the highest overall match priority...
6595                        if (info.priority > maxMatchPrio) {
6596                            maxMatchPrio = info.priority;
6597                        }
6598                        // ...and the highest-priority default browser match
6599                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6600                            if (defaultBrowserMatch == null
6601                                    || (defaultBrowserMatch.priority < info.priority)) {
6602                                if (debug) {
6603                                    Slog.v(TAG, "Considering default browser match " + info);
6604                                }
6605                                defaultBrowserMatch = info;
6606                            }
6607                        }
6608                    }
6609                    if (defaultBrowserMatch != null
6610                            && defaultBrowserMatch.priority >= maxMatchPrio
6611                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6612                    {
6613                        if (debug) {
6614                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6615                        }
6616                        result.add(defaultBrowserMatch);
6617                    } else {
6618                        result.addAll(matchAllList);
6619                    }
6620                }
6621
6622                // If there is nothing selected, add all candidates and remove the ones that the user
6623                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6624                if (result.size() == 0) {
6625                    result.addAll(candidates);
6626                    result.removeAll(neverList);
6627                }
6628            }
6629        }
6630        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6631            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6632                    result.size());
6633            for (ResolveInfo info : result) {
6634                Slog.v(TAG, "  + " + info.activityInfo);
6635            }
6636        }
6637        return result;
6638    }
6639
6640    // Returns a packed value as a long:
6641    //
6642    // high 'int'-sized word: link status: undefined/ask/never/always.
6643    // low 'int'-sized word: relative priority among 'always' results.
6644    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6645        long result = ps.getDomainVerificationStatusForUser(userId);
6646        // if none available, get the master status
6647        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6648            if (ps.getIntentFilterVerificationInfo() != null) {
6649                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6650            }
6651        }
6652        return result;
6653    }
6654
6655    private ResolveInfo querySkipCurrentProfileIntents(
6656            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6657            int flags, int sourceUserId) {
6658        if (matchingFilters != null) {
6659            int size = matchingFilters.size();
6660            for (int i = 0; i < size; i ++) {
6661                CrossProfileIntentFilter filter = matchingFilters.get(i);
6662                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6663                    // Checking if there are activities in the target user that can handle the
6664                    // intent.
6665                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6666                            resolvedType, flags, sourceUserId);
6667                    if (resolveInfo != null) {
6668                        return resolveInfo;
6669                    }
6670                }
6671            }
6672        }
6673        return null;
6674    }
6675
6676    // Return matching ResolveInfo in target user if any.
6677    private ResolveInfo queryCrossProfileIntents(
6678            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6679            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6680        if (matchingFilters != null) {
6681            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6682            // match the same intent. For performance reasons, it is better not to
6683            // run queryIntent twice for the same userId
6684            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6685            int size = matchingFilters.size();
6686            for (int i = 0; i < size; i++) {
6687                CrossProfileIntentFilter filter = matchingFilters.get(i);
6688                int targetUserId = filter.getTargetUserId();
6689                boolean skipCurrentProfile =
6690                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6691                boolean skipCurrentProfileIfNoMatchFound =
6692                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6693                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6694                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6695                    // Checking if there are activities in the target user that can handle the
6696                    // intent.
6697                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6698                            resolvedType, flags, sourceUserId);
6699                    if (resolveInfo != null) return resolveInfo;
6700                    alreadyTriedUserIds.put(targetUserId, true);
6701                }
6702            }
6703        }
6704        return null;
6705    }
6706
6707    /**
6708     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6709     * will forward the intent to the filter's target user.
6710     * Otherwise, returns null.
6711     */
6712    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6713            String resolvedType, int flags, int sourceUserId) {
6714        int targetUserId = filter.getTargetUserId();
6715        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6716                resolvedType, flags, targetUserId);
6717        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6718            // If all the matches in the target profile are suspended, return null.
6719            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6720                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6721                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6722                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6723                            targetUserId);
6724                }
6725            }
6726        }
6727        return null;
6728    }
6729
6730    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6731            int sourceUserId, int targetUserId) {
6732        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6733        long ident = Binder.clearCallingIdentity();
6734        boolean targetIsProfile;
6735        try {
6736            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6737        } finally {
6738            Binder.restoreCallingIdentity(ident);
6739        }
6740        String className;
6741        if (targetIsProfile) {
6742            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6743        } else {
6744            className = FORWARD_INTENT_TO_PARENT;
6745        }
6746        ComponentName forwardingActivityComponentName = new ComponentName(
6747                mAndroidApplication.packageName, className);
6748        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6749                sourceUserId);
6750        if (!targetIsProfile) {
6751            forwardingActivityInfo.showUserIcon = targetUserId;
6752            forwardingResolveInfo.noResourceId = true;
6753        }
6754        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6755        forwardingResolveInfo.priority = 0;
6756        forwardingResolveInfo.preferredOrder = 0;
6757        forwardingResolveInfo.match = 0;
6758        forwardingResolveInfo.isDefault = true;
6759        forwardingResolveInfo.filter = filter;
6760        forwardingResolveInfo.targetUserId = targetUserId;
6761        return forwardingResolveInfo;
6762    }
6763
6764    @Override
6765    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6766            Intent[] specifics, String[] specificTypes, Intent intent,
6767            String resolvedType, int flags, int userId) {
6768        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6769                specificTypes, intent, resolvedType, flags, userId));
6770    }
6771
6772    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6773            Intent[] specifics, String[] specificTypes, Intent intent,
6774            String resolvedType, int flags, int userId) {
6775        if (!sUserManager.exists(userId)) return Collections.emptyList();
6776        flags = updateFlagsForResolve(flags, userId, intent, false);
6777        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6778                false /* requireFullPermission */, false /* checkShell */,
6779                "query intent activity options");
6780        final String resultsAction = intent.getAction();
6781
6782        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6783                | PackageManager.GET_RESOLVED_FILTER, userId);
6784
6785        if (DEBUG_INTENT_MATCHING) {
6786            Log.v(TAG, "Query " + intent + ": " + results);
6787        }
6788
6789        int specificsPos = 0;
6790        int N;
6791
6792        // todo: note that the algorithm used here is O(N^2).  This
6793        // isn't a problem in our current environment, but if we start running
6794        // into situations where we have more than 5 or 10 matches then this
6795        // should probably be changed to something smarter...
6796
6797        // First we go through and resolve each of the specific items
6798        // that were supplied, taking care of removing any corresponding
6799        // duplicate items in the generic resolve list.
6800        if (specifics != null) {
6801            for (int i=0; i<specifics.length; i++) {
6802                final Intent sintent = specifics[i];
6803                if (sintent == null) {
6804                    continue;
6805                }
6806
6807                if (DEBUG_INTENT_MATCHING) {
6808                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6809                }
6810
6811                String action = sintent.getAction();
6812                if (resultsAction != null && resultsAction.equals(action)) {
6813                    // If this action was explicitly requested, then don't
6814                    // remove things that have it.
6815                    action = null;
6816                }
6817
6818                ResolveInfo ri = null;
6819                ActivityInfo ai = null;
6820
6821                ComponentName comp = sintent.getComponent();
6822                if (comp == null) {
6823                    ri = resolveIntent(
6824                        sintent,
6825                        specificTypes != null ? specificTypes[i] : null,
6826                            flags, userId);
6827                    if (ri == null) {
6828                        continue;
6829                    }
6830                    if (ri == mResolveInfo) {
6831                        // ACK!  Must do something better with this.
6832                    }
6833                    ai = ri.activityInfo;
6834                    comp = new ComponentName(ai.applicationInfo.packageName,
6835                            ai.name);
6836                } else {
6837                    ai = getActivityInfo(comp, flags, userId);
6838                    if (ai == null) {
6839                        continue;
6840                    }
6841                }
6842
6843                // Look for any generic query activities that are duplicates
6844                // of this specific one, and remove them from the results.
6845                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6846                N = results.size();
6847                int j;
6848                for (j=specificsPos; j<N; j++) {
6849                    ResolveInfo sri = results.get(j);
6850                    if ((sri.activityInfo.name.equals(comp.getClassName())
6851                            && sri.activityInfo.applicationInfo.packageName.equals(
6852                                    comp.getPackageName()))
6853                        || (action != null && sri.filter.matchAction(action))) {
6854                        results.remove(j);
6855                        if (DEBUG_INTENT_MATCHING) Log.v(
6856                            TAG, "Removing duplicate item from " + j
6857                            + " due to specific " + specificsPos);
6858                        if (ri == null) {
6859                            ri = sri;
6860                        }
6861                        j--;
6862                        N--;
6863                    }
6864                }
6865
6866                // Add this specific item to its proper place.
6867                if (ri == null) {
6868                    ri = new ResolveInfo();
6869                    ri.activityInfo = ai;
6870                }
6871                results.add(specificsPos, ri);
6872                ri.specificIndex = i;
6873                specificsPos++;
6874            }
6875        }
6876
6877        // Now we go through the remaining generic results and remove any
6878        // duplicate actions that are found here.
6879        N = results.size();
6880        for (int i=specificsPos; i<N-1; i++) {
6881            final ResolveInfo rii = results.get(i);
6882            if (rii.filter == null) {
6883                continue;
6884            }
6885
6886            // Iterate over all of the actions of this result's intent
6887            // filter...  typically this should be just one.
6888            final Iterator<String> it = rii.filter.actionsIterator();
6889            if (it == null) {
6890                continue;
6891            }
6892            while (it.hasNext()) {
6893                final String action = it.next();
6894                if (resultsAction != null && resultsAction.equals(action)) {
6895                    // If this action was explicitly requested, then don't
6896                    // remove things that have it.
6897                    continue;
6898                }
6899                for (int j=i+1; j<N; j++) {
6900                    final ResolveInfo rij = results.get(j);
6901                    if (rij.filter != null && rij.filter.hasAction(action)) {
6902                        results.remove(j);
6903                        if (DEBUG_INTENT_MATCHING) Log.v(
6904                            TAG, "Removing duplicate item from " + j
6905                            + " due to action " + action + " at " + i);
6906                        j--;
6907                        N--;
6908                    }
6909                }
6910            }
6911
6912            // If the caller didn't request filter information, drop it now
6913            // so we don't have to marshall/unmarshall it.
6914            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6915                rii.filter = null;
6916            }
6917        }
6918
6919        // Filter out the caller activity if so requested.
6920        if (caller != null) {
6921            N = results.size();
6922            for (int i=0; i<N; i++) {
6923                ActivityInfo ainfo = results.get(i).activityInfo;
6924                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6925                        && caller.getClassName().equals(ainfo.name)) {
6926                    results.remove(i);
6927                    break;
6928                }
6929            }
6930        }
6931
6932        // If the caller didn't request filter information,
6933        // drop them now so we don't have to
6934        // marshall/unmarshall it.
6935        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6936            N = results.size();
6937            for (int i=0; i<N; i++) {
6938                results.get(i).filter = null;
6939            }
6940        }
6941
6942        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6943        return results;
6944    }
6945
6946    @Override
6947    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6948            String resolvedType, int flags, int userId) {
6949        return new ParceledListSlice<>(
6950                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6951    }
6952
6953    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6954            String resolvedType, int flags, int userId) {
6955        if (!sUserManager.exists(userId)) return Collections.emptyList();
6956        flags = updateFlagsForResolve(flags, userId, intent, false);
6957        ComponentName comp = intent.getComponent();
6958        if (comp == null) {
6959            if (intent.getSelector() != null) {
6960                intent = intent.getSelector();
6961                comp = intent.getComponent();
6962            }
6963        }
6964        if (comp != null) {
6965            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6966            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6967            if (ai != null) {
6968                ResolveInfo ri = new ResolveInfo();
6969                ri.activityInfo = ai;
6970                list.add(ri);
6971            }
6972            return list;
6973        }
6974
6975        // reader
6976        synchronized (mPackages) {
6977            String pkgName = intent.getPackage();
6978            if (pkgName == null) {
6979                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6980            }
6981            final PackageParser.Package pkg = mPackages.get(pkgName);
6982            if (pkg != null) {
6983                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6984                        userId);
6985            }
6986            return Collections.emptyList();
6987        }
6988    }
6989
6990    @Override
6991    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6992        if (!sUserManager.exists(userId)) return null;
6993        flags = updateFlagsForResolve(flags, userId, intent, false);
6994        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6995        if (query != null) {
6996            if (query.size() >= 1) {
6997                // If there is more than one service with the same priority,
6998                // just arbitrarily pick the first one.
6999                return query.get(0);
7000            }
7001        }
7002        return null;
7003    }
7004
7005    @Override
7006    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7007            String resolvedType, int flags, int userId) {
7008        return new ParceledListSlice<>(
7009                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7010    }
7011
7012    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7013            String resolvedType, int flags, int userId) {
7014        if (!sUserManager.exists(userId)) return Collections.emptyList();
7015        flags = updateFlagsForResolve(flags, userId, intent, false);
7016        ComponentName comp = intent.getComponent();
7017        if (comp == null) {
7018            if (intent.getSelector() != null) {
7019                intent = intent.getSelector();
7020                comp = intent.getComponent();
7021            }
7022        }
7023        if (comp != null) {
7024            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7025            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7026            if (si != null) {
7027                final ResolveInfo ri = new ResolveInfo();
7028                ri.serviceInfo = si;
7029                list.add(ri);
7030            }
7031            return list;
7032        }
7033
7034        // reader
7035        synchronized (mPackages) {
7036            String pkgName = intent.getPackage();
7037            if (pkgName == null) {
7038                return mServices.queryIntent(intent, resolvedType, flags, userId);
7039            }
7040            final PackageParser.Package pkg = mPackages.get(pkgName);
7041            if (pkg != null) {
7042                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7043                        userId);
7044            }
7045            return Collections.emptyList();
7046        }
7047    }
7048
7049    @Override
7050    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7051            String resolvedType, int flags, int userId) {
7052        return new ParceledListSlice<>(
7053                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7054    }
7055
7056    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7057            Intent intent, String resolvedType, int flags, int userId) {
7058        if (!sUserManager.exists(userId)) return Collections.emptyList();
7059        flags = updateFlagsForResolve(flags, userId, intent, false);
7060        ComponentName comp = intent.getComponent();
7061        if (comp == null) {
7062            if (intent.getSelector() != null) {
7063                intent = intent.getSelector();
7064                comp = intent.getComponent();
7065            }
7066        }
7067        if (comp != null) {
7068            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7069            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7070            if (pi != null) {
7071                final ResolveInfo ri = new ResolveInfo();
7072                ri.providerInfo = pi;
7073                list.add(ri);
7074            }
7075            return list;
7076        }
7077
7078        // reader
7079        synchronized (mPackages) {
7080            String pkgName = intent.getPackage();
7081            if (pkgName == null) {
7082                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7083            }
7084            final PackageParser.Package pkg = mPackages.get(pkgName);
7085            if (pkg != null) {
7086                return mProviders.queryIntentForPackage(
7087                        intent, resolvedType, flags, pkg.providers, userId);
7088            }
7089            return Collections.emptyList();
7090        }
7091    }
7092
7093    @Override
7094    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7095        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7096        flags = updateFlagsForPackage(flags, userId, null);
7097        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7098        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7099                true /* requireFullPermission */, false /* checkShell */,
7100                "get installed packages");
7101
7102        // writer
7103        synchronized (mPackages) {
7104            ArrayList<PackageInfo> list;
7105            if (listUninstalled) {
7106                list = new ArrayList<>(mSettings.mPackages.size());
7107                for (PackageSetting ps : mSettings.mPackages.values()) {
7108                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7109                        continue;
7110                    }
7111                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7112                    if (pi != null) {
7113                        list.add(pi);
7114                    }
7115                }
7116            } else {
7117                list = new ArrayList<>(mPackages.size());
7118                for (PackageParser.Package p : mPackages.values()) {
7119                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7120                            Binder.getCallingUid(), userId)) {
7121                        continue;
7122                    }
7123                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7124                            p.mExtras, flags, userId);
7125                    if (pi != null) {
7126                        list.add(pi);
7127                    }
7128                }
7129            }
7130
7131            return new ParceledListSlice<>(list);
7132        }
7133    }
7134
7135    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7136            String[] permissions, boolean[] tmp, int flags, int userId) {
7137        int numMatch = 0;
7138        final PermissionsState permissionsState = ps.getPermissionsState();
7139        for (int i=0; i<permissions.length; i++) {
7140            final String permission = permissions[i];
7141            if (permissionsState.hasPermission(permission, userId)) {
7142                tmp[i] = true;
7143                numMatch++;
7144            } else {
7145                tmp[i] = false;
7146            }
7147        }
7148        if (numMatch == 0) {
7149            return;
7150        }
7151        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7152
7153        // The above might return null in cases of uninstalled apps or install-state
7154        // skew across users/profiles.
7155        if (pi != null) {
7156            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7157                if (numMatch == permissions.length) {
7158                    pi.requestedPermissions = permissions;
7159                } else {
7160                    pi.requestedPermissions = new String[numMatch];
7161                    numMatch = 0;
7162                    for (int i=0; i<permissions.length; i++) {
7163                        if (tmp[i]) {
7164                            pi.requestedPermissions[numMatch] = permissions[i];
7165                            numMatch++;
7166                        }
7167                    }
7168                }
7169            }
7170            list.add(pi);
7171        }
7172    }
7173
7174    @Override
7175    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7176            String[] permissions, int flags, int userId) {
7177        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7178        flags = updateFlagsForPackage(flags, userId, permissions);
7179        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7180                true /* requireFullPermission */, false /* checkShell */,
7181                "get packages holding permissions");
7182        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7183
7184        // writer
7185        synchronized (mPackages) {
7186            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7187            boolean[] tmpBools = new boolean[permissions.length];
7188            if (listUninstalled) {
7189                for (PackageSetting ps : mSettings.mPackages.values()) {
7190                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7191                            userId);
7192                }
7193            } else {
7194                for (PackageParser.Package pkg : mPackages.values()) {
7195                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7196                    if (ps != null) {
7197                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7198                                userId);
7199                    }
7200                }
7201            }
7202
7203            return new ParceledListSlice<PackageInfo>(list);
7204        }
7205    }
7206
7207    @Override
7208    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7209        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7210        flags = updateFlagsForApplication(flags, userId, null);
7211        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7212
7213        // writer
7214        synchronized (mPackages) {
7215            ArrayList<ApplicationInfo> list;
7216            if (listUninstalled) {
7217                list = new ArrayList<>(mSettings.mPackages.size());
7218                for (PackageSetting ps : mSettings.mPackages.values()) {
7219                    ApplicationInfo ai;
7220                    int effectiveFlags = flags;
7221                    if (ps.isSystem()) {
7222                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7223                    }
7224                    if (ps.pkg != null) {
7225                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7226                            continue;
7227                        }
7228                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7229                                ps.readUserState(userId), userId);
7230                        if (ai != null) {
7231                            rebaseEnabledOverlays(ai, userId);
7232                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7233                        }
7234                    } else {
7235                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7236                        // and already converts to externally visible package name
7237                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7238                                Binder.getCallingUid(), effectiveFlags, userId);
7239                    }
7240                    if (ai != null) {
7241                        list.add(ai);
7242                    }
7243                }
7244            } else {
7245                list = new ArrayList<>(mPackages.size());
7246                for (PackageParser.Package p : mPackages.values()) {
7247                    if (p.mExtras != null) {
7248                        PackageSetting ps = (PackageSetting) p.mExtras;
7249                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7250                            continue;
7251                        }
7252                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7253                                ps.readUserState(userId), userId);
7254                        if (ai != null) {
7255                            rebaseEnabledOverlays(ai, userId);
7256                            ai.packageName = resolveExternalPackageNameLPr(p);
7257                            list.add(ai);
7258                        }
7259                    }
7260                }
7261            }
7262
7263            return new ParceledListSlice<>(list);
7264        }
7265    }
7266
7267    @Override
7268    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7269        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7270            return null;
7271        }
7272
7273        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7274                "getEphemeralApplications");
7275        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7276                true /* requireFullPermission */, false /* checkShell */,
7277                "getEphemeralApplications");
7278        synchronized (mPackages) {
7279            List<InstantAppInfo> instantApps = mInstantAppRegistry
7280                    .getInstantAppsLPr(userId);
7281            if (instantApps != null) {
7282                return new ParceledListSlice<>(instantApps);
7283            }
7284        }
7285        return null;
7286    }
7287
7288    @Override
7289    public boolean isInstantApp(String packageName, int userId) {
7290        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7291                true /* requireFullPermission */, false /* checkShell */,
7292                "isInstantApp");
7293        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7294            return false;
7295        }
7296
7297        synchronized (mPackages) {
7298            final PackageSetting ps = mSettings.mPackages.get(packageName);
7299            final boolean returnAllowed =
7300                    ps != null
7301                    && (isCallerSameApp(packageName)
7302                            || mContext.checkCallingOrSelfPermission(
7303                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7304                                            == PERMISSION_GRANTED
7305                            || mInstantAppRegistry.isInstantAccessGranted(
7306                                    userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId));
7307            if (returnAllowed) {
7308                return ps.getInstantApp(userId);
7309            }
7310        }
7311        return false;
7312    }
7313
7314    @Override
7315    public byte[] getInstantAppCookie(String packageName, int userId) {
7316        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7317            return null;
7318        }
7319
7320        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7321                true /* requireFullPermission */, false /* checkShell */,
7322                "getInstantAppCookie");
7323        if (!isCallerSameApp(packageName)) {
7324            return null;
7325        }
7326        synchronized (mPackages) {
7327            return mInstantAppRegistry.getInstantAppCookieLPw(
7328                    packageName, userId);
7329        }
7330    }
7331
7332    @Override
7333    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7334        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7335            return true;
7336        }
7337
7338        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7339                true /* requireFullPermission */, true /* checkShell */,
7340                "setInstantAppCookie");
7341        if (!isCallerSameApp(packageName)) {
7342            return false;
7343        }
7344        synchronized (mPackages) {
7345            return mInstantAppRegistry.setInstantAppCookieLPw(
7346                    packageName, cookie, userId);
7347        }
7348    }
7349
7350    @Override
7351    public Bitmap getInstantAppIcon(String packageName, int userId) {
7352        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7353            return null;
7354        }
7355
7356        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7357                "getInstantAppIcon");
7358
7359        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7360                true /* requireFullPermission */, false /* checkShell */,
7361                "getInstantAppIcon");
7362
7363        synchronized (mPackages) {
7364            return mInstantAppRegistry.getInstantAppIconLPw(
7365                    packageName, userId);
7366        }
7367    }
7368
7369    private boolean isCallerSameApp(String packageName) {
7370        PackageParser.Package pkg = mPackages.get(packageName);
7371        return pkg != null
7372                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7373    }
7374
7375    @Override
7376    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7377        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7378    }
7379
7380    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7381        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7382
7383        // reader
7384        synchronized (mPackages) {
7385            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7386            final int userId = UserHandle.getCallingUserId();
7387            while (i.hasNext()) {
7388                final PackageParser.Package p = i.next();
7389                if (p.applicationInfo == null) continue;
7390
7391                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7392                        && !p.applicationInfo.isDirectBootAware();
7393                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7394                        && p.applicationInfo.isDirectBootAware();
7395
7396                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7397                        && (!mSafeMode || isSystemApp(p))
7398                        && (matchesUnaware || matchesAware)) {
7399                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7400                    if (ps != null) {
7401                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7402                                ps.readUserState(userId), userId);
7403                        if (ai != null) {
7404                            rebaseEnabledOverlays(ai, userId);
7405                            finalList.add(ai);
7406                        }
7407                    }
7408                }
7409            }
7410        }
7411
7412        return finalList;
7413    }
7414
7415    @Override
7416    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7417        if (!sUserManager.exists(userId)) return null;
7418        flags = updateFlagsForComponent(flags, userId, name);
7419        // reader
7420        synchronized (mPackages) {
7421            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7422            PackageSetting ps = provider != null
7423                    ? mSettings.mPackages.get(provider.owner.packageName)
7424                    : null;
7425            return ps != null
7426                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7427                    ? PackageParser.generateProviderInfo(provider, flags,
7428                            ps.readUserState(userId), userId)
7429                    : null;
7430        }
7431    }
7432
7433    /**
7434     * @deprecated
7435     */
7436    @Deprecated
7437    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7438        // reader
7439        synchronized (mPackages) {
7440            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7441                    .entrySet().iterator();
7442            final int userId = UserHandle.getCallingUserId();
7443            while (i.hasNext()) {
7444                Map.Entry<String, PackageParser.Provider> entry = i.next();
7445                PackageParser.Provider p = entry.getValue();
7446                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7447
7448                if (ps != null && p.syncable
7449                        && (!mSafeMode || (p.info.applicationInfo.flags
7450                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7451                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7452                            ps.readUserState(userId), userId);
7453                    if (info != null) {
7454                        outNames.add(entry.getKey());
7455                        outInfo.add(info);
7456                    }
7457                }
7458            }
7459        }
7460    }
7461
7462    @Override
7463    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7464            int uid, int flags, String metaDataKey) {
7465        final int userId = processName != null ? UserHandle.getUserId(uid)
7466                : UserHandle.getCallingUserId();
7467        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7468        flags = updateFlagsForComponent(flags, userId, processName);
7469
7470        ArrayList<ProviderInfo> finalList = null;
7471        // reader
7472        synchronized (mPackages) {
7473            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7474            while (i.hasNext()) {
7475                final PackageParser.Provider p = i.next();
7476                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7477                if (ps != null && p.info.authority != null
7478                        && (processName == null
7479                                || (p.info.processName.equals(processName)
7480                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7481                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7482
7483                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7484                    // parameter.
7485                    if (metaDataKey != null
7486                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7487                        continue;
7488                    }
7489
7490                    if (finalList == null) {
7491                        finalList = new ArrayList<ProviderInfo>(3);
7492                    }
7493                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7494                            ps.readUserState(userId), userId);
7495                    if (info != null) {
7496                        finalList.add(info);
7497                    }
7498                }
7499            }
7500        }
7501
7502        if (finalList != null) {
7503            Collections.sort(finalList, mProviderInitOrderSorter);
7504            return new ParceledListSlice<ProviderInfo>(finalList);
7505        }
7506
7507        return ParceledListSlice.emptyList();
7508    }
7509
7510    @Override
7511    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7512        // reader
7513        synchronized (mPackages) {
7514            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7515            return PackageParser.generateInstrumentationInfo(i, flags);
7516        }
7517    }
7518
7519    @Override
7520    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7521            String targetPackage, int flags) {
7522        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7523    }
7524
7525    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7526            int flags) {
7527        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7528
7529        // reader
7530        synchronized (mPackages) {
7531            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7532            while (i.hasNext()) {
7533                final PackageParser.Instrumentation p = i.next();
7534                if (targetPackage == null
7535                        || targetPackage.equals(p.info.targetPackage)) {
7536                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7537                            flags);
7538                    if (ii != null) {
7539                        finalList.add(ii);
7540                    }
7541                }
7542            }
7543        }
7544
7545        return finalList;
7546    }
7547
7548    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7549        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7550        try {
7551            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7552        } finally {
7553            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7554        }
7555    }
7556
7557    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7558        final File[] files = dir.listFiles();
7559        if (ArrayUtils.isEmpty(files)) {
7560            Log.d(TAG, "No files in app dir " + dir);
7561            return;
7562        }
7563
7564        if (DEBUG_PACKAGE_SCANNING) {
7565            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7566                    + " flags=0x" + Integer.toHexString(parseFlags));
7567        }
7568        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7569                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7570
7571        // Submit files for parsing in parallel
7572        int fileCount = 0;
7573        for (File file : files) {
7574            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7575                    && !PackageInstallerService.isStageName(file.getName());
7576            if (!isPackage) {
7577                // Ignore entries which are not packages
7578                continue;
7579            }
7580            parallelPackageParser.submit(file, parseFlags);
7581            fileCount++;
7582        }
7583
7584        // Process results one by one
7585        for (; fileCount > 0; fileCount--) {
7586            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7587            Throwable throwable = parseResult.throwable;
7588            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7589
7590            if (throwable == null) {
7591                // Static shared libraries have synthetic package names
7592                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7593                    renameStaticSharedLibraryPackage(parseResult.pkg);
7594                }
7595                try {
7596                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7597                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7598                                currentTime, null);
7599                    }
7600                } catch (PackageManagerException e) {
7601                    errorCode = e.error;
7602                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7603                }
7604            } else if (throwable instanceof PackageParser.PackageParserException) {
7605                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7606                        throwable;
7607                errorCode = e.error;
7608                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7609            } else {
7610                throw new IllegalStateException("Unexpected exception occurred while parsing "
7611                        + parseResult.scanFile, throwable);
7612            }
7613
7614            // Delete invalid userdata apps
7615            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7616                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7617                logCriticalInfo(Log.WARN,
7618                        "Deleting invalid package at " + parseResult.scanFile);
7619                removeCodePathLI(parseResult.scanFile);
7620            }
7621        }
7622        parallelPackageParser.close();
7623    }
7624
7625    private static File getSettingsProblemFile() {
7626        File dataDir = Environment.getDataDirectory();
7627        File systemDir = new File(dataDir, "system");
7628        File fname = new File(systemDir, "uiderrors.txt");
7629        return fname;
7630    }
7631
7632    static void reportSettingsProblem(int priority, String msg) {
7633        logCriticalInfo(priority, msg);
7634    }
7635
7636    public static void logCriticalInfo(int priority, String msg) {
7637        Slog.println(priority, TAG, msg);
7638        EventLogTags.writePmCriticalInfo(msg);
7639        try {
7640            File fname = getSettingsProblemFile();
7641            FileOutputStream out = new FileOutputStream(fname, true);
7642            PrintWriter pw = new FastPrintWriter(out);
7643            SimpleDateFormat formatter = new SimpleDateFormat();
7644            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7645            pw.println(dateString + ": " + msg);
7646            pw.close();
7647            FileUtils.setPermissions(
7648                    fname.toString(),
7649                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7650                    -1, -1);
7651        } catch (java.io.IOException e) {
7652        }
7653    }
7654
7655    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7656        if (srcFile.isDirectory()) {
7657            final File baseFile = new File(pkg.baseCodePath);
7658            long maxModifiedTime = baseFile.lastModified();
7659            if (pkg.splitCodePaths != null) {
7660                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7661                    final File splitFile = new File(pkg.splitCodePaths[i]);
7662                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7663                }
7664            }
7665            return maxModifiedTime;
7666        }
7667        return srcFile.lastModified();
7668    }
7669
7670    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7671            final int policyFlags) throws PackageManagerException {
7672        // When upgrading from pre-N MR1, verify the package time stamp using the package
7673        // directory and not the APK file.
7674        final long lastModifiedTime = mIsPreNMR1Upgrade
7675                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7676        if (ps != null
7677                && ps.codePath.equals(srcFile)
7678                && ps.timeStamp == lastModifiedTime
7679                && !isCompatSignatureUpdateNeeded(pkg)
7680                && !isRecoverSignatureUpdateNeeded(pkg)) {
7681            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7682            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7683            ArraySet<PublicKey> signingKs;
7684            synchronized (mPackages) {
7685                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7686            }
7687            if (ps.signatures.mSignatures != null
7688                    && ps.signatures.mSignatures.length != 0
7689                    && signingKs != null) {
7690                // Optimization: reuse the existing cached certificates
7691                // if the package appears to be unchanged.
7692                pkg.mSignatures = ps.signatures.mSignatures;
7693                pkg.mSigningKeys = signingKs;
7694                return;
7695            }
7696
7697            Slog.w(TAG, "PackageSetting for " + ps.name
7698                    + " is missing signatures.  Collecting certs again to recover them.");
7699        } else {
7700            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7701        }
7702
7703        try {
7704            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7705            PackageParser.collectCertificates(pkg, policyFlags);
7706        } catch (PackageParserException e) {
7707            throw PackageManagerException.from(e);
7708        } finally {
7709            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7710        }
7711    }
7712
7713    /**
7714     *  Traces a package scan.
7715     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7716     */
7717    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7718            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7719        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7720        try {
7721            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7722        } finally {
7723            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7724        }
7725    }
7726
7727    /**
7728     *  Scans a package and returns the newly parsed package.
7729     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7730     */
7731    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7732            long currentTime, UserHandle user) throws PackageManagerException {
7733        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7734        PackageParser pp = new PackageParser();
7735        pp.setSeparateProcesses(mSeparateProcesses);
7736        pp.setOnlyCoreApps(mOnlyCore);
7737        pp.setDisplayMetrics(mMetrics);
7738        pp.setCallback(mPackageParserCallback);
7739
7740        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7741            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7742        }
7743
7744        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7745        final PackageParser.Package pkg;
7746        try {
7747            pkg = pp.parsePackage(scanFile, parseFlags);
7748        } catch (PackageParserException e) {
7749            throw PackageManagerException.from(e);
7750        } finally {
7751            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7752        }
7753
7754        // Static shared libraries have synthetic package names
7755        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7756            renameStaticSharedLibraryPackage(pkg);
7757        }
7758
7759        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7760    }
7761
7762    /**
7763     *  Scans a package and returns the newly parsed package.
7764     *  @throws PackageManagerException on a parse error.
7765     */
7766    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7767            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7768            throws PackageManagerException {
7769        // If the package has children and this is the first dive in the function
7770        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7771        // packages (parent and children) would be successfully scanned before the
7772        // actual scan since scanning mutates internal state and we want to atomically
7773        // install the package and its children.
7774        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7775            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7776                scanFlags |= SCAN_CHECK_ONLY;
7777            }
7778        } else {
7779            scanFlags &= ~SCAN_CHECK_ONLY;
7780        }
7781
7782        // Scan the parent
7783        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7784                scanFlags, currentTime, user);
7785
7786        // Scan the children
7787        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7788        for (int i = 0; i < childCount; i++) {
7789            PackageParser.Package childPackage = pkg.childPackages.get(i);
7790            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7791                    currentTime, user);
7792        }
7793
7794
7795        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7796            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7797        }
7798
7799        return scannedPkg;
7800    }
7801
7802    /**
7803     *  Scans a package and returns the newly parsed package.
7804     *  @throws PackageManagerException on a parse error.
7805     */
7806    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7807            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7808            throws PackageManagerException {
7809        PackageSetting ps = null;
7810        PackageSetting updatedPkg;
7811        // reader
7812        synchronized (mPackages) {
7813            // Look to see if we already know about this package.
7814            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7815            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7816                // This package has been renamed to its original name.  Let's
7817                // use that.
7818                ps = mSettings.getPackageLPr(oldName);
7819            }
7820            // If there was no original package, see one for the real package name.
7821            if (ps == null) {
7822                ps = mSettings.getPackageLPr(pkg.packageName);
7823            }
7824            // Check to see if this package could be hiding/updating a system
7825            // package.  Must look for it either under the original or real
7826            // package name depending on our state.
7827            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7828            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7829
7830            // If this is a package we don't know about on the system partition, we
7831            // may need to remove disabled child packages on the system partition
7832            // or may need to not add child packages if the parent apk is updated
7833            // on the data partition and no longer defines this child package.
7834            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7835                // If this is a parent package for an updated system app and this system
7836                // app got an OTA update which no longer defines some of the child packages
7837                // we have to prune them from the disabled system packages.
7838                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7839                if (disabledPs != null) {
7840                    final int scannedChildCount = (pkg.childPackages != null)
7841                            ? pkg.childPackages.size() : 0;
7842                    final int disabledChildCount = disabledPs.childPackageNames != null
7843                            ? disabledPs.childPackageNames.size() : 0;
7844                    for (int i = 0; i < disabledChildCount; i++) {
7845                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7846                        boolean disabledPackageAvailable = false;
7847                        for (int j = 0; j < scannedChildCount; j++) {
7848                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7849                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7850                                disabledPackageAvailable = true;
7851                                break;
7852                            }
7853                         }
7854                         if (!disabledPackageAvailable) {
7855                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7856                         }
7857                    }
7858                }
7859            }
7860        }
7861
7862        boolean updatedPkgBetter = false;
7863        // First check if this is a system package that may involve an update
7864        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7865            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7866            // it needs to drop FLAG_PRIVILEGED.
7867            if (locationIsPrivileged(scanFile)) {
7868                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7869            } else {
7870                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7871            }
7872
7873            if (ps != null && !ps.codePath.equals(scanFile)) {
7874                // The path has changed from what was last scanned...  check the
7875                // version of the new path against what we have stored to determine
7876                // what to do.
7877                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7878                if (pkg.mVersionCode <= ps.versionCode) {
7879                    // The system package has been updated and the code path does not match
7880                    // Ignore entry. Skip it.
7881                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7882                            + " ignored: updated version " + ps.versionCode
7883                            + " better than this " + pkg.mVersionCode);
7884                    if (!updatedPkg.codePath.equals(scanFile)) {
7885                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7886                                + ps.name + " changing from " + updatedPkg.codePathString
7887                                + " to " + scanFile);
7888                        updatedPkg.codePath = scanFile;
7889                        updatedPkg.codePathString = scanFile.toString();
7890                        updatedPkg.resourcePath = scanFile;
7891                        updatedPkg.resourcePathString = scanFile.toString();
7892                    }
7893                    updatedPkg.pkg = pkg;
7894                    updatedPkg.versionCode = pkg.mVersionCode;
7895
7896                    // Update the disabled system child packages to point to the package too.
7897                    final int childCount = updatedPkg.childPackageNames != null
7898                            ? updatedPkg.childPackageNames.size() : 0;
7899                    for (int i = 0; i < childCount; i++) {
7900                        String childPackageName = updatedPkg.childPackageNames.get(i);
7901                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7902                                childPackageName);
7903                        if (updatedChildPkg != null) {
7904                            updatedChildPkg.pkg = pkg;
7905                            updatedChildPkg.versionCode = pkg.mVersionCode;
7906                        }
7907                    }
7908
7909                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7910                            + scanFile + " ignored: updated version " + ps.versionCode
7911                            + " better than this " + pkg.mVersionCode);
7912                } else {
7913                    // The current app on the system partition is better than
7914                    // what we have updated to on the data partition; switch
7915                    // back to the system partition version.
7916                    // At this point, its safely assumed that package installation for
7917                    // apps in system partition will go through. If not there won't be a working
7918                    // version of the app
7919                    // writer
7920                    synchronized (mPackages) {
7921                        // Just remove the loaded entries from package lists.
7922                        mPackages.remove(ps.name);
7923                    }
7924
7925                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7926                            + " reverting from " + ps.codePathString
7927                            + ": new version " + pkg.mVersionCode
7928                            + " better than installed " + ps.versionCode);
7929
7930                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7931                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7932                    synchronized (mInstallLock) {
7933                        args.cleanUpResourcesLI();
7934                    }
7935                    synchronized (mPackages) {
7936                        mSettings.enableSystemPackageLPw(ps.name);
7937                    }
7938                    updatedPkgBetter = true;
7939                }
7940            }
7941        }
7942
7943        if (updatedPkg != null) {
7944            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7945            // initially
7946            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7947
7948            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7949            // flag set initially
7950            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7951                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7952            }
7953        }
7954
7955        // Verify certificates against what was last scanned
7956        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7957
7958        /*
7959         * A new system app appeared, but we already had a non-system one of the
7960         * same name installed earlier.
7961         */
7962        boolean shouldHideSystemApp = false;
7963        if (updatedPkg == null && ps != null
7964                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7965            /*
7966             * Check to make sure the signatures match first. If they don't,
7967             * wipe the installed application and its data.
7968             */
7969            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7970                    != PackageManager.SIGNATURE_MATCH) {
7971                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7972                        + " signatures don't match existing userdata copy; removing");
7973                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7974                        "scanPackageInternalLI")) {
7975                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7976                }
7977                ps = null;
7978            } else {
7979                /*
7980                 * If the newly-added system app is an older version than the
7981                 * already installed version, hide it. It will be scanned later
7982                 * and re-added like an update.
7983                 */
7984                if (pkg.mVersionCode <= ps.versionCode) {
7985                    shouldHideSystemApp = true;
7986                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7987                            + " but new version " + pkg.mVersionCode + " better than installed "
7988                            + ps.versionCode + "; hiding system");
7989                } else {
7990                    /*
7991                     * The newly found system app is a newer version that the
7992                     * one previously installed. Simply remove the
7993                     * already-installed application and replace it with our own
7994                     * while keeping the application data.
7995                     */
7996                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7997                            + " reverting from " + ps.codePathString + ": new version "
7998                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7999                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8000                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8001                    synchronized (mInstallLock) {
8002                        args.cleanUpResourcesLI();
8003                    }
8004                }
8005            }
8006        }
8007
8008        // The apk is forward locked (not public) if its code and resources
8009        // are kept in different files. (except for app in either system or
8010        // vendor path).
8011        // TODO grab this value from PackageSettings
8012        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8013            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8014                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8015            }
8016        }
8017
8018        // TODO: extend to support forward-locked splits
8019        String resourcePath = null;
8020        String baseResourcePath = null;
8021        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8022            if (ps != null && ps.resourcePathString != null) {
8023                resourcePath = ps.resourcePathString;
8024                baseResourcePath = ps.resourcePathString;
8025            } else {
8026                // Should not happen at all. Just log an error.
8027                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8028            }
8029        } else {
8030            resourcePath = pkg.codePath;
8031            baseResourcePath = pkg.baseCodePath;
8032        }
8033
8034        // Set application objects path explicitly.
8035        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8036        pkg.setApplicationInfoCodePath(pkg.codePath);
8037        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8038        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8039        pkg.setApplicationInfoResourcePath(resourcePath);
8040        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8041        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8042
8043        final int userId = ((user == null) ? 0 : user.getIdentifier());
8044        if (ps != null && ps.getInstantApp(userId)) {
8045            scanFlags |= SCAN_AS_INSTANT_APP;
8046        }
8047
8048        // Note that we invoke the following method only if we are about to unpack an application
8049        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8050                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8051
8052        /*
8053         * If the system app should be overridden by a previously installed
8054         * data, hide the system app now and let the /data/app scan pick it up
8055         * again.
8056         */
8057        if (shouldHideSystemApp) {
8058            synchronized (mPackages) {
8059                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8060            }
8061        }
8062
8063        return scannedPkg;
8064    }
8065
8066    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8067        // Derive the new package synthetic package name
8068        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8069                + pkg.staticSharedLibVersion);
8070    }
8071
8072    private static String fixProcessName(String defProcessName,
8073            String processName) {
8074        if (processName == null) {
8075            return defProcessName;
8076        }
8077        return processName;
8078    }
8079
8080    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8081            throws PackageManagerException {
8082        if (pkgSetting.signatures.mSignatures != null) {
8083            // Already existing package. Make sure signatures match
8084            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8085                    == PackageManager.SIGNATURE_MATCH;
8086            if (!match) {
8087                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8088                        == PackageManager.SIGNATURE_MATCH;
8089            }
8090            if (!match) {
8091                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8092                        == PackageManager.SIGNATURE_MATCH;
8093            }
8094            if (!match) {
8095                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8096                        + pkg.packageName + " signatures do not match the "
8097                        + "previously installed version; ignoring!");
8098            }
8099        }
8100
8101        // Check for shared user signatures
8102        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8103            // Already existing package. Make sure signatures match
8104            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8105                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8106            if (!match) {
8107                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8108                        == PackageManager.SIGNATURE_MATCH;
8109            }
8110            if (!match) {
8111                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8112                        == PackageManager.SIGNATURE_MATCH;
8113            }
8114            if (!match) {
8115                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8116                        "Package " + pkg.packageName
8117                        + " has no signatures that match those in shared user "
8118                        + pkgSetting.sharedUser.name + "; ignoring!");
8119            }
8120        }
8121    }
8122
8123    /**
8124     * Enforces that only the system UID or root's UID can call a method exposed
8125     * via Binder.
8126     *
8127     * @param message used as message if SecurityException is thrown
8128     * @throws SecurityException if the caller is not system or root
8129     */
8130    private static final void enforceSystemOrRoot(String message) {
8131        final int uid = Binder.getCallingUid();
8132        if (uid != Process.SYSTEM_UID && uid != 0) {
8133            throw new SecurityException(message);
8134        }
8135    }
8136
8137    @Override
8138    public void performFstrimIfNeeded() {
8139        enforceSystemOrRoot("Only the system can request fstrim");
8140
8141        // Before everything else, see whether we need to fstrim.
8142        try {
8143            IStorageManager sm = PackageHelper.getStorageManager();
8144            if (sm != null) {
8145                boolean doTrim = false;
8146                final long interval = android.provider.Settings.Global.getLong(
8147                        mContext.getContentResolver(),
8148                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8149                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8150                if (interval > 0) {
8151                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8152                    if (timeSinceLast > interval) {
8153                        doTrim = true;
8154                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8155                                + "; running immediately");
8156                    }
8157                }
8158                if (doTrim) {
8159                    final boolean dexOptDialogShown;
8160                    synchronized (mPackages) {
8161                        dexOptDialogShown = mDexOptDialogShown;
8162                    }
8163                    if (!isFirstBoot() && dexOptDialogShown) {
8164                        try {
8165                            ActivityManager.getService().showBootMessage(
8166                                    mContext.getResources().getString(
8167                                            R.string.android_upgrading_fstrim), true);
8168                        } catch (RemoteException e) {
8169                        }
8170                    }
8171                    sm.runMaintenance();
8172                }
8173            } else {
8174                Slog.e(TAG, "storageManager service unavailable!");
8175            }
8176        } catch (RemoteException e) {
8177            // Can't happen; StorageManagerService is local
8178        }
8179    }
8180
8181    @Override
8182    public void updatePackagesIfNeeded() {
8183        enforceSystemOrRoot("Only the system can request package update");
8184
8185        // We need to re-extract after an OTA.
8186        boolean causeUpgrade = isUpgrade();
8187
8188        // First boot or factory reset.
8189        // Note: we also handle devices that are upgrading to N right now as if it is their
8190        //       first boot, as they do not have profile data.
8191        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8192
8193        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8194        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8195
8196        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8197            return;
8198        }
8199
8200        List<PackageParser.Package> pkgs;
8201        synchronized (mPackages) {
8202            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8203        }
8204
8205        final long startTime = System.nanoTime();
8206        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8207                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8208
8209        final int elapsedTimeSeconds =
8210                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8211
8212        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8213        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8214        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8215        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8216        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8217    }
8218
8219    /**
8220     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8221     * containing statistics about the invocation. The array consists of three elements,
8222     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8223     * and {@code numberOfPackagesFailed}.
8224     */
8225    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8226            String compilerFilter) {
8227
8228        int numberOfPackagesVisited = 0;
8229        int numberOfPackagesOptimized = 0;
8230        int numberOfPackagesSkipped = 0;
8231        int numberOfPackagesFailed = 0;
8232        final int numberOfPackagesToDexopt = pkgs.size();
8233
8234        for (PackageParser.Package pkg : pkgs) {
8235            numberOfPackagesVisited++;
8236
8237            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8238                if (DEBUG_DEXOPT) {
8239                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8240                }
8241                numberOfPackagesSkipped++;
8242                continue;
8243            }
8244
8245            if (DEBUG_DEXOPT) {
8246                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8247                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8248            }
8249
8250            if (showDialog) {
8251                try {
8252                    ActivityManager.getService().showBootMessage(
8253                            mContext.getResources().getString(R.string.android_upgrading_apk,
8254                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8255                } catch (RemoteException e) {
8256                }
8257                synchronized (mPackages) {
8258                    mDexOptDialogShown = true;
8259                }
8260            }
8261
8262            // If the OTA updates a system app which was previously preopted to a non-preopted state
8263            // the app might end up being verified at runtime. That's because by default the apps
8264            // are verify-profile but for preopted apps there's no profile.
8265            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8266            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8267            // filter (by default interpret-only).
8268            // Note that at this stage unused apps are already filtered.
8269            if (isSystemApp(pkg) &&
8270                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8271                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8272                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8273            }
8274
8275            // checkProfiles is false to avoid merging profiles during boot which
8276            // might interfere with background compilation (b/28612421).
8277            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8278            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8279            // trade-off worth doing to save boot time work.
8280            int dexOptStatus = performDexOptTraced(pkg.packageName,
8281                    false /* checkProfiles */,
8282                    compilerFilter,
8283                    false /* force */);
8284            switch (dexOptStatus) {
8285                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8286                    numberOfPackagesOptimized++;
8287                    break;
8288                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8289                    numberOfPackagesSkipped++;
8290                    break;
8291                case PackageDexOptimizer.DEX_OPT_FAILED:
8292                    numberOfPackagesFailed++;
8293                    break;
8294                default:
8295                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8296                    break;
8297            }
8298        }
8299
8300        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8301                numberOfPackagesFailed };
8302    }
8303
8304    @Override
8305    public void notifyPackageUse(String packageName, int reason) {
8306        synchronized (mPackages) {
8307            PackageParser.Package p = mPackages.get(packageName);
8308            if (p == null) {
8309                return;
8310            }
8311            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8312        }
8313    }
8314
8315    @Override
8316    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8317        int userId = UserHandle.getCallingUserId();
8318        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8319        if (ai == null) {
8320            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8321                + loadingPackageName + ", user=" + userId);
8322            return;
8323        }
8324        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8325    }
8326
8327    // TODO: this is not used nor needed. Delete it.
8328    @Override
8329    public boolean performDexOptIfNeeded(String packageName) {
8330        int dexOptStatus = performDexOptTraced(packageName,
8331                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8332        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8333    }
8334
8335    @Override
8336    public boolean performDexOpt(String packageName,
8337            boolean checkProfiles, int compileReason, boolean force) {
8338        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8339                getCompilerFilterForReason(compileReason), force);
8340        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8341    }
8342
8343    @Override
8344    public boolean performDexOptMode(String packageName,
8345            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8346        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8347                targetCompilerFilter, force);
8348        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8349    }
8350
8351    private int performDexOptTraced(String packageName,
8352                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8353        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8354        try {
8355            return performDexOptInternal(packageName, checkProfiles,
8356                    targetCompilerFilter, force);
8357        } finally {
8358            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8359        }
8360    }
8361
8362    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8363    // if the package can now be considered up to date for the given filter.
8364    private int performDexOptInternal(String packageName,
8365                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8366        PackageParser.Package p;
8367        synchronized (mPackages) {
8368            p = mPackages.get(packageName);
8369            if (p == null) {
8370                // Package could not be found. Report failure.
8371                return PackageDexOptimizer.DEX_OPT_FAILED;
8372            }
8373            mPackageUsage.maybeWriteAsync(mPackages);
8374            mCompilerStats.maybeWriteAsync();
8375        }
8376        long callingId = Binder.clearCallingIdentity();
8377        try {
8378            synchronized (mInstallLock) {
8379                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8380                        targetCompilerFilter, force);
8381            }
8382        } finally {
8383            Binder.restoreCallingIdentity(callingId);
8384        }
8385    }
8386
8387    public ArraySet<String> getOptimizablePackages() {
8388        ArraySet<String> pkgs = new ArraySet<String>();
8389        synchronized (mPackages) {
8390            for (PackageParser.Package p : mPackages.values()) {
8391                if (PackageDexOptimizer.canOptimizePackage(p)) {
8392                    pkgs.add(p.packageName);
8393                }
8394            }
8395        }
8396        return pkgs;
8397    }
8398
8399    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8400            boolean checkProfiles, String targetCompilerFilter,
8401            boolean force) {
8402        // Select the dex optimizer based on the force parameter.
8403        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8404        //       allocate an object here.
8405        PackageDexOptimizer pdo = force
8406                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8407                : mPackageDexOptimizer;
8408
8409        // Dexopt all dependencies first. Note: we ignore the return value and march on
8410        // on errors.
8411        // Note that we are going to call performDexOpt on those libraries as many times as
8412        // they are referenced in packages. When we do a batch of performDexOpt (for example
8413        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8414        // and the first package that uses the library will dexopt it. The
8415        // others will see that the compiled code for the library is up to date.
8416        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8417        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8418        if (!deps.isEmpty()) {
8419            for (PackageParser.Package depPackage : deps) {
8420                // TODO: Analyze and investigate if we (should) profile libraries.
8421                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8422                        false /* checkProfiles */,
8423                        targetCompilerFilter,
8424                        getOrCreateCompilerPackageStats(depPackage),
8425                        true /* isUsedByOtherApps */);
8426            }
8427        }
8428        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8429                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8430                mDexManager.isUsedByOtherApps(p.packageName));
8431    }
8432
8433    // Performs dexopt on the used secondary dex files belonging to the given package.
8434    // Returns true if all dex files were process successfully (which could mean either dexopt or
8435    // skip). Returns false if any of the files caused errors.
8436    @Override
8437    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8438            boolean force) {
8439        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8440    }
8441
8442    public boolean performDexOptSecondary(String packageName, int compileReason,
8443            boolean force) {
8444        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8445    }
8446
8447    /**
8448     * Reconcile the information we have about the secondary dex files belonging to
8449     * {@code packagName} and the actual dex files. For all dex files that were
8450     * deleted, update the internal records and delete the generated oat files.
8451     */
8452    @Override
8453    public void reconcileSecondaryDexFiles(String packageName) {
8454        mDexManager.reconcileSecondaryDexFiles(packageName);
8455    }
8456
8457    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8458    // a reference there.
8459    /*package*/ DexManager getDexManager() {
8460        return mDexManager;
8461    }
8462
8463    /**
8464     * Execute the background dexopt job immediately.
8465     */
8466    @Override
8467    public boolean runBackgroundDexoptJob() {
8468        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8469    }
8470
8471    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8472        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8473                || p.usesStaticLibraries != null) {
8474            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8475            Set<String> collectedNames = new HashSet<>();
8476            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8477
8478            retValue.remove(p);
8479
8480            return retValue;
8481        } else {
8482            return Collections.emptyList();
8483        }
8484    }
8485
8486    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8487            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8488        if (!collectedNames.contains(p.packageName)) {
8489            collectedNames.add(p.packageName);
8490            collected.add(p);
8491
8492            if (p.usesLibraries != null) {
8493                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8494                        null, collected, collectedNames);
8495            }
8496            if (p.usesOptionalLibraries != null) {
8497                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8498                        null, collected, collectedNames);
8499            }
8500            if (p.usesStaticLibraries != null) {
8501                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8502                        p.usesStaticLibrariesVersions, collected, collectedNames);
8503            }
8504        }
8505    }
8506
8507    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8508            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8509        final int libNameCount = libs.size();
8510        for (int i = 0; i < libNameCount; i++) {
8511            String libName = libs.get(i);
8512            int version = (versions != null && versions.length == libNameCount)
8513                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8514            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8515            if (libPkg != null) {
8516                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8517            }
8518        }
8519    }
8520
8521    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8522        synchronized (mPackages) {
8523            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8524            if (libEntry != null) {
8525                return mPackages.get(libEntry.apk);
8526            }
8527            return null;
8528        }
8529    }
8530
8531    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8532        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8533        if (versionedLib == null) {
8534            return null;
8535        }
8536        return versionedLib.get(version);
8537    }
8538
8539    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8540        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8541                pkg.staticSharedLibName);
8542        if (versionedLib == null) {
8543            return null;
8544        }
8545        int previousLibVersion = -1;
8546        final int versionCount = versionedLib.size();
8547        for (int i = 0; i < versionCount; i++) {
8548            final int libVersion = versionedLib.keyAt(i);
8549            if (libVersion < pkg.staticSharedLibVersion) {
8550                previousLibVersion = Math.max(previousLibVersion, libVersion);
8551            }
8552        }
8553        if (previousLibVersion >= 0) {
8554            return versionedLib.get(previousLibVersion);
8555        }
8556        return null;
8557    }
8558
8559    public void shutdown() {
8560        mPackageUsage.writeNow(mPackages);
8561        mCompilerStats.writeNow();
8562    }
8563
8564    @Override
8565    public void dumpProfiles(String packageName) {
8566        PackageParser.Package pkg;
8567        synchronized (mPackages) {
8568            pkg = mPackages.get(packageName);
8569            if (pkg == null) {
8570                throw new IllegalArgumentException("Unknown package: " + packageName);
8571            }
8572        }
8573        /* Only the shell, root, or the app user should be able to dump profiles. */
8574        int callingUid = Binder.getCallingUid();
8575        if (callingUid != Process.SHELL_UID &&
8576            callingUid != Process.ROOT_UID &&
8577            callingUid != pkg.applicationInfo.uid) {
8578            throw new SecurityException("dumpProfiles");
8579        }
8580
8581        synchronized (mInstallLock) {
8582            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8583            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8584            try {
8585                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8586                String codePaths = TextUtils.join(";", allCodePaths);
8587                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8588            } catch (InstallerException e) {
8589                Slog.w(TAG, "Failed to dump profiles", e);
8590            }
8591            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8592        }
8593    }
8594
8595    @Override
8596    public void forceDexOpt(String packageName) {
8597        enforceSystemOrRoot("forceDexOpt");
8598
8599        PackageParser.Package pkg;
8600        synchronized (mPackages) {
8601            pkg = mPackages.get(packageName);
8602            if (pkg == null) {
8603                throw new IllegalArgumentException("Unknown package: " + packageName);
8604            }
8605        }
8606
8607        synchronized (mInstallLock) {
8608            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8609
8610            // Whoever is calling forceDexOpt wants a fully compiled package.
8611            // Don't use profiles since that may cause compilation to be skipped.
8612            final int res = performDexOptInternalWithDependenciesLI(pkg,
8613                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8614                    true /* force */);
8615
8616            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8617            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8618                throw new IllegalStateException("Failed to dexopt: " + res);
8619            }
8620        }
8621    }
8622
8623    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8624        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8625            Slog.w(TAG, "Unable to update from " + oldPkg.name
8626                    + " to " + newPkg.packageName
8627                    + ": old package not in system partition");
8628            return false;
8629        } else if (mPackages.get(oldPkg.name) != null) {
8630            Slog.w(TAG, "Unable to update from " + oldPkg.name
8631                    + " to " + newPkg.packageName
8632                    + ": old package still exists");
8633            return false;
8634        }
8635        return true;
8636    }
8637
8638    void removeCodePathLI(File codePath) {
8639        if (codePath.isDirectory()) {
8640            try {
8641                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8642            } catch (InstallerException e) {
8643                Slog.w(TAG, "Failed to remove code path", e);
8644            }
8645        } else {
8646            codePath.delete();
8647        }
8648    }
8649
8650    private int[] resolveUserIds(int userId) {
8651        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8652    }
8653
8654    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8655        if (pkg == null) {
8656            Slog.wtf(TAG, "Package was null!", new Throwable());
8657            return;
8658        }
8659        clearAppDataLeafLIF(pkg, userId, flags);
8660        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8661        for (int i = 0; i < childCount; i++) {
8662            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8663        }
8664    }
8665
8666    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8667        final PackageSetting ps;
8668        synchronized (mPackages) {
8669            ps = mSettings.mPackages.get(pkg.packageName);
8670        }
8671        for (int realUserId : resolveUserIds(userId)) {
8672            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8673            try {
8674                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8675                        ceDataInode);
8676            } catch (InstallerException e) {
8677                Slog.w(TAG, String.valueOf(e));
8678            }
8679        }
8680    }
8681
8682    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8683        if (pkg == null) {
8684            Slog.wtf(TAG, "Package was null!", new Throwable());
8685            return;
8686        }
8687        destroyAppDataLeafLIF(pkg, userId, flags);
8688        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8689        for (int i = 0; i < childCount; i++) {
8690            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8691        }
8692    }
8693
8694    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8695        final PackageSetting ps;
8696        synchronized (mPackages) {
8697            ps = mSettings.mPackages.get(pkg.packageName);
8698        }
8699        for (int realUserId : resolveUserIds(userId)) {
8700            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8701            try {
8702                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8703                        ceDataInode);
8704            } catch (InstallerException e) {
8705                Slog.w(TAG, String.valueOf(e));
8706            }
8707            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8708        }
8709    }
8710
8711    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8712        if (pkg == null) {
8713            Slog.wtf(TAG, "Package was null!", new Throwable());
8714            return;
8715        }
8716        destroyAppProfilesLeafLIF(pkg);
8717        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8718        for (int i = 0; i < childCount; i++) {
8719            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8720        }
8721    }
8722
8723    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8724        try {
8725            mInstaller.destroyAppProfiles(pkg.packageName);
8726        } catch (InstallerException e) {
8727            Slog.w(TAG, String.valueOf(e));
8728        }
8729    }
8730
8731    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8732        if (pkg == null) {
8733            Slog.wtf(TAG, "Package was null!", new Throwable());
8734            return;
8735        }
8736        clearAppProfilesLeafLIF(pkg);
8737        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8738        for (int i = 0; i < childCount; i++) {
8739            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8740        }
8741    }
8742
8743    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8744        try {
8745            mInstaller.clearAppProfiles(pkg.packageName);
8746        } catch (InstallerException e) {
8747            Slog.w(TAG, String.valueOf(e));
8748        }
8749    }
8750
8751    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8752            long lastUpdateTime) {
8753        // Set parent install/update time
8754        PackageSetting ps = (PackageSetting) pkg.mExtras;
8755        if (ps != null) {
8756            ps.firstInstallTime = firstInstallTime;
8757            ps.lastUpdateTime = lastUpdateTime;
8758        }
8759        // Set children install/update time
8760        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8761        for (int i = 0; i < childCount; i++) {
8762            PackageParser.Package childPkg = pkg.childPackages.get(i);
8763            ps = (PackageSetting) childPkg.mExtras;
8764            if (ps != null) {
8765                ps.firstInstallTime = firstInstallTime;
8766                ps.lastUpdateTime = lastUpdateTime;
8767            }
8768        }
8769    }
8770
8771    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8772            PackageParser.Package changingLib) {
8773        if (file.path != null) {
8774            usesLibraryFiles.add(file.path);
8775            return;
8776        }
8777        PackageParser.Package p = mPackages.get(file.apk);
8778        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8779            // If we are doing this while in the middle of updating a library apk,
8780            // then we need to make sure to use that new apk for determining the
8781            // dependencies here.  (We haven't yet finished committing the new apk
8782            // to the package manager state.)
8783            if (p == null || p.packageName.equals(changingLib.packageName)) {
8784                p = changingLib;
8785            }
8786        }
8787        if (p != null) {
8788            usesLibraryFiles.addAll(p.getAllCodePaths());
8789        }
8790    }
8791
8792    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8793            PackageParser.Package changingLib) throws PackageManagerException {
8794        if (pkg == null) {
8795            return;
8796        }
8797        ArraySet<String> usesLibraryFiles = null;
8798        if (pkg.usesLibraries != null) {
8799            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8800                    null, null, pkg.packageName, changingLib, true, null);
8801        }
8802        if (pkg.usesStaticLibraries != null) {
8803            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8804                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8805                    pkg.packageName, changingLib, true, usesLibraryFiles);
8806        }
8807        if (pkg.usesOptionalLibraries != null) {
8808            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8809                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8810        }
8811        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8812            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8813        } else {
8814            pkg.usesLibraryFiles = null;
8815        }
8816    }
8817
8818    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8819            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8820            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8821            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8822            throws PackageManagerException {
8823        final int libCount = requestedLibraries.size();
8824        for (int i = 0; i < libCount; i++) {
8825            final String libName = requestedLibraries.get(i);
8826            final int libVersion = requiredVersions != null ? requiredVersions[i]
8827                    : SharedLibraryInfo.VERSION_UNDEFINED;
8828            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8829            if (libEntry == null) {
8830                if (required) {
8831                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8832                            "Package " + packageName + " requires unavailable shared library "
8833                                    + libName + "; failing!");
8834                } else {
8835                    Slog.w(TAG, "Package " + packageName
8836                            + " desires unavailable shared library "
8837                            + libName + "; ignoring!");
8838                }
8839            } else {
8840                if (requiredVersions != null && requiredCertDigests != null) {
8841                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8842                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8843                            "Package " + packageName + " requires unavailable static shared"
8844                                    + " library " + libName + " version "
8845                                    + libEntry.info.getVersion() + "; failing!");
8846                    }
8847
8848                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8849                    if (libPkg == null) {
8850                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8851                                "Package " + packageName + " requires unavailable static shared"
8852                                        + " library; failing!");
8853                    }
8854
8855                    String expectedCertDigest = requiredCertDigests[i];
8856                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8857                                libPkg.mSignatures[0]);
8858                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8859                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8860                                "Package " + packageName + " requires differently signed" +
8861                                        " static shared library; failing!");
8862                    }
8863                }
8864
8865                if (outUsedLibraries == null) {
8866                    outUsedLibraries = new ArraySet<>();
8867                }
8868                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8869            }
8870        }
8871        return outUsedLibraries;
8872    }
8873
8874    private static boolean hasString(List<String> list, List<String> which) {
8875        if (list == null) {
8876            return false;
8877        }
8878        for (int i=list.size()-1; i>=0; i--) {
8879            for (int j=which.size()-1; j>=0; j--) {
8880                if (which.get(j).equals(list.get(i))) {
8881                    return true;
8882                }
8883            }
8884        }
8885        return false;
8886    }
8887
8888    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8889            PackageParser.Package changingPkg) {
8890        ArrayList<PackageParser.Package> res = null;
8891        for (PackageParser.Package pkg : mPackages.values()) {
8892            if (changingPkg != null
8893                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8894                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8895                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8896                            changingPkg.staticSharedLibName)) {
8897                return null;
8898            }
8899            if (res == null) {
8900                res = new ArrayList<>();
8901            }
8902            res.add(pkg);
8903            try {
8904                updateSharedLibrariesLPr(pkg, changingPkg);
8905            } catch (PackageManagerException e) {
8906                // If a system app update or an app and a required lib missing we
8907                // delete the package and for updated system apps keep the data as
8908                // it is better for the user to reinstall than to be in an limbo
8909                // state. Also libs disappearing under an app should never happen
8910                // - just in case.
8911                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8912                    final int flags = pkg.isUpdatedSystemApp()
8913                            ? PackageManager.DELETE_KEEP_DATA : 0;
8914                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8915                            flags , null, true, null);
8916                }
8917                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8918            }
8919        }
8920        return res;
8921    }
8922
8923    /**
8924     * Derive the value of the {@code cpuAbiOverride} based on the provided
8925     * value and an optional stored value from the package settings.
8926     */
8927    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8928        String cpuAbiOverride = null;
8929
8930        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8931            cpuAbiOverride = null;
8932        } else if (abiOverride != null) {
8933            cpuAbiOverride = abiOverride;
8934        } else if (settings != null) {
8935            cpuAbiOverride = settings.cpuAbiOverrideString;
8936        }
8937
8938        return cpuAbiOverride;
8939    }
8940
8941    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8942            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8943                    throws PackageManagerException {
8944        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8945        // If the package has children and this is the first dive in the function
8946        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8947        // whether all packages (parent and children) would be successfully scanned
8948        // before the actual scan since scanning mutates internal state and we want
8949        // to atomically install the package and its children.
8950        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8951            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8952                scanFlags |= SCAN_CHECK_ONLY;
8953            }
8954        } else {
8955            scanFlags &= ~SCAN_CHECK_ONLY;
8956        }
8957
8958        final PackageParser.Package scannedPkg;
8959        try {
8960            // Scan the parent
8961            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8962            // Scan the children
8963            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8964            for (int i = 0; i < childCount; i++) {
8965                PackageParser.Package childPkg = pkg.childPackages.get(i);
8966                scanPackageLI(childPkg, policyFlags,
8967                        scanFlags, currentTime, user);
8968            }
8969        } finally {
8970            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8971        }
8972
8973        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8974            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8975        }
8976
8977        return scannedPkg;
8978    }
8979
8980    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8981            int scanFlags, long currentTime, @Nullable UserHandle user)
8982                    throws PackageManagerException {
8983        boolean success = false;
8984        try {
8985            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8986                    currentTime, user);
8987            success = true;
8988            return res;
8989        } finally {
8990            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8991                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8992                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8993                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8994                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8995            }
8996        }
8997    }
8998
8999    /**
9000     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9001     */
9002    private static boolean apkHasCode(String fileName) {
9003        StrictJarFile jarFile = null;
9004        try {
9005            jarFile = new StrictJarFile(fileName,
9006                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9007            return jarFile.findEntry("classes.dex") != null;
9008        } catch (IOException ignore) {
9009        } finally {
9010            try {
9011                if (jarFile != null) {
9012                    jarFile.close();
9013                }
9014            } catch (IOException ignore) {}
9015        }
9016        return false;
9017    }
9018
9019    /**
9020     * Enforces code policy for the package. This ensures that if an APK has
9021     * declared hasCode="true" in its manifest that the APK actually contains
9022     * code.
9023     *
9024     * @throws PackageManagerException If bytecode could not be found when it should exist
9025     */
9026    private static void assertCodePolicy(PackageParser.Package pkg)
9027            throws PackageManagerException {
9028        final boolean shouldHaveCode =
9029                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9030        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9031            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9032                    "Package " + pkg.baseCodePath + " code is missing");
9033        }
9034
9035        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9036            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9037                final boolean splitShouldHaveCode =
9038                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9039                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9040                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9041                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9042                }
9043            }
9044        }
9045    }
9046
9047    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9048            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9049                    throws PackageManagerException {
9050        if (DEBUG_PACKAGE_SCANNING) {
9051            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9052                Log.d(TAG, "Scanning package " + pkg.packageName);
9053        }
9054
9055        applyPolicy(pkg, policyFlags);
9056
9057        assertPackageIsValid(pkg, policyFlags, scanFlags);
9058
9059        // Initialize package source and resource directories
9060        final File scanFile = new File(pkg.codePath);
9061        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9062        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9063
9064        SharedUserSetting suid = null;
9065        PackageSetting pkgSetting = null;
9066
9067        // Getting the package setting may have a side-effect, so if we
9068        // are only checking if scan would succeed, stash a copy of the
9069        // old setting to restore at the end.
9070        PackageSetting nonMutatedPs = null;
9071
9072        // We keep references to the derived CPU Abis from settings in oder to reuse
9073        // them in the case where we're not upgrading or booting for the first time.
9074        String primaryCpuAbiFromSettings = null;
9075        String secondaryCpuAbiFromSettings = null;
9076
9077        // writer
9078        synchronized (mPackages) {
9079            if (pkg.mSharedUserId != null) {
9080                // SIDE EFFECTS; may potentially allocate a new shared user
9081                suid = mSettings.getSharedUserLPw(
9082                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9083                if (DEBUG_PACKAGE_SCANNING) {
9084                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9085                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9086                                + "): packages=" + suid.packages);
9087                }
9088            }
9089
9090            // Check if we are renaming from an original package name.
9091            PackageSetting origPackage = null;
9092            String realName = null;
9093            if (pkg.mOriginalPackages != null) {
9094                // This package may need to be renamed to a previously
9095                // installed name.  Let's check on that...
9096                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9097                if (pkg.mOriginalPackages.contains(renamed)) {
9098                    // This package had originally been installed as the
9099                    // original name, and we have already taken care of
9100                    // transitioning to the new one.  Just update the new
9101                    // one to continue using the old name.
9102                    realName = pkg.mRealPackage;
9103                    if (!pkg.packageName.equals(renamed)) {
9104                        // Callers into this function may have already taken
9105                        // care of renaming the package; only do it here if
9106                        // it is not already done.
9107                        pkg.setPackageName(renamed);
9108                    }
9109                } else {
9110                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9111                        if ((origPackage = mSettings.getPackageLPr(
9112                                pkg.mOriginalPackages.get(i))) != null) {
9113                            // We do have the package already installed under its
9114                            // original name...  should we use it?
9115                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9116                                // New package is not compatible with original.
9117                                origPackage = null;
9118                                continue;
9119                            } else if (origPackage.sharedUser != null) {
9120                                // Make sure uid is compatible between packages.
9121                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9122                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9123                                            + " to " + pkg.packageName + ": old uid "
9124                                            + origPackage.sharedUser.name
9125                                            + " differs from " + pkg.mSharedUserId);
9126                                    origPackage = null;
9127                                    continue;
9128                                }
9129                                // TODO: Add case when shared user id is added [b/28144775]
9130                            } else {
9131                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9132                                        + pkg.packageName + " to old name " + origPackage.name);
9133                            }
9134                            break;
9135                        }
9136                    }
9137                }
9138            }
9139
9140            if (mTransferedPackages.contains(pkg.packageName)) {
9141                Slog.w(TAG, "Package " + pkg.packageName
9142                        + " was transferred to another, but its .apk remains");
9143            }
9144
9145            // See comments in nonMutatedPs declaration
9146            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9147                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9148                if (foundPs != null) {
9149                    nonMutatedPs = new PackageSetting(foundPs);
9150                }
9151            }
9152
9153            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9154                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9155                if (foundPs != null) {
9156                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9157                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9158                }
9159            }
9160
9161            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9162            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9163                PackageManagerService.reportSettingsProblem(Log.WARN,
9164                        "Package " + pkg.packageName + " shared user changed from "
9165                                + (pkgSetting.sharedUser != null
9166                                        ? pkgSetting.sharedUser.name : "<nothing>")
9167                                + " to "
9168                                + (suid != null ? suid.name : "<nothing>")
9169                                + "; replacing with new");
9170                pkgSetting = null;
9171            }
9172            final PackageSetting oldPkgSetting =
9173                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9174            final PackageSetting disabledPkgSetting =
9175                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9176
9177            String[] usesStaticLibraries = null;
9178            if (pkg.usesStaticLibraries != null) {
9179                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9180                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9181            }
9182
9183            if (pkgSetting == null) {
9184                final String parentPackageName = (pkg.parentPackage != null)
9185                        ? pkg.parentPackage.packageName : null;
9186                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9187                // REMOVE SharedUserSetting from method; update in a separate call
9188                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9189                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9190                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9191                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9192                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9193                        true /*allowInstall*/, instantApp, parentPackageName,
9194                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9195                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9196                // SIDE EFFECTS; updates system state; move elsewhere
9197                if (origPackage != null) {
9198                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9199                }
9200                mSettings.addUserToSettingLPw(pkgSetting);
9201            } else {
9202                // REMOVE SharedUserSetting from method; update in a separate call.
9203                //
9204                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9205                // secondaryCpuAbi are not known at this point so we always update them
9206                // to null here, only to reset them at a later point.
9207                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9208                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9209                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9210                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9211                        UserManagerService.getInstance(), usesStaticLibraries,
9212                        pkg.usesStaticLibrariesVersions);
9213            }
9214            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9215            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9216
9217            // SIDE EFFECTS; modifies system state; move elsewhere
9218            if (pkgSetting.origPackage != null) {
9219                // If we are first transitioning from an original package,
9220                // fix up the new package's name now.  We need to do this after
9221                // looking up the package under its new name, so getPackageLP
9222                // can take care of fiddling things correctly.
9223                pkg.setPackageName(origPackage.name);
9224
9225                // File a report about this.
9226                String msg = "New package " + pkgSetting.realName
9227                        + " renamed to replace old package " + pkgSetting.name;
9228                reportSettingsProblem(Log.WARN, msg);
9229
9230                // Make a note of it.
9231                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9232                    mTransferedPackages.add(origPackage.name);
9233                }
9234
9235                // No longer need to retain this.
9236                pkgSetting.origPackage = null;
9237            }
9238
9239            // SIDE EFFECTS; modifies system state; move elsewhere
9240            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9241                // Make a note of it.
9242                mTransferedPackages.add(pkg.packageName);
9243            }
9244
9245            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9246                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9247            }
9248
9249            if ((scanFlags & SCAN_BOOTING) == 0
9250                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9251                // Check all shared libraries and map to their actual file path.
9252                // We only do this here for apps not on a system dir, because those
9253                // are the only ones that can fail an install due to this.  We
9254                // will take care of the system apps by updating all of their
9255                // library paths after the scan is done. Also during the initial
9256                // scan don't update any libs as we do this wholesale after all
9257                // apps are scanned to avoid dependency based scanning.
9258                updateSharedLibrariesLPr(pkg, null);
9259            }
9260
9261            if (mFoundPolicyFile) {
9262                SELinuxMMAC.assignSeInfoValue(pkg);
9263            }
9264            pkg.applicationInfo.uid = pkgSetting.appId;
9265            pkg.mExtras = pkgSetting;
9266
9267
9268            // Static shared libs have same package with different versions where
9269            // we internally use a synthetic package name to allow multiple versions
9270            // of the same package, therefore we need to compare signatures against
9271            // the package setting for the latest library version.
9272            PackageSetting signatureCheckPs = pkgSetting;
9273            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9274                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9275                if (libraryEntry != null) {
9276                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9277                }
9278            }
9279
9280            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9281                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9282                    // We just determined the app is signed correctly, so bring
9283                    // over the latest parsed certs.
9284                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9285                } else {
9286                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9287                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9288                                "Package " + pkg.packageName + " upgrade keys do not match the "
9289                                + "previously installed version");
9290                    } else {
9291                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9292                        String msg = "System package " + pkg.packageName
9293                                + " signature changed; retaining data.";
9294                        reportSettingsProblem(Log.WARN, msg);
9295                    }
9296                }
9297            } else {
9298                try {
9299                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9300                    verifySignaturesLP(signatureCheckPs, pkg);
9301                    // We just determined the app is signed correctly, so bring
9302                    // over the latest parsed certs.
9303                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9304                } catch (PackageManagerException e) {
9305                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9306                        throw e;
9307                    }
9308                    // The signature has changed, but this package is in the system
9309                    // image...  let's recover!
9310                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9311                    // However...  if this package is part of a shared user, but it
9312                    // doesn't match the signature of the shared user, let's fail.
9313                    // What this means is that you can't change the signatures
9314                    // associated with an overall shared user, which doesn't seem all
9315                    // that unreasonable.
9316                    if (signatureCheckPs.sharedUser != null) {
9317                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9318                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9319                            throw new PackageManagerException(
9320                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9321                                    "Signature mismatch for shared user: "
9322                                            + pkgSetting.sharedUser);
9323                        }
9324                    }
9325                    // File a report about this.
9326                    String msg = "System package " + pkg.packageName
9327                            + " signature changed; retaining data.";
9328                    reportSettingsProblem(Log.WARN, msg);
9329                }
9330            }
9331
9332            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9333                // This package wants to adopt ownership of permissions from
9334                // another package.
9335                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9336                    final String origName = pkg.mAdoptPermissions.get(i);
9337                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9338                    if (orig != null) {
9339                        if (verifyPackageUpdateLPr(orig, pkg)) {
9340                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9341                                    + pkg.packageName);
9342                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9343                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9344                        }
9345                    }
9346                }
9347            }
9348        }
9349
9350        pkg.applicationInfo.processName = fixProcessName(
9351                pkg.applicationInfo.packageName,
9352                pkg.applicationInfo.processName);
9353
9354        if (pkg != mPlatformPackage) {
9355            // Get all of our default paths setup
9356            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9357        }
9358
9359        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9360
9361        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9362            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9363                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9364                derivePackageAbi(
9365                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9366                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9367
9368                // Some system apps still use directory structure for native libraries
9369                // in which case we might end up not detecting abi solely based on apk
9370                // structure. Try to detect abi based on directory structure.
9371                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9372                        pkg.applicationInfo.primaryCpuAbi == null) {
9373                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9374                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9375                }
9376            } else {
9377                // This is not a first boot or an upgrade, don't bother deriving the
9378                // ABI during the scan. Instead, trust the value that was stored in the
9379                // package setting.
9380                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9381                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9382
9383                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9384
9385                if (DEBUG_ABI_SELECTION) {
9386                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9387                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9388                        pkg.applicationInfo.secondaryCpuAbi);
9389                }
9390            }
9391        } else {
9392            if ((scanFlags & SCAN_MOVE) != 0) {
9393                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9394                // but we already have this packages package info in the PackageSetting. We just
9395                // use that and derive the native library path based on the new codepath.
9396                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9397                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9398            }
9399
9400            // Set native library paths again. For moves, the path will be updated based on the
9401            // ABIs we've determined above. For non-moves, the path will be updated based on the
9402            // ABIs we determined during compilation, but the path will depend on the final
9403            // package path (after the rename away from the stage path).
9404            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9405        }
9406
9407        // This is a special case for the "system" package, where the ABI is
9408        // dictated by the zygote configuration (and init.rc). We should keep track
9409        // of this ABI so that we can deal with "normal" applications that run under
9410        // the same UID correctly.
9411        if (mPlatformPackage == pkg) {
9412            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9413                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9414        }
9415
9416        // If there's a mismatch between the abi-override in the package setting
9417        // and the abiOverride specified for the install. Warn about this because we
9418        // would've already compiled the app without taking the package setting into
9419        // account.
9420        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9421            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9422                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9423                        " for package " + pkg.packageName);
9424            }
9425        }
9426
9427        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9428        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9429        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9430
9431        // Copy the derived override back to the parsed package, so that we can
9432        // update the package settings accordingly.
9433        pkg.cpuAbiOverride = cpuAbiOverride;
9434
9435        if (DEBUG_ABI_SELECTION) {
9436            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9437                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9438                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9439        }
9440
9441        // Push the derived path down into PackageSettings so we know what to
9442        // clean up at uninstall time.
9443        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9444
9445        if (DEBUG_ABI_SELECTION) {
9446            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9447                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9448                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9449        }
9450
9451        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9452        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9453            // We don't do this here during boot because we can do it all
9454            // at once after scanning all existing packages.
9455            //
9456            // We also do this *before* we perform dexopt on this package, so that
9457            // we can avoid redundant dexopts, and also to make sure we've got the
9458            // code and package path correct.
9459            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9460        }
9461
9462        if (mFactoryTest && pkg.requestedPermissions.contains(
9463                android.Manifest.permission.FACTORY_TEST)) {
9464            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9465        }
9466
9467        if (isSystemApp(pkg)) {
9468            pkgSetting.isOrphaned = true;
9469        }
9470
9471        // Take care of first install / last update times.
9472        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9473        if (currentTime != 0) {
9474            if (pkgSetting.firstInstallTime == 0) {
9475                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9476            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9477                pkgSetting.lastUpdateTime = currentTime;
9478            }
9479        } else if (pkgSetting.firstInstallTime == 0) {
9480            // We need *something*.  Take time time stamp of the file.
9481            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9482        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9483            if (scanFileTime != pkgSetting.timeStamp) {
9484                // A package on the system image has changed; consider this
9485                // to be an update.
9486                pkgSetting.lastUpdateTime = scanFileTime;
9487            }
9488        }
9489        pkgSetting.setTimeStamp(scanFileTime);
9490
9491        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9492            if (nonMutatedPs != null) {
9493                synchronized (mPackages) {
9494                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9495                }
9496            }
9497        } else {
9498            final int userId = user == null ? 0 : user.getIdentifier();
9499            // Modify state for the given package setting
9500            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9501                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9502            if (pkgSetting.getInstantApp(userId)) {
9503                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9504            }
9505        }
9506        return pkg;
9507    }
9508
9509    /**
9510     * Applies policy to the parsed package based upon the given policy flags.
9511     * Ensures the package is in a good state.
9512     * <p>
9513     * Implementation detail: This method must NOT have any side effect. It would
9514     * ideally be static, but, it requires locks to read system state.
9515     */
9516    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9517        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9518            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9519            if (pkg.applicationInfo.isDirectBootAware()) {
9520                // we're direct boot aware; set for all components
9521                for (PackageParser.Service s : pkg.services) {
9522                    s.info.encryptionAware = s.info.directBootAware = true;
9523                }
9524                for (PackageParser.Provider p : pkg.providers) {
9525                    p.info.encryptionAware = p.info.directBootAware = true;
9526                }
9527                for (PackageParser.Activity a : pkg.activities) {
9528                    a.info.encryptionAware = a.info.directBootAware = true;
9529                }
9530                for (PackageParser.Activity r : pkg.receivers) {
9531                    r.info.encryptionAware = r.info.directBootAware = true;
9532                }
9533            }
9534        } else {
9535            // Only allow system apps to be flagged as core apps.
9536            pkg.coreApp = false;
9537            // clear flags not applicable to regular apps
9538            pkg.applicationInfo.privateFlags &=
9539                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9540            pkg.applicationInfo.privateFlags &=
9541                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9542        }
9543        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9544
9545        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9546            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9547        }
9548
9549        if (!isSystemApp(pkg)) {
9550            // Only system apps can use these features.
9551            pkg.mOriginalPackages = null;
9552            pkg.mRealPackage = null;
9553            pkg.mAdoptPermissions = null;
9554        }
9555    }
9556
9557    /**
9558     * Asserts the parsed package is valid according to the given policy. If the
9559     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9560     * <p>
9561     * Implementation detail: This method must NOT have any side effects. It would
9562     * ideally be static, but, it requires locks to read system state.
9563     *
9564     * @throws PackageManagerException If the package fails any of the validation checks
9565     */
9566    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9567            throws PackageManagerException {
9568        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9569            assertCodePolicy(pkg);
9570        }
9571
9572        if (pkg.applicationInfo.getCodePath() == null ||
9573                pkg.applicationInfo.getResourcePath() == null) {
9574            // Bail out. The resource and code paths haven't been set.
9575            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9576                    "Code and resource paths haven't been set correctly");
9577        }
9578
9579        // Make sure we're not adding any bogus keyset info
9580        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9581        ksms.assertScannedPackageValid(pkg);
9582
9583        synchronized (mPackages) {
9584            // The special "android" package can only be defined once
9585            if (pkg.packageName.equals("android")) {
9586                if (mAndroidApplication != null) {
9587                    Slog.w(TAG, "*************************************************");
9588                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9589                    Slog.w(TAG, " codePath=" + pkg.codePath);
9590                    Slog.w(TAG, "*************************************************");
9591                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9592                            "Core android package being redefined.  Skipping.");
9593                }
9594            }
9595
9596            // A package name must be unique; don't allow duplicates
9597            if (mPackages.containsKey(pkg.packageName)) {
9598                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9599                        "Application package " + pkg.packageName
9600                        + " already installed.  Skipping duplicate.");
9601            }
9602
9603            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9604                // Static libs have a synthetic package name containing the version
9605                // but we still want the base name to be unique.
9606                if (mPackages.containsKey(pkg.manifestPackageName)) {
9607                    throw new PackageManagerException(
9608                            "Duplicate static shared lib provider package");
9609                }
9610
9611                // Static shared libraries should have at least O target SDK
9612                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9613                    throw new PackageManagerException(
9614                            "Packages declaring static-shared libs must target O SDK or higher");
9615                }
9616
9617                // Package declaring static a shared lib cannot be instant apps
9618                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9619                    throw new PackageManagerException(
9620                            "Packages declaring static-shared libs cannot be instant apps");
9621                }
9622
9623                // Package declaring static a shared lib cannot be renamed since the package
9624                // name is synthetic and apps can't code around package manager internals.
9625                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9626                    throw new PackageManagerException(
9627                            "Packages declaring static-shared libs cannot be renamed");
9628                }
9629
9630                // Package declaring static a shared lib cannot declare child packages
9631                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9632                    throw new PackageManagerException(
9633                            "Packages declaring static-shared libs cannot have child packages");
9634                }
9635
9636                // Package declaring static a shared lib cannot declare dynamic libs
9637                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9638                    throw new PackageManagerException(
9639                            "Packages declaring static-shared libs cannot declare dynamic libs");
9640                }
9641
9642                // Package declaring static a shared lib cannot declare shared users
9643                if (pkg.mSharedUserId != null) {
9644                    throw new PackageManagerException(
9645                            "Packages declaring static-shared libs cannot declare shared users");
9646                }
9647
9648                // Static shared libs cannot declare activities
9649                if (!pkg.activities.isEmpty()) {
9650                    throw new PackageManagerException(
9651                            "Static shared libs cannot declare activities");
9652                }
9653
9654                // Static shared libs cannot declare services
9655                if (!pkg.services.isEmpty()) {
9656                    throw new PackageManagerException(
9657                            "Static shared libs cannot declare services");
9658                }
9659
9660                // Static shared libs cannot declare providers
9661                if (!pkg.providers.isEmpty()) {
9662                    throw new PackageManagerException(
9663                            "Static shared libs cannot declare content providers");
9664                }
9665
9666                // Static shared libs cannot declare receivers
9667                if (!pkg.receivers.isEmpty()) {
9668                    throw new PackageManagerException(
9669                            "Static shared libs cannot declare broadcast receivers");
9670                }
9671
9672                // Static shared libs cannot declare permission groups
9673                if (!pkg.permissionGroups.isEmpty()) {
9674                    throw new PackageManagerException(
9675                            "Static shared libs cannot declare permission groups");
9676                }
9677
9678                // Static shared libs cannot declare permissions
9679                if (!pkg.permissions.isEmpty()) {
9680                    throw new PackageManagerException(
9681                            "Static shared libs cannot declare permissions");
9682                }
9683
9684                // Static shared libs cannot declare protected broadcasts
9685                if (pkg.protectedBroadcasts != null) {
9686                    throw new PackageManagerException(
9687                            "Static shared libs cannot declare protected broadcasts");
9688                }
9689
9690                // Static shared libs cannot be overlay targets
9691                if (pkg.mOverlayTarget != null) {
9692                    throw new PackageManagerException(
9693                            "Static shared libs cannot be overlay targets");
9694                }
9695
9696                // The version codes must be ordered as lib versions
9697                int minVersionCode = Integer.MIN_VALUE;
9698                int maxVersionCode = Integer.MAX_VALUE;
9699
9700                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9701                        pkg.staticSharedLibName);
9702                if (versionedLib != null) {
9703                    final int versionCount = versionedLib.size();
9704                    for (int i = 0; i < versionCount; i++) {
9705                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9706                        // TODO: We will change version code to long, so in the new API it is long
9707                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9708                                .getVersionCode();
9709                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9710                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9711                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9712                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9713                        } else {
9714                            minVersionCode = maxVersionCode = libVersionCode;
9715                            break;
9716                        }
9717                    }
9718                }
9719                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9720                    throw new PackageManagerException("Static shared"
9721                            + " lib version codes must be ordered as lib versions");
9722                }
9723            }
9724
9725            // Only privileged apps and updated privileged apps can add child packages.
9726            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9727                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9728                    throw new PackageManagerException("Only privileged apps can add child "
9729                            + "packages. Ignoring package " + pkg.packageName);
9730                }
9731                final int childCount = pkg.childPackages.size();
9732                for (int i = 0; i < childCount; i++) {
9733                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9734                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9735                            childPkg.packageName)) {
9736                        throw new PackageManagerException("Can't override child of "
9737                                + "another disabled app. Ignoring package " + pkg.packageName);
9738                    }
9739                }
9740            }
9741
9742            // If we're only installing presumed-existing packages, require that the
9743            // scanned APK is both already known and at the path previously established
9744            // for it.  Previously unknown packages we pick up normally, but if we have an
9745            // a priori expectation about this package's install presence, enforce it.
9746            // With a singular exception for new system packages. When an OTA contains
9747            // a new system package, we allow the codepath to change from a system location
9748            // to the user-installed location. If we don't allow this change, any newer,
9749            // user-installed version of the application will be ignored.
9750            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9751                if (mExpectingBetter.containsKey(pkg.packageName)) {
9752                    logCriticalInfo(Log.WARN,
9753                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9754                } else {
9755                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9756                    if (known != null) {
9757                        if (DEBUG_PACKAGE_SCANNING) {
9758                            Log.d(TAG, "Examining " + pkg.codePath
9759                                    + " and requiring known paths " + known.codePathString
9760                                    + " & " + known.resourcePathString);
9761                        }
9762                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9763                                || !pkg.applicationInfo.getResourcePath().equals(
9764                                        known.resourcePathString)) {
9765                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9766                                    "Application package " + pkg.packageName
9767                                    + " found at " + pkg.applicationInfo.getCodePath()
9768                                    + " but expected at " + known.codePathString
9769                                    + "; ignoring.");
9770                        }
9771                    }
9772                }
9773            }
9774
9775            // Verify that this new package doesn't have any content providers
9776            // that conflict with existing packages.  Only do this if the
9777            // package isn't already installed, since we don't want to break
9778            // things that are installed.
9779            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9780                final int N = pkg.providers.size();
9781                int i;
9782                for (i=0; i<N; i++) {
9783                    PackageParser.Provider p = pkg.providers.get(i);
9784                    if (p.info.authority != null) {
9785                        String names[] = p.info.authority.split(";");
9786                        for (int j = 0; j < names.length; j++) {
9787                            if (mProvidersByAuthority.containsKey(names[j])) {
9788                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9789                                final String otherPackageName =
9790                                        ((other != null && other.getComponentName() != null) ?
9791                                                other.getComponentName().getPackageName() : "?");
9792                                throw new PackageManagerException(
9793                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9794                                        "Can't install because provider name " + names[j]
9795                                                + " (in package " + pkg.applicationInfo.packageName
9796                                                + ") is already used by " + otherPackageName);
9797                            }
9798                        }
9799                    }
9800                }
9801            }
9802        }
9803    }
9804
9805    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9806            int type, String declaringPackageName, int declaringVersionCode) {
9807        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9808        if (versionedLib == null) {
9809            versionedLib = new SparseArray<>();
9810            mSharedLibraries.put(name, versionedLib);
9811            if (type == SharedLibraryInfo.TYPE_STATIC) {
9812                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9813            }
9814        } else if (versionedLib.indexOfKey(version) >= 0) {
9815            return false;
9816        }
9817        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9818                version, type, declaringPackageName, declaringVersionCode);
9819        versionedLib.put(version, libEntry);
9820        return true;
9821    }
9822
9823    private boolean removeSharedLibraryLPw(String name, int version) {
9824        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9825        if (versionedLib == null) {
9826            return false;
9827        }
9828        final int libIdx = versionedLib.indexOfKey(version);
9829        if (libIdx < 0) {
9830            return false;
9831        }
9832        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9833        versionedLib.remove(version);
9834        if (versionedLib.size() <= 0) {
9835            mSharedLibraries.remove(name);
9836            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9837                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9838                        .getPackageName());
9839            }
9840        }
9841        return true;
9842    }
9843
9844    /**
9845     * Adds a scanned package to the system. When this method is finished, the package will
9846     * be available for query, resolution, etc...
9847     */
9848    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9849            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9850        final String pkgName = pkg.packageName;
9851        if (mCustomResolverComponentName != null &&
9852                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9853            setUpCustomResolverActivity(pkg);
9854        }
9855
9856        if (pkg.packageName.equals("android")) {
9857            synchronized (mPackages) {
9858                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9859                    // Set up information for our fall-back user intent resolution activity.
9860                    mPlatformPackage = pkg;
9861                    pkg.mVersionCode = mSdkVersion;
9862                    mAndroidApplication = pkg.applicationInfo;
9863                    if (!mResolverReplaced) {
9864                        mResolveActivity.applicationInfo = mAndroidApplication;
9865                        mResolveActivity.name = ResolverActivity.class.getName();
9866                        mResolveActivity.packageName = mAndroidApplication.packageName;
9867                        mResolveActivity.processName = "system:ui";
9868                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9869                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9870                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9871                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9872                        mResolveActivity.exported = true;
9873                        mResolveActivity.enabled = true;
9874                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9875                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9876                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9877                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9878                                | ActivityInfo.CONFIG_ORIENTATION
9879                                | ActivityInfo.CONFIG_KEYBOARD
9880                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9881                        mResolveInfo.activityInfo = mResolveActivity;
9882                        mResolveInfo.priority = 0;
9883                        mResolveInfo.preferredOrder = 0;
9884                        mResolveInfo.match = 0;
9885                        mResolveComponentName = new ComponentName(
9886                                mAndroidApplication.packageName, mResolveActivity.name);
9887                    }
9888                }
9889            }
9890        }
9891
9892        ArrayList<PackageParser.Package> clientLibPkgs = null;
9893        // writer
9894        synchronized (mPackages) {
9895            boolean hasStaticSharedLibs = false;
9896
9897            // Any app can add new static shared libraries
9898            if (pkg.staticSharedLibName != null) {
9899                // Static shared libs don't allow renaming as they have synthetic package
9900                // names to allow install of multiple versions, so use name from manifest.
9901                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9902                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9903                        pkg.manifestPackageName, pkg.mVersionCode)) {
9904                    hasStaticSharedLibs = true;
9905                } else {
9906                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9907                                + pkg.staticSharedLibName + " already exists; skipping");
9908                }
9909                // Static shared libs cannot be updated once installed since they
9910                // use synthetic package name which includes the version code, so
9911                // not need to update other packages's shared lib dependencies.
9912            }
9913
9914            if (!hasStaticSharedLibs
9915                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9916                // Only system apps can add new dynamic shared libraries.
9917                if (pkg.libraryNames != null) {
9918                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9919                        String name = pkg.libraryNames.get(i);
9920                        boolean allowed = false;
9921                        if (pkg.isUpdatedSystemApp()) {
9922                            // New library entries can only be added through the
9923                            // system image.  This is important to get rid of a lot
9924                            // of nasty edge cases: for example if we allowed a non-
9925                            // system update of the app to add a library, then uninstalling
9926                            // the update would make the library go away, and assumptions
9927                            // we made such as through app install filtering would now
9928                            // have allowed apps on the device which aren't compatible
9929                            // with it.  Better to just have the restriction here, be
9930                            // conservative, and create many fewer cases that can negatively
9931                            // impact the user experience.
9932                            final PackageSetting sysPs = mSettings
9933                                    .getDisabledSystemPkgLPr(pkg.packageName);
9934                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9935                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9936                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9937                                        allowed = true;
9938                                        break;
9939                                    }
9940                                }
9941                            }
9942                        } else {
9943                            allowed = true;
9944                        }
9945                        if (allowed) {
9946                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9947                                    SharedLibraryInfo.VERSION_UNDEFINED,
9948                                    SharedLibraryInfo.TYPE_DYNAMIC,
9949                                    pkg.packageName, pkg.mVersionCode)) {
9950                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9951                                        + name + " already exists; skipping");
9952                            }
9953                        } else {
9954                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9955                                    + name + " that is not declared on system image; skipping");
9956                        }
9957                    }
9958
9959                    if ((scanFlags & SCAN_BOOTING) == 0) {
9960                        // If we are not booting, we need to update any applications
9961                        // that are clients of our shared library.  If we are booting,
9962                        // this will all be done once the scan is complete.
9963                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9964                    }
9965                }
9966            }
9967        }
9968
9969        if ((scanFlags & SCAN_BOOTING) != 0) {
9970            // No apps can run during boot scan, so they don't need to be frozen
9971        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9972            // Caller asked to not kill app, so it's probably not frozen
9973        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9974            // Caller asked us to ignore frozen check for some reason; they
9975            // probably didn't know the package name
9976        } else {
9977            // We're doing major surgery on this package, so it better be frozen
9978            // right now to keep it from launching
9979            checkPackageFrozen(pkgName);
9980        }
9981
9982        // Also need to kill any apps that are dependent on the library.
9983        if (clientLibPkgs != null) {
9984            for (int i=0; i<clientLibPkgs.size(); i++) {
9985                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9986                killApplication(clientPkg.applicationInfo.packageName,
9987                        clientPkg.applicationInfo.uid, "update lib");
9988            }
9989        }
9990
9991        // writer
9992        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9993
9994        synchronized (mPackages) {
9995            // We don't expect installation to fail beyond this point
9996
9997            // Add the new setting to mSettings
9998            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9999            // Add the new setting to mPackages
10000            mPackages.put(pkg.applicationInfo.packageName, pkg);
10001            // Make sure we don't accidentally delete its data.
10002            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10003            while (iter.hasNext()) {
10004                PackageCleanItem item = iter.next();
10005                if (pkgName.equals(item.packageName)) {
10006                    iter.remove();
10007                }
10008            }
10009
10010            // Add the package's KeySets to the global KeySetManagerService
10011            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10012            ksms.addScannedPackageLPw(pkg);
10013
10014            int N = pkg.providers.size();
10015            StringBuilder r = null;
10016            int i;
10017            for (i=0; i<N; i++) {
10018                PackageParser.Provider p = pkg.providers.get(i);
10019                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10020                        p.info.processName);
10021                mProviders.addProvider(p);
10022                p.syncable = p.info.isSyncable;
10023                if (p.info.authority != null) {
10024                    String names[] = p.info.authority.split(";");
10025                    p.info.authority = null;
10026                    for (int j = 0; j < names.length; j++) {
10027                        if (j == 1 && p.syncable) {
10028                            // We only want the first authority for a provider to possibly be
10029                            // syncable, so if we already added this provider using a different
10030                            // authority clear the syncable flag. We copy the provider before
10031                            // changing it because the mProviders object contains a reference
10032                            // to a provider that we don't want to change.
10033                            // Only do this for the second authority since the resulting provider
10034                            // object can be the same for all future authorities for this provider.
10035                            p = new PackageParser.Provider(p);
10036                            p.syncable = false;
10037                        }
10038                        if (!mProvidersByAuthority.containsKey(names[j])) {
10039                            mProvidersByAuthority.put(names[j], p);
10040                            if (p.info.authority == null) {
10041                                p.info.authority = names[j];
10042                            } else {
10043                                p.info.authority = p.info.authority + ";" + names[j];
10044                            }
10045                            if (DEBUG_PACKAGE_SCANNING) {
10046                                if (chatty)
10047                                    Log.d(TAG, "Registered content provider: " + names[j]
10048                                            + ", className = " + p.info.name + ", isSyncable = "
10049                                            + p.info.isSyncable);
10050                            }
10051                        } else {
10052                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10053                            Slog.w(TAG, "Skipping provider name " + names[j] +
10054                                    " (in package " + pkg.applicationInfo.packageName +
10055                                    "): name already used by "
10056                                    + ((other != null && other.getComponentName() != null)
10057                                            ? other.getComponentName().getPackageName() : "?"));
10058                        }
10059                    }
10060                }
10061                if (chatty) {
10062                    if (r == null) {
10063                        r = new StringBuilder(256);
10064                    } else {
10065                        r.append(' ');
10066                    }
10067                    r.append(p.info.name);
10068                }
10069            }
10070            if (r != null) {
10071                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10072            }
10073
10074            N = pkg.services.size();
10075            r = null;
10076            for (i=0; i<N; i++) {
10077                PackageParser.Service s = pkg.services.get(i);
10078                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10079                        s.info.processName);
10080                mServices.addService(s);
10081                if (chatty) {
10082                    if (r == null) {
10083                        r = new StringBuilder(256);
10084                    } else {
10085                        r.append(' ');
10086                    }
10087                    r.append(s.info.name);
10088                }
10089            }
10090            if (r != null) {
10091                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10092            }
10093
10094            N = pkg.receivers.size();
10095            r = null;
10096            for (i=0; i<N; i++) {
10097                PackageParser.Activity a = pkg.receivers.get(i);
10098                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10099                        a.info.processName);
10100                mReceivers.addActivity(a, "receiver");
10101                if (chatty) {
10102                    if (r == null) {
10103                        r = new StringBuilder(256);
10104                    } else {
10105                        r.append(' ');
10106                    }
10107                    r.append(a.info.name);
10108                }
10109            }
10110            if (r != null) {
10111                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10112            }
10113
10114            N = pkg.activities.size();
10115            r = null;
10116            for (i=0; i<N; i++) {
10117                PackageParser.Activity a = pkg.activities.get(i);
10118                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10119                        a.info.processName);
10120                mActivities.addActivity(a, "activity");
10121                if (chatty) {
10122                    if (r == null) {
10123                        r = new StringBuilder(256);
10124                    } else {
10125                        r.append(' ');
10126                    }
10127                    r.append(a.info.name);
10128                }
10129            }
10130            if (r != null) {
10131                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10132            }
10133
10134            N = pkg.permissionGroups.size();
10135            r = null;
10136            for (i=0; i<N; i++) {
10137                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10138                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10139                final String curPackageName = cur == null ? null : cur.info.packageName;
10140                // Dont allow ephemeral apps to define new permission groups.
10141                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10142                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10143                            + pg.info.packageName
10144                            + " ignored: instant apps cannot define new permission groups.");
10145                    continue;
10146                }
10147                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10148                if (cur == null || isPackageUpdate) {
10149                    mPermissionGroups.put(pg.info.name, pg);
10150                    if (chatty) {
10151                        if (r == null) {
10152                            r = new StringBuilder(256);
10153                        } else {
10154                            r.append(' ');
10155                        }
10156                        if (isPackageUpdate) {
10157                            r.append("UPD:");
10158                        }
10159                        r.append(pg.info.name);
10160                    }
10161                } else {
10162                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10163                            + pg.info.packageName + " ignored: original from "
10164                            + cur.info.packageName);
10165                    if (chatty) {
10166                        if (r == null) {
10167                            r = new StringBuilder(256);
10168                        } else {
10169                            r.append(' ');
10170                        }
10171                        r.append("DUP:");
10172                        r.append(pg.info.name);
10173                    }
10174                }
10175            }
10176            if (r != null) {
10177                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10178            }
10179
10180            N = pkg.permissions.size();
10181            r = null;
10182            for (i=0; i<N; i++) {
10183                PackageParser.Permission p = pkg.permissions.get(i);
10184
10185                // Dont allow ephemeral apps to define new permissions.
10186                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10187                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10188                            + p.info.packageName
10189                            + " ignored: instant apps cannot define new permissions.");
10190                    continue;
10191                }
10192
10193                // Assume by default that we did not install this permission into the system.
10194                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10195
10196                // Now that permission groups have a special meaning, we ignore permission
10197                // groups for legacy apps to prevent unexpected behavior. In particular,
10198                // permissions for one app being granted to someone just becase they happen
10199                // to be in a group defined by another app (before this had no implications).
10200                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10201                    p.group = mPermissionGroups.get(p.info.group);
10202                    // Warn for a permission in an unknown group.
10203                    if (p.info.group != null && p.group == null) {
10204                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10205                                + p.info.packageName + " in an unknown group " + p.info.group);
10206                    }
10207                }
10208
10209                ArrayMap<String, BasePermission> permissionMap =
10210                        p.tree ? mSettings.mPermissionTrees
10211                                : mSettings.mPermissions;
10212                BasePermission bp = permissionMap.get(p.info.name);
10213
10214                // Allow system apps to redefine non-system permissions
10215                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10216                    final boolean currentOwnerIsSystem = (bp.perm != null
10217                            && isSystemApp(bp.perm.owner));
10218                    if (isSystemApp(p.owner)) {
10219                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10220                            // It's a built-in permission and no owner, take ownership now
10221                            bp.packageSetting = pkgSetting;
10222                            bp.perm = p;
10223                            bp.uid = pkg.applicationInfo.uid;
10224                            bp.sourcePackage = p.info.packageName;
10225                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10226                        } else if (!currentOwnerIsSystem) {
10227                            String msg = "New decl " + p.owner + " of permission  "
10228                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10229                            reportSettingsProblem(Log.WARN, msg);
10230                            bp = null;
10231                        }
10232                    }
10233                }
10234
10235                if (bp == null) {
10236                    bp = new BasePermission(p.info.name, p.info.packageName,
10237                            BasePermission.TYPE_NORMAL);
10238                    permissionMap.put(p.info.name, bp);
10239                }
10240
10241                if (bp.perm == null) {
10242                    if (bp.sourcePackage == null
10243                            || bp.sourcePackage.equals(p.info.packageName)) {
10244                        BasePermission tree = findPermissionTreeLP(p.info.name);
10245                        if (tree == null
10246                                || tree.sourcePackage.equals(p.info.packageName)) {
10247                            bp.packageSetting = pkgSetting;
10248                            bp.perm = p;
10249                            bp.uid = pkg.applicationInfo.uid;
10250                            bp.sourcePackage = p.info.packageName;
10251                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10252                            if (chatty) {
10253                                if (r == null) {
10254                                    r = new StringBuilder(256);
10255                                } else {
10256                                    r.append(' ');
10257                                }
10258                                r.append(p.info.name);
10259                            }
10260                        } else {
10261                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10262                                    + p.info.packageName + " ignored: base tree "
10263                                    + tree.name + " is from package "
10264                                    + tree.sourcePackage);
10265                        }
10266                    } else {
10267                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10268                                + p.info.packageName + " ignored: original from "
10269                                + bp.sourcePackage);
10270                    }
10271                } else if (chatty) {
10272                    if (r == null) {
10273                        r = new StringBuilder(256);
10274                    } else {
10275                        r.append(' ');
10276                    }
10277                    r.append("DUP:");
10278                    r.append(p.info.name);
10279                }
10280                if (bp.perm == p) {
10281                    bp.protectionLevel = p.info.protectionLevel;
10282                }
10283            }
10284
10285            if (r != null) {
10286                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10287            }
10288
10289            N = pkg.instrumentation.size();
10290            r = null;
10291            for (i=0; i<N; i++) {
10292                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10293                a.info.packageName = pkg.applicationInfo.packageName;
10294                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10295                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10296                a.info.splitNames = pkg.splitNames;
10297                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10298                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10299                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10300                a.info.dataDir = pkg.applicationInfo.dataDir;
10301                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10302                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10303                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10304                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10305                mInstrumentation.put(a.getComponentName(), a);
10306                if (chatty) {
10307                    if (r == null) {
10308                        r = new StringBuilder(256);
10309                    } else {
10310                        r.append(' ');
10311                    }
10312                    r.append(a.info.name);
10313                }
10314            }
10315            if (r != null) {
10316                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10317            }
10318
10319            if (pkg.protectedBroadcasts != null) {
10320                N = pkg.protectedBroadcasts.size();
10321                for (i=0; i<N; i++) {
10322                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10323                }
10324            }
10325        }
10326
10327        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10328    }
10329
10330    /**
10331     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10332     * is derived purely on the basis of the contents of {@code scanFile} and
10333     * {@code cpuAbiOverride}.
10334     *
10335     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10336     */
10337    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10338                                 String cpuAbiOverride, boolean extractLibs,
10339                                 File appLib32InstallDir)
10340            throws PackageManagerException {
10341        // Give ourselves some initial paths; we'll come back for another
10342        // pass once we've determined ABI below.
10343        setNativeLibraryPaths(pkg, appLib32InstallDir);
10344
10345        // We would never need to extract libs for forward-locked and external packages,
10346        // since the container service will do it for us. We shouldn't attempt to
10347        // extract libs from system app when it was not updated.
10348        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10349                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10350            extractLibs = false;
10351        }
10352
10353        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10354        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10355
10356        NativeLibraryHelper.Handle handle = null;
10357        try {
10358            handle = NativeLibraryHelper.Handle.create(pkg);
10359            // TODO(multiArch): This can be null for apps that didn't go through the
10360            // usual installation process. We can calculate it again, like we
10361            // do during install time.
10362            //
10363            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10364            // unnecessary.
10365            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10366
10367            // Null out the abis so that they can be recalculated.
10368            pkg.applicationInfo.primaryCpuAbi = null;
10369            pkg.applicationInfo.secondaryCpuAbi = null;
10370            if (isMultiArch(pkg.applicationInfo)) {
10371                // Warn if we've set an abiOverride for multi-lib packages..
10372                // By definition, we need to copy both 32 and 64 bit libraries for
10373                // such packages.
10374                if (pkg.cpuAbiOverride != null
10375                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10376                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10377                }
10378
10379                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10380                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10381                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10382                    if (extractLibs) {
10383                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10384                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10385                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10386                                useIsaSpecificSubdirs);
10387                    } else {
10388                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10389                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10390                    }
10391                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10392                }
10393
10394                maybeThrowExceptionForMultiArchCopy(
10395                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10396
10397                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10398                    if (extractLibs) {
10399                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10400                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10401                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10402                                useIsaSpecificSubdirs);
10403                    } else {
10404                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10405                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10406                    }
10407                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10408                }
10409
10410                maybeThrowExceptionForMultiArchCopy(
10411                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10412
10413                if (abi64 >= 0) {
10414                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10415                }
10416
10417                if (abi32 >= 0) {
10418                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10419                    if (abi64 >= 0) {
10420                        if (pkg.use32bitAbi) {
10421                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10422                            pkg.applicationInfo.primaryCpuAbi = abi;
10423                        } else {
10424                            pkg.applicationInfo.secondaryCpuAbi = abi;
10425                        }
10426                    } else {
10427                        pkg.applicationInfo.primaryCpuAbi = abi;
10428                    }
10429                }
10430
10431            } else {
10432                String[] abiList = (cpuAbiOverride != null) ?
10433                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10434
10435                // Enable gross and lame hacks for apps that are built with old
10436                // SDK tools. We must scan their APKs for renderscript bitcode and
10437                // not launch them if it's present. Don't bother checking on devices
10438                // that don't have 64 bit support.
10439                boolean needsRenderScriptOverride = false;
10440                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10441                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10442                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10443                    needsRenderScriptOverride = true;
10444                }
10445
10446                final int copyRet;
10447                if (extractLibs) {
10448                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10449                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10450                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10451                } else {
10452                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10453                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10454                }
10455                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10456
10457                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10458                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10459                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10460                }
10461
10462                if (copyRet >= 0) {
10463                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10464                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10465                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10466                } else if (needsRenderScriptOverride) {
10467                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10468                }
10469            }
10470        } catch (IOException ioe) {
10471            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10472        } finally {
10473            IoUtils.closeQuietly(handle);
10474        }
10475
10476        // Now that we've calculated the ABIs and determined if it's an internal app,
10477        // we will go ahead and populate the nativeLibraryPath.
10478        setNativeLibraryPaths(pkg, appLib32InstallDir);
10479    }
10480
10481    /**
10482     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10483     * i.e, so that all packages can be run inside a single process if required.
10484     *
10485     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10486     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10487     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10488     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10489     * updating a package that belongs to a shared user.
10490     *
10491     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10492     * adds unnecessary complexity.
10493     */
10494    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10495            PackageParser.Package scannedPackage) {
10496        String requiredInstructionSet = null;
10497        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10498            requiredInstructionSet = VMRuntime.getInstructionSet(
10499                     scannedPackage.applicationInfo.primaryCpuAbi);
10500        }
10501
10502        PackageSetting requirer = null;
10503        for (PackageSetting ps : packagesForUser) {
10504            // If packagesForUser contains scannedPackage, we skip it. This will happen
10505            // when scannedPackage is an update of an existing package. Without this check,
10506            // we will never be able to change the ABI of any package belonging to a shared
10507            // user, even if it's compatible with other packages.
10508            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10509                if (ps.primaryCpuAbiString == null) {
10510                    continue;
10511                }
10512
10513                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10514                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10515                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10516                    // this but there's not much we can do.
10517                    String errorMessage = "Instruction set mismatch, "
10518                            + ((requirer == null) ? "[caller]" : requirer)
10519                            + " requires " + requiredInstructionSet + " whereas " + ps
10520                            + " requires " + instructionSet;
10521                    Slog.w(TAG, errorMessage);
10522                }
10523
10524                if (requiredInstructionSet == null) {
10525                    requiredInstructionSet = instructionSet;
10526                    requirer = ps;
10527                }
10528            }
10529        }
10530
10531        if (requiredInstructionSet != null) {
10532            String adjustedAbi;
10533            if (requirer != null) {
10534                // requirer != null implies that either scannedPackage was null or that scannedPackage
10535                // did not require an ABI, in which case we have to adjust scannedPackage to match
10536                // the ABI of the set (which is the same as requirer's ABI)
10537                adjustedAbi = requirer.primaryCpuAbiString;
10538                if (scannedPackage != null) {
10539                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10540                }
10541            } else {
10542                // requirer == null implies that we're updating all ABIs in the set to
10543                // match scannedPackage.
10544                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10545            }
10546
10547            for (PackageSetting ps : packagesForUser) {
10548                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10549                    if (ps.primaryCpuAbiString != null) {
10550                        continue;
10551                    }
10552
10553                    ps.primaryCpuAbiString = adjustedAbi;
10554                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10555                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10556                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10557                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10558                                + " (requirer="
10559                                + (requirer != null ? requirer.pkg : "null")
10560                                + ", scannedPackage="
10561                                + (scannedPackage != null ? scannedPackage : "null")
10562                                + ")");
10563                        try {
10564                            mInstaller.rmdex(ps.codePathString,
10565                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10566                        } catch (InstallerException ignored) {
10567                        }
10568                    }
10569                }
10570            }
10571        }
10572    }
10573
10574    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10575        synchronized (mPackages) {
10576            mResolverReplaced = true;
10577            // Set up information for custom user intent resolution activity.
10578            mResolveActivity.applicationInfo = pkg.applicationInfo;
10579            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10580            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10581            mResolveActivity.processName = pkg.applicationInfo.packageName;
10582            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10583            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10584                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10585            mResolveActivity.theme = 0;
10586            mResolveActivity.exported = true;
10587            mResolveActivity.enabled = true;
10588            mResolveInfo.activityInfo = mResolveActivity;
10589            mResolveInfo.priority = 0;
10590            mResolveInfo.preferredOrder = 0;
10591            mResolveInfo.match = 0;
10592            mResolveComponentName = mCustomResolverComponentName;
10593            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10594                    mResolveComponentName);
10595        }
10596    }
10597
10598    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10599        if (installerActivity == null) {
10600            if (DEBUG_EPHEMERAL) {
10601                Slog.d(TAG, "Clear ephemeral installer activity");
10602            }
10603            mInstantAppInstallerActivity = null;
10604            return;
10605        }
10606
10607        if (DEBUG_EPHEMERAL) {
10608            Slog.d(TAG, "Set ephemeral installer activity: "
10609                    + installerActivity.getComponentName());
10610        }
10611        // Set up information for ephemeral installer activity
10612        mInstantAppInstallerActivity = installerActivity;
10613        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10614                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10615        mInstantAppInstallerActivity.exported = true;
10616        mInstantAppInstallerActivity.enabled = true;
10617        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10618        mInstantAppInstallerInfo.priority = 0;
10619        mInstantAppInstallerInfo.preferredOrder = 1;
10620        mInstantAppInstallerInfo.isDefault = true;
10621        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10622                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10623    }
10624
10625    private static String calculateBundledApkRoot(final String codePathString) {
10626        final File codePath = new File(codePathString);
10627        final File codeRoot;
10628        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10629            codeRoot = Environment.getRootDirectory();
10630        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10631            codeRoot = Environment.getOemDirectory();
10632        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10633            codeRoot = Environment.getVendorDirectory();
10634        } else {
10635            // Unrecognized code path; take its top real segment as the apk root:
10636            // e.g. /something/app/blah.apk => /something
10637            try {
10638                File f = codePath.getCanonicalFile();
10639                File parent = f.getParentFile();    // non-null because codePath is a file
10640                File tmp;
10641                while ((tmp = parent.getParentFile()) != null) {
10642                    f = parent;
10643                    parent = tmp;
10644                }
10645                codeRoot = f;
10646                Slog.w(TAG, "Unrecognized code path "
10647                        + codePath + " - using " + codeRoot);
10648            } catch (IOException e) {
10649                // Can't canonicalize the code path -- shenanigans?
10650                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10651                return Environment.getRootDirectory().getPath();
10652            }
10653        }
10654        return codeRoot.getPath();
10655    }
10656
10657    /**
10658     * Derive and set the location of native libraries for the given package,
10659     * which varies depending on where and how the package was installed.
10660     */
10661    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10662        final ApplicationInfo info = pkg.applicationInfo;
10663        final String codePath = pkg.codePath;
10664        final File codeFile = new File(codePath);
10665        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10666        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10667
10668        info.nativeLibraryRootDir = null;
10669        info.nativeLibraryRootRequiresIsa = false;
10670        info.nativeLibraryDir = null;
10671        info.secondaryNativeLibraryDir = null;
10672
10673        if (isApkFile(codeFile)) {
10674            // Monolithic install
10675            if (bundledApp) {
10676                // If "/system/lib64/apkname" exists, assume that is the per-package
10677                // native library directory to use; otherwise use "/system/lib/apkname".
10678                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10679                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10680                        getPrimaryInstructionSet(info));
10681
10682                // This is a bundled system app so choose the path based on the ABI.
10683                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10684                // is just the default path.
10685                final String apkName = deriveCodePathName(codePath);
10686                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10687                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10688                        apkName).getAbsolutePath();
10689
10690                if (info.secondaryCpuAbi != null) {
10691                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10692                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10693                            secondaryLibDir, apkName).getAbsolutePath();
10694                }
10695            } else if (asecApp) {
10696                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10697                        .getAbsolutePath();
10698            } else {
10699                final String apkName = deriveCodePathName(codePath);
10700                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10701                        .getAbsolutePath();
10702            }
10703
10704            info.nativeLibraryRootRequiresIsa = false;
10705            info.nativeLibraryDir = info.nativeLibraryRootDir;
10706        } else {
10707            // Cluster install
10708            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10709            info.nativeLibraryRootRequiresIsa = true;
10710
10711            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10712                    getPrimaryInstructionSet(info)).getAbsolutePath();
10713
10714            if (info.secondaryCpuAbi != null) {
10715                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10716                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10717            }
10718        }
10719    }
10720
10721    /**
10722     * Calculate the abis and roots for a bundled app. These can uniquely
10723     * be determined from the contents of the system partition, i.e whether
10724     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10725     * of this information, and instead assume that the system was built
10726     * sensibly.
10727     */
10728    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10729                                           PackageSetting pkgSetting) {
10730        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10731
10732        // If "/system/lib64/apkname" exists, assume that is the per-package
10733        // native library directory to use; otherwise use "/system/lib/apkname".
10734        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10735        setBundledAppAbi(pkg, apkRoot, apkName);
10736        // pkgSetting might be null during rescan following uninstall of updates
10737        // to a bundled app, so accommodate that possibility.  The settings in
10738        // that case will be established later from the parsed package.
10739        //
10740        // If the settings aren't null, sync them up with what we've just derived.
10741        // note that apkRoot isn't stored in the package settings.
10742        if (pkgSetting != null) {
10743            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10744            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10745        }
10746    }
10747
10748    /**
10749     * Deduces the ABI of a bundled app and sets the relevant fields on the
10750     * parsed pkg object.
10751     *
10752     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10753     *        under which system libraries are installed.
10754     * @param apkName the name of the installed package.
10755     */
10756    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10757        final File codeFile = new File(pkg.codePath);
10758
10759        final boolean has64BitLibs;
10760        final boolean has32BitLibs;
10761        if (isApkFile(codeFile)) {
10762            // Monolithic install
10763            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10764            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10765        } else {
10766            // Cluster install
10767            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10768            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10769                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10770                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10771                has64BitLibs = (new File(rootDir, isa)).exists();
10772            } else {
10773                has64BitLibs = false;
10774            }
10775            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10776                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10777                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10778                has32BitLibs = (new File(rootDir, isa)).exists();
10779            } else {
10780                has32BitLibs = false;
10781            }
10782        }
10783
10784        if (has64BitLibs && !has32BitLibs) {
10785            // The package has 64 bit libs, but not 32 bit libs. Its primary
10786            // ABI should be 64 bit. We can safely assume here that the bundled
10787            // native libraries correspond to the most preferred ABI in the list.
10788
10789            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10790            pkg.applicationInfo.secondaryCpuAbi = null;
10791        } else if (has32BitLibs && !has64BitLibs) {
10792            // The package has 32 bit libs but not 64 bit libs. Its primary
10793            // ABI should be 32 bit.
10794
10795            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10796            pkg.applicationInfo.secondaryCpuAbi = null;
10797        } else if (has32BitLibs && has64BitLibs) {
10798            // The application has both 64 and 32 bit bundled libraries. We check
10799            // here that the app declares multiArch support, and warn if it doesn't.
10800            //
10801            // We will be lenient here and record both ABIs. The primary will be the
10802            // ABI that's higher on the list, i.e, a device that's configured to prefer
10803            // 64 bit apps will see a 64 bit primary ABI,
10804
10805            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10806                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10807            }
10808
10809            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10810                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10811                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10812            } else {
10813                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10814                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10815            }
10816        } else {
10817            pkg.applicationInfo.primaryCpuAbi = null;
10818            pkg.applicationInfo.secondaryCpuAbi = null;
10819        }
10820    }
10821
10822    private void killApplication(String pkgName, int appId, String reason) {
10823        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10824    }
10825
10826    private void killApplication(String pkgName, int appId, int userId, String reason) {
10827        // Request the ActivityManager to kill the process(only for existing packages)
10828        // so that we do not end up in a confused state while the user is still using the older
10829        // version of the application while the new one gets installed.
10830        final long token = Binder.clearCallingIdentity();
10831        try {
10832            IActivityManager am = ActivityManager.getService();
10833            if (am != null) {
10834                try {
10835                    am.killApplication(pkgName, appId, userId, reason);
10836                } catch (RemoteException e) {
10837                }
10838            }
10839        } finally {
10840            Binder.restoreCallingIdentity(token);
10841        }
10842    }
10843
10844    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10845        // Remove the parent package setting
10846        PackageSetting ps = (PackageSetting) pkg.mExtras;
10847        if (ps != null) {
10848            removePackageLI(ps, chatty);
10849        }
10850        // Remove the child package setting
10851        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10852        for (int i = 0; i < childCount; i++) {
10853            PackageParser.Package childPkg = pkg.childPackages.get(i);
10854            ps = (PackageSetting) childPkg.mExtras;
10855            if (ps != null) {
10856                removePackageLI(ps, chatty);
10857            }
10858        }
10859    }
10860
10861    void removePackageLI(PackageSetting ps, boolean chatty) {
10862        if (DEBUG_INSTALL) {
10863            if (chatty)
10864                Log.d(TAG, "Removing package " + ps.name);
10865        }
10866
10867        // writer
10868        synchronized (mPackages) {
10869            mPackages.remove(ps.name);
10870            final PackageParser.Package pkg = ps.pkg;
10871            if (pkg != null) {
10872                cleanPackageDataStructuresLILPw(pkg, chatty);
10873            }
10874        }
10875    }
10876
10877    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10878        if (DEBUG_INSTALL) {
10879            if (chatty)
10880                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10881        }
10882
10883        // writer
10884        synchronized (mPackages) {
10885            // Remove the parent package
10886            mPackages.remove(pkg.applicationInfo.packageName);
10887            cleanPackageDataStructuresLILPw(pkg, chatty);
10888
10889            // Remove the child packages
10890            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10891            for (int i = 0; i < childCount; i++) {
10892                PackageParser.Package childPkg = pkg.childPackages.get(i);
10893                mPackages.remove(childPkg.applicationInfo.packageName);
10894                cleanPackageDataStructuresLILPw(childPkg, chatty);
10895            }
10896        }
10897    }
10898
10899    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10900        int N = pkg.providers.size();
10901        StringBuilder r = null;
10902        int i;
10903        for (i=0; i<N; i++) {
10904            PackageParser.Provider p = pkg.providers.get(i);
10905            mProviders.removeProvider(p);
10906            if (p.info.authority == null) {
10907
10908                /* There was another ContentProvider with this authority when
10909                 * this app was installed so this authority is null,
10910                 * Ignore it as we don't have to unregister the provider.
10911                 */
10912                continue;
10913            }
10914            String names[] = p.info.authority.split(";");
10915            for (int j = 0; j < names.length; j++) {
10916                if (mProvidersByAuthority.get(names[j]) == p) {
10917                    mProvidersByAuthority.remove(names[j]);
10918                    if (DEBUG_REMOVE) {
10919                        if (chatty)
10920                            Log.d(TAG, "Unregistered content provider: " + names[j]
10921                                    + ", className = " + p.info.name + ", isSyncable = "
10922                                    + p.info.isSyncable);
10923                    }
10924                }
10925            }
10926            if (DEBUG_REMOVE && chatty) {
10927                if (r == null) {
10928                    r = new StringBuilder(256);
10929                } else {
10930                    r.append(' ');
10931                }
10932                r.append(p.info.name);
10933            }
10934        }
10935        if (r != null) {
10936            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10937        }
10938
10939        N = pkg.services.size();
10940        r = null;
10941        for (i=0; i<N; i++) {
10942            PackageParser.Service s = pkg.services.get(i);
10943            mServices.removeService(s);
10944            if (chatty) {
10945                if (r == null) {
10946                    r = new StringBuilder(256);
10947                } else {
10948                    r.append(' ');
10949                }
10950                r.append(s.info.name);
10951            }
10952        }
10953        if (r != null) {
10954            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10955        }
10956
10957        N = pkg.receivers.size();
10958        r = null;
10959        for (i=0; i<N; i++) {
10960            PackageParser.Activity a = pkg.receivers.get(i);
10961            mReceivers.removeActivity(a, "receiver");
10962            if (DEBUG_REMOVE && chatty) {
10963                if (r == null) {
10964                    r = new StringBuilder(256);
10965                } else {
10966                    r.append(' ');
10967                }
10968                r.append(a.info.name);
10969            }
10970        }
10971        if (r != null) {
10972            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10973        }
10974
10975        N = pkg.activities.size();
10976        r = null;
10977        for (i=0; i<N; i++) {
10978            PackageParser.Activity a = pkg.activities.get(i);
10979            mActivities.removeActivity(a, "activity");
10980            if (DEBUG_REMOVE && chatty) {
10981                if (r == null) {
10982                    r = new StringBuilder(256);
10983                } else {
10984                    r.append(' ');
10985                }
10986                r.append(a.info.name);
10987            }
10988        }
10989        if (r != null) {
10990            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10991        }
10992
10993        N = pkg.permissions.size();
10994        r = null;
10995        for (i=0; i<N; i++) {
10996            PackageParser.Permission p = pkg.permissions.get(i);
10997            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10998            if (bp == null) {
10999                bp = mSettings.mPermissionTrees.get(p.info.name);
11000            }
11001            if (bp != null && bp.perm == p) {
11002                bp.perm = null;
11003                if (DEBUG_REMOVE && chatty) {
11004                    if (r == null) {
11005                        r = new StringBuilder(256);
11006                    } else {
11007                        r.append(' ');
11008                    }
11009                    r.append(p.info.name);
11010                }
11011            }
11012            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11013                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11014                if (appOpPkgs != null) {
11015                    appOpPkgs.remove(pkg.packageName);
11016                }
11017            }
11018        }
11019        if (r != null) {
11020            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11021        }
11022
11023        N = pkg.requestedPermissions.size();
11024        r = null;
11025        for (i=0; i<N; i++) {
11026            String perm = pkg.requestedPermissions.get(i);
11027            BasePermission bp = mSettings.mPermissions.get(perm);
11028            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11029                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11030                if (appOpPkgs != null) {
11031                    appOpPkgs.remove(pkg.packageName);
11032                    if (appOpPkgs.isEmpty()) {
11033                        mAppOpPermissionPackages.remove(perm);
11034                    }
11035                }
11036            }
11037        }
11038        if (r != null) {
11039            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11040        }
11041
11042        N = pkg.instrumentation.size();
11043        r = null;
11044        for (i=0; i<N; i++) {
11045            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11046            mInstrumentation.remove(a.getComponentName());
11047            if (DEBUG_REMOVE && chatty) {
11048                if (r == null) {
11049                    r = new StringBuilder(256);
11050                } else {
11051                    r.append(' ');
11052                }
11053                r.append(a.info.name);
11054            }
11055        }
11056        if (r != null) {
11057            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11058        }
11059
11060        r = null;
11061        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11062            // Only system apps can hold shared libraries.
11063            if (pkg.libraryNames != null) {
11064                for (i = 0; i < pkg.libraryNames.size(); i++) {
11065                    String name = pkg.libraryNames.get(i);
11066                    if (removeSharedLibraryLPw(name, 0)) {
11067                        if (DEBUG_REMOVE && chatty) {
11068                            if (r == null) {
11069                                r = new StringBuilder(256);
11070                            } else {
11071                                r.append(' ');
11072                            }
11073                            r.append(name);
11074                        }
11075                    }
11076                }
11077            }
11078        }
11079
11080        r = null;
11081
11082        // Any package can hold static shared libraries.
11083        if (pkg.staticSharedLibName != null) {
11084            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11085                if (DEBUG_REMOVE && chatty) {
11086                    if (r == null) {
11087                        r = new StringBuilder(256);
11088                    } else {
11089                        r.append(' ');
11090                    }
11091                    r.append(pkg.staticSharedLibName);
11092                }
11093            }
11094        }
11095
11096        if (r != null) {
11097            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11098        }
11099    }
11100
11101    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11102        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11103            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11104                return true;
11105            }
11106        }
11107        return false;
11108    }
11109
11110    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11111    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11112    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11113
11114    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11115        // Update the parent permissions
11116        updatePermissionsLPw(pkg.packageName, pkg, flags);
11117        // Update the child permissions
11118        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11119        for (int i = 0; i < childCount; i++) {
11120            PackageParser.Package childPkg = pkg.childPackages.get(i);
11121            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11122        }
11123    }
11124
11125    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11126            int flags) {
11127        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11128        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11129    }
11130
11131    private void updatePermissionsLPw(String changingPkg,
11132            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11133        // Make sure there are no dangling permission trees.
11134        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11135        while (it.hasNext()) {
11136            final BasePermission bp = it.next();
11137            if (bp.packageSetting == null) {
11138                // We may not yet have parsed the package, so just see if
11139                // we still know about its settings.
11140                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11141            }
11142            if (bp.packageSetting == null) {
11143                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11144                        + " from package " + bp.sourcePackage);
11145                it.remove();
11146            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11147                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11148                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11149                            + " from package " + bp.sourcePackage);
11150                    flags |= UPDATE_PERMISSIONS_ALL;
11151                    it.remove();
11152                }
11153            }
11154        }
11155
11156        // Make sure all dynamic permissions have been assigned to a package,
11157        // and make sure there are no dangling permissions.
11158        it = mSettings.mPermissions.values().iterator();
11159        while (it.hasNext()) {
11160            final BasePermission bp = it.next();
11161            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11162                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11163                        + bp.name + " pkg=" + bp.sourcePackage
11164                        + " info=" + bp.pendingInfo);
11165                if (bp.packageSetting == null && bp.pendingInfo != null) {
11166                    final BasePermission tree = findPermissionTreeLP(bp.name);
11167                    if (tree != null && tree.perm != null) {
11168                        bp.packageSetting = tree.packageSetting;
11169                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11170                                new PermissionInfo(bp.pendingInfo));
11171                        bp.perm.info.packageName = tree.perm.info.packageName;
11172                        bp.perm.info.name = bp.name;
11173                        bp.uid = tree.uid;
11174                    }
11175                }
11176            }
11177            if (bp.packageSetting == null) {
11178                // We may not yet have parsed the package, so just see if
11179                // we still know about its settings.
11180                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11181            }
11182            if (bp.packageSetting == null) {
11183                Slog.w(TAG, "Removing dangling permission: " + bp.name
11184                        + " from package " + bp.sourcePackage);
11185                it.remove();
11186            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11187                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11188                    Slog.i(TAG, "Removing old permission: " + bp.name
11189                            + " from package " + bp.sourcePackage);
11190                    flags |= UPDATE_PERMISSIONS_ALL;
11191                    it.remove();
11192                }
11193            }
11194        }
11195
11196        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11197        // Now update the permissions for all packages, in particular
11198        // replace the granted permissions of the system packages.
11199        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11200            for (PackageParser.Package pkg : mPackages.values()) {
11201                if (pkg != pkgInfo) {
11202                    // Only replace for packages on requested volume
11203                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11204                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11205                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11206                    grantPermissionsLPw(pkg, replace, changingPkg);
11207                }
11208            }
11209        }
11210
11211        if (pkgInfo != null) {
11212            // Only replace for packages on requested volume
11213            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11214            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11215                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11216            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11217        }
11218        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11219    }
11220
11221    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11222            String packageOfInterest) {
11223        // IMPORTANT: There are two types of permissions: install and runtime.
11224        // Install time permissions are granted when the app is installed to
11225        // all device users and users added in the future. Runtime permissions
11226        // are granted at runtime explicitly to specific users. Normal and signature
11227        // protected permissions are install time permissions. Dangerous permissions
11228        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11229        // otherwise they are runtime permissions. This function does not manage
11230        // runtime permissions except for the case an app targeting Lollipop MR1
11231        // being upgraded to target a newer SDK, in which case dangerous permissions
11232        // are transformed from install time to runtime ones.
11233
11234        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11235        if (ps == null) {
11236            return;
11237        }
11238
11239        PermissionsState permissionsState = ps.getPermissionsState();
11240        PermissionsState origPermissions = permissionsState;
11241
11242        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11243
11244        boolean runtimePermissionsRevoked = false;
11245        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11246
11247        boolean changedInstallPermission = false;
11248
11249        if (replace) {
11250            ps.installPermissionsFixed = false;
11251            if (!ps.isSharedUser()) {
11252                origPermissions = new PermissionsState(permissionsState);
11253                permissionsState.reset();
11254            } else {
11255                // We need to know only about runtime permission changes since the
11256                // calling code always writes the install permissions state but
11257                // the runtime ones are written only if changed. The only cases of
11258                // changed runtime permissions here are promotion of an install to
11259                // runtime and revocation of a runtime from a shared user.
11260                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11261                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11262                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11263                    runtimePermissionsRevoked = true;
11264                }
11265            }
11266        }
11267
11268        permissionsState.setGlobalGids(mGlobalGids);
11269
11270        final int N = pkg.requestedPermissions.size();
11271        for (int i=0; i<N; i++) {
11272            final String name = pkg.requestedPermissions.get(i);
11273            final BasePermission bp = mSettings.mPermissions.get(name);
11274
11275            if (DEBUG_INSTALL) {
11276                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11277            }
11278
11279            if (bp == null || bp.packageSetting == null) {
11280                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11281                    Slog.w(TAG, "Unknown permission " + name
11282                            + " in package " + pkg.packageName);
11283                }
11284                continue;
11285            }
11286
11287
11288            // Limit ephemeral apps to ephemeral allowed permissions.
11289            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11290                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11291                        + pkg.packageName);
11292                continue;
11293            }
11294
11295            final String perm = bp.name;
11296            boolean allowedSig = false;
11297            int grant = GRANT_DENIED;
11298
11299            // Keep track of app op permissions.
11300            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11301                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11302                if (pkgs == null) {
11303                    pkgs = new ArraySet<>();
11304                    mAppOpPermissionPackages.put(bp.name, pkgs);
11305                }
11306                pkgs.add(pkg.packageName);
11307            }
11308
11309            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11310            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11311                    >= Build.VERSION_CODES.M;
11312            switch (level) {
11313                case PermissionInfo.PROTECTION_NORMAL: {
11314                    // For all apps normal permissions are install time ones.
11315                    grant = GRANT_INSTALL;
11316                } break;
11317
11318                case PermissionInfo.PROTECTION_DANGEROUS: {
11319                    // If a permission review is required for legacy apps we represent
11320                    // their permissions as always granted runtime ones since we need
11321                    // to keep the review required permission flag per user while an
11322                    // install permission's state is shared across all users.
11323                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11324                        // For legacy apps dangerous permissions are install time ones.
11325                        grant = GRANT_INSTALL;
11326                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11327                        // For legacy apps that became modern, install becomes runtime.
11328                        grant = GRANT_UPGRADE;
11329                    } else if (mPromoteSystemApps
11330                            && isSystemApp(ps)
11331                            && mExistingSystemPackages.contains(ps.name)) {
11332                        // For legacy system apps, install becomes runtime.
11333                        // We cannot check hasInstallPermission() for system apps since those
11334                        // permissions were granted implicitly and not persisted pre-M.
11335                        grant = GRANT_UPGRADE;
11336                    } else {
11337                        // For modern apps keep runtime permissions unchanged.
11338                        grant = GRANT_RUNTIME;
11339                    }
11340                } break;
11341
11342                case PermissionInfo.PROTECTION_SIGNATURE: {
11343                    // For all apps signature permissions are install time ones.
11344                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11345                    if (allowedSig) {
11346                        grant = GRANT_INSTALL;
11347                    }
11348                } break;
11349            }
11350
11351            if (DEBUG_INSTALL) {
11352                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11353            }
11354
11355            if (grant != GRANT_DENIED) {
11356                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11357                    // If this is an existing, non-system package, then
11358                    // we can't add any new permissions to it.
11359                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11360                        // Except...  if this is a permission that was added
11361                        // to the platform (note: need to only do this when
11362                        // updating the platform).
11363                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11364                            grant = GRANT_DENIED;
11365                        }
11366                    }
11367                }
11368
11369                switch (grant) {
11370                    case GRANT_INSTALL: {
11371                        // Revoke this as runtime permission to handle the case of
11372                        // a runtime permission being downgraded to an install one.
11373                        // Also in permission review mode we keep dangerous permissions
11374                        // for legacy apps
11375                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11376                            if (origPermissions.getRuntimePermissionState(
11377                                    bp.name, userId) != null) {
11378                                // Revoke the runtime permission and clear the flags.
11379                                origPermissions.revokeRuntimePermission(bp, userId);
11380                                origPermissions.updatePermissionFlags(bp, userId,
11381                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11382                                // If we revoked a permission permission, we have to write.
11383                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11384                                        changedRuntimePermissionUserIds, userId);
11385                            }
11386                        }
11387                        // Grant an install permission.
11388                        if (permissionsState.grantInstallPermission(bp) !=
11389                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11390                            changedInstallPermission = true;
11391                        }
11392                    } break;
11393
11394                    case GRANT_RUNTIME: {
11395                        // Grant previously granted runtime permissions.
11396                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11397                            PermissionState permissionState = origPermissions
11398                                    .getRuntimePermissionState(bp.name, userId);
11399                            int flags = permissionState != null
11400                                    ? permissionState.getFlags() : 0;
11401                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11402                                // Don't propagate the permission in a permission review mode if
11403                                // the former was revoked, i.e. marked to not propagate on upgrade.
11404                                // Note that in a permission review mode install permissions are
11405                                // represented as constantly granted runtime ones since we need to
11406                                // keep a per user state associated with the permission. Also the
11407                                // revoke on upgrade flag is no longer applicable and is reset.
11408                                final boolean revokeOnUpgrade = (flags & PackageManager
11409                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11410                                if (revokeOnUpgrade) {
11411                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11412                                    // Since we changed the flags, we have to write.
11413                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11414                                            changedRuntimePermissionUserIds, userId);
11415                                }
11416                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11417                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11418                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11419                                        // If we cannot put the permission as it was,
11420                                        // we have to write.
11421                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11422                                                changedRuntimePermissionUserIds, userId);
11423                                    }
11424                                }
11425
11426                                // If the app supports runtime permissions no need for a review.
11427                                if (mPermissionReviewRequired
11428                                        && appSupportsRuntimePermissions
11429                                        && (flags & PackageManager
11430                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11431                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11432                                    // Since we changed the flags, we have to write.
11433                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11434                                            changedRuntimePermissionUserIds, userId);
11435                                }
11436                            } else if (mPermissionReviewRequired
11437                                    && !appSupportsRuntimePermissions) {
11438                                // For legacy apps that need a permission review, every new
11439                                // runtime permission is granted but it is pending a review.
11440                                // We also need to review only platform defined runtime
11441                                // permissions as these are the only ones the platform knows
11442                                // how to disable the API to simulate revocation as legacy
11443                                // apps don't expect to run with revoked permissions.
11444                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11445                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11446                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11447                                        // We changed the flags, hence have to write.
11448                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11449                                                changedRuntimePermissionUserIds, userId);
11450                                    }
11451                                }
11452                                if (permissionsState.grantRuntimePermission(bp, userId)
11453                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11454                                    // We changed the permission, hence have to write.
11455                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11456                                            changedRuntimePermissionUserIds, userId);
11457                                }
11458                            }
11459                            // Propagate the permission flags.
11460                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11461                        }
11462                    } break;
11463
11464                    case GRANT_UPGRADE: {
11465                        // Grant runtime permissions for a previously held install permission.
11466                        PermissionState permissionState = origPermissions
11467                                .getInstallPermissionState(bp.name);
11468                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11469
11470                        if (origPermissions.revokeInstallPermission(bp)
11471                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11472                            // We will be transferring the permission flags, so clear them.
11473                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11474                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11475                            changedInstallPermission = true;
11476                        }
11477
11478                        // If the permission is not to be promoted to runtime we ignore it and
11479                        // also its other flags as they are not applicable to install permissions.
11480                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11481                            for (int userId : currentUserIds) {
11482                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11483                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11484                                    // Transfer the permission flags.
11485                                    permissionsState.updatePermissionFlags(bp, userId,
11486                                            flags, flags);
11487                                    // If we granted the permission, we have to write.
11488                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11489                                            changedRuntimePermissionUserIds, userId);
11490                                }
11491                            }
11492                        }
11493                    } break;
11494
11495                    default: {
11496                        if (packageOfInterest == null
11497                                || packageOfInterest.equals(pkg.packageName)) {
11498                            Slog.w(TAG, "Not granting permission " + perm
11499                                    + " to package " + pkg.packageName
11500                                    + " because it was previously installed without");
11501                        }
11502                    } break;
11503                }
11504            } else {
11505                if (permissionsState.revokeInstallPermission(bp) !=
11506                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11507                    // Also drop the permission flags.
11508                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11509                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11510                    changedInstallPermission = true;
11511                    Slog.i(TAG, "Un-granting permission " + perm
11512                            + " from package " + pkg.packageName
11513                            + " (protectionLevel=" + bp.protectionLevel
11514                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11515                            + ")");
11516                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11517                    // Don't print warning for app op permissions, since it is fine for them
11518                    // not to be granted, there is a UI for the user to decide.
11519                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11520                        Slog.w(TAG, "Not granting permission " + perm
11521                                + " to package " + pkg.packageName
11522                                + " (protectionLevel=" + bp.protectionLevel
11523                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11524                                + ")");
11525                    }
11526                }
11527            }
11528        }
11529
11530        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11531                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11532            // This is the first that we have heard about this package, so the
11533            // permissions we have now selected are fixed until explicitly
11534            // changed.
11535            ps.installPermissionsFixed = true;
11536        }
11537
11538        // Persist the runtime permissions state for users with changes. If permissions
11539        // were revoked because no app in the shared user declares them we have to
11540        // write synchronously to avoid losing runtime permissions state.
11541        for (int userId : changedRuntimePermissionUserIds) {
11542            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11543        }
11544    }
11545
11546    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11547        boolean allowed = false;
11548        final int NP = PackageParser.NEW_PERMISSIONS.length;
11549        for (int ip=0; ip<NP; ip++) {
11550            final PackageParser.NewPermissionInfo npi
11551                    = PackageParser.NEW_PERMISSIONS[ip];
11552            if (npi.name.equals(perm)
11553                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11554                allowed = true;
11555                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11556                        + pkg.packageName);
11557                break;
11558            }
11559        }
11560        return allowed;
11561    }
11562
11563    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11564            BasePermission bp, PermissionsState origPermissions) {
11565        boolean privilegedPermission = (bp.protectionLevel
11566                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11567        boolean privappPermissionsDisable =
11568                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11569        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11570        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11571        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11572                && !platformPackage && platformPermission) {
11573            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11574                    .getPrivAppPermissions(pkg.packageName);
11575            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11576            if (!whitelisted) {
11577                Slog.w(TAG, "Privileged permission " + perm + " for package "
11578                        + pkg.packageName + " - not in privapp-permissions whitelist");
11579                // Only report violations for apps on system image
11580                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11581                    if (mPrivappPermissionsViolations == null) {
11582                        mPrivappPermissionsViolations = new ArraySet<>();
11583                    }
11584                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11585                }
11586                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11587                    return false;
11588                }
11589            }
11590        }
11591        boolean allowed = (compareSignatures(
11592                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11593                        == PackageManager.SIGNATURE_MATCH)
11594                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11595                        == PackageManager.SIGNATURE_MATCH);
11596        if (!allowed && privilegedPermission) {
11597            if (isSystemApp(pkg)) {
11598                // For updated system applications, a system permission
11599                // is granted only if it had been defined by the original application.
11600                if (pkg.isUpdatedSystemApp()) {
11601                    final PackageSetting sysPs = mSettings
11602                            .getDisabledSystemPkgLPr(pkg.packageName);
11603                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11604                        // If the original was granted this permission, we take
11605                        // that grant decision as read and propagate it to the
11606                        // update.
11607                        if (sysPs.isPrivileged()) {
11608                            allowed = true;
11609                        }
11610                    } else {
11611                        // The system apk may have been updated with an older
11612                        // version of the one on the data partition, but which
11613                        // granted a new system permission that it didn't have
11614                        // before.  In this case we do want to allow the app to
11615                        // now get the new permission if the ancestral apk is
11616                        // privileged to get it.
11617                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11618                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11619                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11620                                    allowed = true;
11621                                    break;
11622                                }
11623                            }
11624                        }
11625                        // Also if a privileged parent package on the system image or any of
11626                        // its children requested a privileged permission, the updated child
11627                        // packages can also get the permission.
11628                        if (pkg.parentPackage != null) {
11629                            final PackageSetting disabledSysParentPs = mSettings
11630                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11631                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11632                                    && disabledSysParentPs.isPrivileged()) {
11633                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11634                                    allowed = true;
11635                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11636                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11637                                    for (int i = 0; i < count; i++) {
11638                                        PackageParser.Package disabledSysChildPkg =
11639                                                disabledSysParentPs.pkg.childPackages.get(i);
11640                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11641                                                perm)) {
11642                                            allowed = true;
11643                                            break;
11644                                        }
11645                                    }
11646                                }
11647                            }
11648                        }
11649                    }
11650                } else {
11651                    allowed = isPrivilegedApp(pkg);
11652                }
11653            }
11654        }
11655        if (!allowed) {
11656            if (!allowed && (bp.protectionLevel
11657                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11658                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11659                // If this was a previously normal/dangerous permission that got moved
11660                // to a system permission as part of the runtime permission redesign, then
11661                // we still want to blindly grant it to old apps.
11662                allowed = true;
11663            }
11664            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11665                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11666                // If this permission is to be granted to the system installer and
11667                // this app is an installer, then it gets the permission.
11668                allowed = true;
11669            }
11670            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11671                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11672                // If this permission is to be granted to the system verifier and
11673                // this app is a verifier, then it gets the permission.
11674                allowed = true;
11675            }
11676            if (!allowed && (bp.protectionLevel
11677                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11678                    && isSystemApp(pkg)) {
11679                // Any pre-installed system app is allowed to get this permission.
11680                allowed = true;
11681            }
11682            if (!allowed && (bp.protectionLevel
11683                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11684                // For development permissions, a development permission
11685                // is granted only if it was already granted.
11686                allowed = origPermissions.hasInstallPermission(perm);
11687            }
11688            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11689                    && pkg.packageName.equals(mSetupWizardPackage)) {
11690                // If this permission is to be granted to the system setup wizard and
11691                // this app is a setup wizard, then it gets the permission.
11692                allowed = true;
11693            }
11694        }
11695        return allowed;
11696    }
11697
11698    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11699        final int permCount = pkg.requestedPermissions.size();
11700        for (int j = 0; j < permCount; j++) {
11701            String requestedPermission = pkg.requestedPermissions.get(j);
11702            if (permission.equals(requestedPermission)) {
11703                return true;
11704            }
11705        }
11706        return false;
11707    }
11708
11709    final class ActivityIntentResolver
11710            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11711        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11712                boolean defaultOnly, int userId) {
11713            if (!sUserManager.exists(userId)) return null;
11714            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11715            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11716        }
11717
11718        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11719                int userId) {
11720            if (!sUserManager.exists(userId)) return null;
11721            mFlags = flags;
11722            return super.queryIntent(intent, resolvedType,
11723                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11724                    userId);
11725        }
11726
11727        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11728                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11729            if (!sUserManager.exists(userId)) return null;
11730            if (packageActivities == null) {
11731                return null;
11732            }
11733            mFlags = flags;
11734            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11735            final int N = packageActivities.size();
11736            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11737                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11738
11739            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11740            for (int i = 0; i < N; ++i) {
11741                intentFilters = packageActivities.get(i).intents;
11742                if (intentFilters != null && intentFilters.size() > 0) {
11743                    PackageParser.ActivityIntentInfo[] array =
11744                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11745                    intentFilters.toArray(array);
11746                    listCut.add(array);
11747                }
11748            }
11749            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11750        }
11751
11752        /**
11753         * Finds a privileged activity that matches the specified activity names.
11754         */
11755        private PackageParser.Activity findMatchingActivity(
11756                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11757            for (PackageParser.Activity sysActivity : activityList) {
11758                if (sysActivity.info.name.equals(activityInfo.name)) {
11759                    return sysActivity;
11760                }
11761                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11762                    return sysActivity;
11763                }
11764                if (sysActivity.info.targetActivity != null) {
11765                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11766                        return sysActivity;
11767                    }
11768                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11769                        return sysActivity;
11770                    }
11771                }
11772            }
11773            return null;
11774        }
11775
11776        public class IterGenerator<E> {
11777            public Iterator<E> generate(ActivityIntentInfo info) {
11778                return null;
11779            }
11780        }
11781
11782        public class ActionIterGenerator extends IterGenerator<String> {
11783            @Override
11784            public Iterator<String> generate(ActivityIntentInfo info) {
11785                return info.actionsIterator();
11786            }
11787        }
11788
11789        public class CategoriesIterGenerator extends IterGenerator<String> {
11790            @Override
11791            public Iterator<String> generate(ActivityIntentInfo info) {
11792                return info.categoriesIterator();
11793            }
11794        }
11795
11796        public class SchemesIterGenerator extends IterGenerator<String> {
11797            @Override
11798            public Iterator<String> generate(ActivityIntentInfo info) {
11799                return info.schemesIterator();
11800            }
11801        }
11802
11803        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11804            @Override
11805            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11806                return info.authoritiesIterator();
11807            }
11808        }
11809
11810        /**
11811         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11812         * MODIFIED. Do not pass in a list that should not be changed.
11813         */
11814        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11815                IterGenerator<T> generator, Iterator<T> searchIterator) {
11816            // loop through the set of actions; every one must be found in the intent filter
11817            while (searchIterator.hasNext()) {
11818                // we must have at least one filter in the list to consider a match
11819                if (intentList.size() == 0) {
11820                    break;
11821                }
11822
11823                final T searchAction = searchIterator.next();
11824
11825                // loop through the set of intent filters
11826                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11827                while (intentIter.hasNext()) {
11828                    final ActivityIntentInfo intentInfo = intentIter.next();
11829                    boolean selectionFound = false;
11830
11831                    // loop through the intent filter's selection criteria; at least one
11832                    // of them must match the searched criteria
11833                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11834                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11835                        final T intentSelection = intentSelectionIter.next();
11836                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11837                            selectionFound = true;
11838                            break;
11839                        }
11840                    }
11841
11842                    // the selection criteria wasn't found in this filter's set; this filter
11843                    // is not a potential match
11844                    if (!selectionFound) {
11845                        intentIter.remove();
11846                    }
11847                }
11848            }
11849        }
11850
11851        private boolean isProtectedAction(ActivityIntentInfo filter) {
11852            final Iterator<String> actionsIter = filter.actionsIterator();
11853            while (actionsIter != null && actionsIter.hasNext()) {
11854                final String filterAction = actionsIter.next();
11855                if (PROTECTED_ACTIONS.contains(filterAction)) {
11856                    return true;
11857                }
11858            }
11859            return false;
11860        }
11861
11862        /**
11863         * Adjusts the priority of the given intent filter according to policy.
11864         * <p>
11865         * <ul>
11866         * <li>The priority for non privileged applications is capped to '0'</li>
11867         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11868         * <li>The priority for unbundled updates to privileged applications is capped to the
11869         *      priority defined on the system partition</li>
11870         * </ul>
11871         * <p>
11872         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11873         * allowed to obtain any priority on any action.
11874         */
11875        private void adjustPriority(
11876                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11877            // nothing to do; priority is fine as-is
11878            if (intent.getPriority() <= 0) {
11879                return;
11880            }
11881
11882            final ActivityInfo activityInfo = intent.activity.info;
11883            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11884
11885            final boolean privilegedApp =
11886                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11887            if (!privilegedApp) {
11888                // non-privileged applications can never define a priority >0
11889                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11890                        + " package: " + applicationInfo.packageName
11891                        + " activity: " + intent.activity.className
11892                        + " origPrio: " + intent.getPriority());
11893                intent.setPriority(0);
11894                return;
11895            }
11896
11897            if (systemActivities == null) {
11898                // the system package is not disabled; we're parsing the system partition
11899                if (isProtectedAction(intent)) {
11900                    if (mDeferProtectedFilters) {
11901                        // We can't deal with these just yet. No component should ever obtain a
11902                        // >0 priority for a protected actions, with ONE exception -- the setup
11903                        // wizard. The setup wizard, however, cannot be known until we're able to
11904                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11905                        // until all intent filters have been processed. Chicken, meet egg.
11906                        // Let the filter temporarily have a high priority and rectify the
11907                        // priorities after all system packages have been scanned.
11908                        mProtectedFilters.add(intent);
11909                        if (DEBUG_FILTERS) {
11910                            Slog.i(TAG, "Protected action; save for later;"
11911                                    + " package: " + applicationInfo.packageName
11912                                    + " activity: " + intent.activity.className
11913                                    + " origPrio: " + intent.getPriority());
11914                        }
11915                        return;
11916                    } else {
11917                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11918                            Slog.i(TAG, "No setup wizard;"
11919                                + " All protected intents capped to priority 0");
11920                        }
11921                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11922                            if (DEBUG_FILTERS) {
11923                                Slog.i(TAG, "Found setup wizard;"
11924                                    + " allow priority " + intent.getPriority() + ";"
11925                                    + " package: " + intent.activity.info.packageName
11926                                    + " activity: " + intent.activity.className
11927                                    + " priority: " + intent.getPriority());
11928                            }
11929                            // setup wizard gets whatever it wants
11930                            return;
11931                        }
11932                        Slog.w(TAG, "Protected action; cap priority to 0;"
11933                                + " package: " + intent.activity.info.packageName
11934                                + " activity: " + intent.activity.className
11935                                + " origPrio: " + intent.getPriority());
11936                        intent.setPriority(0);
11937                        return;
11938                    }
11939                }
11940                // privileged apps on the system image get whatever priority they request
11941                return;
11942            }
11943
11944            // privileged app unbundled update ... try to find the same activity
11945            final PackageParser.Activity foundActivity =
11946                    findMatchingActivity(systemActivities, activityInfo);
11947            if (foundActivity == null) {
11948                // this is a new activity; it cannot obtain >0 priority
11949                if (DEBUG_FILTERS) {
11950                    Slog.i(TAG, "New activity; cap priority to 0;"
11951                            + " package: " + applicationInfo.packageName
11952                            + " activity: " + intent.activity.className
11953                            + " origPrio: " + intent.getPriority());
11954                }
11955                intent.setPriority(0);
11956                return;
11957            }
11958
11959            // found activity, now check for filter equivalence
11960
11961            // a shallow copy is enough; we modify the list, not its contents
11962            final List<ActivityIntentInfo> intentListCopy =
11963                    new ArrayList<>(foundActivity.intents);
11964            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11965
11966            // find matching action subsets
11967            final Iterator<String> actionsIterator = intent.actionsIterator();
11968            if (actionsIterator != null) {
11969                getIntentListSubset(
11970                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11971                if (intentListCopy.size() == 0) {
11972                    // no more intents to match; we're not equivalent
11973                    if (DEBUG_FILTERS) {
11974                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11975                                + " package: " + applicationInfo.packageName
11976                                + " activity: " + intent.activity.className
11977                                + " origPrio: " + intent.getPriority());
11978                    }
11979                    intent.setPriority(0);
11980                    return;
11981                }
11982            }
11983
11984            // find matching category subsets
11985            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11986            if (categoriesIterator != null) {
11987                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11988                        categoriesIterator);
11989                if (intentListCopy.size() == 0) {
11990                    // no more intents to match; we're not equivalent
11991                    if (DEBUG_FILTERS) {
11992                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11993                                + " package: " + applicationInfo.packageName
11994                                + " activity: " + intent.activity.className
11995                                + " origPrio: " + intent.getPriority());
11996                    }
11997                    intent.setPriority(0);
11998                    return;
11999                }
12000            }
12001
12002            // find matching schemes subsets
12003            final Iterator<String> schemesIterator = intent.schemesIterator();
12004            if (schemesIterator != null) {
12005                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12006                        schemesIterator);
12007                if (intentListCopy.size() == 0) {
12008                    // no more intents to match; we're not equivalent
12009                    if (DEBUG_FILTERS) {
12010                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12011                                + " package: " + applicationInfo.packageName
12012                                + " activity: " + intent.activity.className
12013                                + " origPrio: " + intent.getPriority());
12014                    }
12015                    intent.setPriority(0);
12016                    return;
12017                }
12018            }
12019
12020            // find matching authorities subsets
12021            final Iterator<IntentFilter.AuthorityEntry>
12022                    authoritiesIterator = intent.authoritiesIterator();
12023            if (authoritiesIterator != null) {
12024                getIntentListSubset(intentListCopy,
12025                        new AuthoritiesIterGenerator(),
12026                        authoritiesIterator);
12027                if (intentListCopy.size() == 0) {
12028                    // no more intents to match; we're not equivalent
12029                    if (DEBUG_FILTERS) {
12030                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12031                                + " package: " + applicationInfo.packageName
12032                                + " activity: " + intent.activity.className
12033                                + " origPrio: " + intent.getPriority());
12034                    }
12035                    intent.setPriority(0);
12036                    return;
12037                }
12038            }
12039
12040            // we found matching filter(s); app gets the max priority of all intents
12041            int cappedPriority = 0;
12042            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12043                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12044            }
12045            if (intent.getPriority() > cappedPriority) {
12046                if (DEBUG_FILTERS) {
12047                    Slog.i(TAG, "Found matching filter(s);"
12048                            + " cap priority to " + cappedPriority + ";"
12049                            + " package: " + applicationInfo.packageName
12050                            + " activity: " + intent.activity.className
12051                            + " origPrio: " + intent.getPriority());
12052                }
12053                intent.setPriority(cappedPriority);
12054                return;
12055            }
12056            // all this for nothing; the requested priority was <= what was on the system
12057        }
12058
12059        public final void addActivity(PackageParser.Activity a, String type) {
12060            mActivities.put(a.getComponentName(), a);
12061            if (DEBUG_SHOW_INFO)
12062                Log.v(
12063                TAG, "  " + type + " " +
12064                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12065            if (DEBUG_SHOW_INFO)
12066                Log.v(TAG, "    Class=" + a.info.name);
12067            final int NI = a.intents.size();
12068            for (int j=0; j<NI; j++) {
12069                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12070                if ("activity".equals(type)) {
12071                    final PackageSetting ps =
12072                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12073                    final List<PackageParser.Activity> systemActivities =
12074                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12075                    adjustPriority(systemActivities, intent);
12076                }
12077                if (DEBUG_SHOW_INFO) {
12078                    Log.v(TAG, "    IntentFilter:");
12079                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12080                }
12081                if (!intent.debugCheck()) {
12082                    Log.w(TAG, "==> For Activity " + a.info.name);
12083                }
12084                addFilter(intent);
12085            }
12086        }
12087
12088        public final void removeActivity(PackageParser.Activity a, String type) {
12089            mActivities.remove(a.getComponentName());
12090            if (DEBUG_SHOW_INFO) {
12091                Log.v(TAG, "  " + type + " "
12092                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12093                                : a.info.name) + ":");
12094                Log.v(TAG, "    Class=" + a.info.name);
12095            }
12096            final int NI = a.intents.size();
12097            for (int j=0; j<NI; j++) {
12098                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12099                if (DEBUG_SHOW_INFO) {
12100                    Log.v(TAG, "    IntentFilter:");
12101                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12102                }
12103                removeFilter(intent);
12104            }
12105        }
12106
12107        @Override
12108        protected boolean allowFilterResult(
12109                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12110            ActivityInfo filterAi = filter.activity.info;
12111            for (int i=dest.size()-1; i>=0; i--) {
12112                ActivityInfo destAi = dest.get(i).activityInfo;
12113                if (destAi.name == filterAi.name
12114                        && destAi.packageName == filterAi.packageName) {
12115                    return false;
12116                }
12117            }
12118            return true;
12119        }
12120
12121        @Override
12122        protected ActivityIntentInfo[] newArray(int size) {
12123            return new ActivityIntentInfo[size];
12124        }
12125
12126        @Override
12127        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12128            if (!sUserManager.exists(userId)) return true;
12129            PackageParser.Package p = filter.activity.owner;
12130            if (p != null) {
12131                PackageSetting ps = (PackageSetting)p.mExtras;
12132                if (ps != null) {
12133                    // System apps are never considered stopped for purposes of
12134                    // filtering, because there may be no way for the user to
12135                    // actually re-launch them.
12136                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12137                            && ps.getStopped(userId);
12138                }
12139            }
12140            return false;
12141        }
12142
12143        @Override
12144        protected boolean isPackageForFilter(String packageName,
12145                PackageParser.ActivityIntentInfo info) {
12146            return packageName.equals(info.activity.owner.packageName);
12147        }
12148
12149        @Override
12150        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12151                int match, int userId) {
12152            if (!sUserManager.exists(userId)) return null;
12153            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12154                return null;
12155            }
12156            final PackageParser.Activity activity = info.activity;
12157            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12158            if (ps == null) {
12159                return null;
12160            }
12161            final PackageUserState userState = ps.readUserState(userId);
12162            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12163                    userState, userId);
12164            if (ai == null) {
12165                return null;
12166            }
12167            final boolean matchVisibleToInstantApp =
12168                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12169            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12170            // throw out filters that aren't visible to ephemeral apps
12171            if (matchVisibleToInstantApp
12172                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12173                return null;
12174            }
12175            // throw out ephemeral filters if we're not explicitly requesting them
12176            if (!isInstantApp && userState.instantApp) {
12177                return null;
12178            }
12179            // throw out instant app filters if updates are available; will trigger
12180            // instant app resolution
12181            if (userState.instantApp && ps.isUpdateAvailable()) {
12182                return null;
12183            }
12184            final ResolveInfo res = new ResolveInfo();
12185            res.activityInfo = ai;
12186            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12187                res.filter = info;
12188            }
12189            if (info != null) {
12190                res.handleAllWebDataURI = info.handleAllWebDataURI();
12191            }
12192            res.priority = info.getPriority();
12193            res.preferredOrder = activity.owner.mPreferredOrder;
12194            //System.out.println("Result: " + res.activityInfo.className +
12195            //                   " = " + res.priority);
12196            res.match = match;
12197            res.isDefault = info.hasDefault;
12198            res.labelRes = info.labelRes;
12199            res.nonLocalizedLabel = info.nonLocalizedLabel;
12200            if (userNeedsBadging(userId)) {
12201                res.noResourceId = true;
12202            } else {
12203                res.icon = info.icon;
12204            }
12205            res.iconResourceId = info.icon;
12206            res.system = res.activityInfo.applicationInfo.isSystemApp();
12207            res.instantAppAvailable = userState.instantApp;
12208            return res;
12209        }
12210
12211        @Override
12212        protected void sortResults(List<ResolveInfo> results) {
12213            Collections.sort(results, mResolvePrioritySorter);
12214        }
12215
12216        @Override
12217        protected void dumpFilter(PrintWriter out, String prefix,
12218                PackageParser.ActivityIntentInfo filter) {
12219            out.print(prefix); out.print(
12220                    Integer.toHexString(System.identityHashCode(filter.activity)));
12221                    out.print(' ');
12222                    filter.activity.printComponentShortName(out);
12223                    out.print(" filter ");
12224                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12225        }
12226
12227        @Override
12228        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12229            return filter.activity;
12230        }
12231
12232        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12233            PackageParser.Activity activity = (PackageParser.Activity)label;
12234            out.print(prefix); out.print(
12235                    Integer.toHexString(System.identityHashCode(activity)));
12236                    out.print(' ');
12237                    activity.printComponentShortName(out);
12238            if (count > 1) {
12239                out.print(" ("); out.print(count); out.print(" filters)");
12240            }
12241            out.println();
12242        }
12243
12244        // Keys are String (activity class name), values are Activity.
12245        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12246                = new ArrayMap<ComponentName, PackageParser.Activity>();
12247        private int mFlags;
12248    }
12249
12250    private final class ServiceIntentResolver
12251            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12252        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12253                boolean defaultOnly, int userId) {
12254            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12255            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12256        }
12257
12258        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12259                int userId) {
12260            if (!sUserManager.exists(userId)) return null;
12261            mFlags = flags;
12262            return super.queryIntent(intent, resolvedType,
12263                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12264                    userId);
12265        }
12266
12267        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12268                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12269            if (!sUserManager.exists(userId)) return null;
12270            if (packageServices == null) {
12271                return null;
12272            }
12273            mFlags = flags;
12274            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12275            final int N = packageServices.size();
12276            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12277                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12278
12279            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12280            for (int i = 0; i < N; ++i) {
12281                intentFilters = packageServices.get(i).intents;
12282                if (intentFilters != null && intentFilters.size() > 0) {
12283                    PackageParser.ServiceIntentInfo[] array =
12284                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12285                    intentFilters.toArray(array);
12286                    listCut.add(array);
12287                }
12288            }
12289            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12290        }
12291
12292        public final void addService(PackageParser.Service s) {
12293            mServices.put(s.getComponentName(), s);
12294            if (DEBUG_SHOW_INFO) {
12295                Log.v(TAG, "  "
12296                        + (s.info.nonLocalizedLabel != null
12297                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12298                Log.v(TAG, "    Class=" + s.info.name);
12299            }
12300            final int NI = s.intents.size();
12301            int j;
12302            for (j=0; j<NI; j++) {
12303                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12304                if (DEBUG_SHOW_INFO) {
12305                    Log.v(TAG, "    IntentFilter:");
12306                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12307                }
12308                if (!intent.debugCheck()) {
12309                    Log.w(TAG, "==> For Service " + s.info.name);
12310                }
12311                addFilter(intent);
12312            }
12313        }
12314
12315        public final void removeService(PackageParser.Service s) {
12316            mServices.remove(s.getComponentName());
12317            if (DEBUG_SHOW_INFO) {
12318                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12319                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12320                Log.v(TAG, "    Class=" + s.info.name);
12321            }
12322            final int NI = s.intents.size();
12323            int j;
12324            for (j=0; j<NI; j++) {
12325                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12326                if (DEBUG_SHOW_INFO) {
12327                    Log.v(TAG, "    IntentFilter:");
12328                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12329                }
12330                removeFilter(intent);
12331            }
12332        }
12333
12334        @Override
12335        protected boolean allowFilterResult(
12336                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12337            ServiceInfo filterSi = filter.service.info;
12338            for (int i=dest.size()-1; i>=0; i--) {
12339                ServiceInfo destAi = dest.get(i).serviceInfo;
12340                if (destAi.name == filterSi.name
12341                        && destAi.packageName == filterSi.packageName) {
12342                    return false;
12343                }
12344            }
12345            return true;
12346        }
12347
12348        @Override
12349        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12350            return new PackageParser.ServiceIntentInfo[size];
12351        }
12352
12353        @Override
12354        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12355            if (!sUserManager.exists(userId)) return true;
12356            PackageParser.Package p = filter.service.owner;
12357            if (p != null) {
12358                PackageSetting ps = (PackageSetting)p.mExtras;
12359                if (ps != null) {
12360                    // System apps are never considered stopped for purposes of
12361                    // filtering, because there may be no way for the user to
12362                    // actually re-launch them.
12363                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12364                            && ps.getStopped(userId);
12365                }
12366            }
12367            return false;
12368        }
12369
12370        @Override
12371        protected boolean isPackageForFilter(String packageName,
12372                PackageParser.ServiceIntentInfo info) {
12373            return packageName.equals(info.service.owner.packageName);
12374        }
12375
12376        @Override
12377        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12378                int match, int userId) {
12379            if (!sUserManager.exists(userId)) return null;
12380            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12381            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12382                return null;
12383            }
12384            final PackageParser.Service service = info.service;
12385            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12386            if (ps == null) {
12387                return null;
12388            }
12389            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12390                    ps.readUserState(userId), userId);
12391            if (si == null) {
12392                return null;
12393            }
12394            final ResolveInfo res = new ResolveInfo();
12395            res.serviceInfo = si;
12396            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12397                res.filter = filter;
12398            }
12399            res.priority = info.getPriority();
12400            res.preferredOrder = service.owner.mPreferredOrder;
12401            res.match = match;
12402            res.isDefault = info.hasDefault;
12403            res.labelRes = info.labelRes;
12404            res.nonLocalizedLabel = info.nonLocalizedLabel;
12405            res.icon = info.icon;
12406            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12407            return res;
12408        }
12409
12410        @Override
12411        protected void sortResults(List<ResolveInfo> results) {
12412            Collections.sort(results, mResolvePrioritySorter);
12413        }
12414
12415        @Override
12416        protected void dumpFilter(PrintWriter out, String prefix,
12417                PackageParser.ServiceIntentInfo filter) {
12418            out.print(prefix); out.print(
12419                    Integer.toHexString(System.identityHashCode(filter.service)));
12420                    out.print(' ');
12421                    filter.service.printComponentShortName(out);
12422                    out.print(" filter ");
12423                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12424        }
12425
12426        @Override
12427        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12428            return filter.service;
12429        }
12430
12431        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12432            PackageParser.Service service = (PackageParser.Service)label;
12433            out.print(prefix); out.print(
12434                    Integer.toHexString(System.identityHashCode(service)));
12435                    out.print(' ');
12436                    service.printComponentShortName(out);
12437            if (count > 1) {
12438                out.print(" ("); out.print(count); out.print(" filters)");
12439            }
12440            out.println();
12441        }
12442
12443//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12444//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12445//            final List<ResolveInfo> retList = Lists.newArrayList();
12446//            while (i.hasNext()) {
12447//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12448//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12449//                    retList.add(resolveInfo);
12450//                }
12451//            }
12452//            return retList;
12453//        }
12454
12455        // Keys are String (activity class name), values are Activity.
12456        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12457                = new ArrayMap<ComponentName, PackageParser.Service>();
12458        private int mFlags;
12459    }
12460
12461    private final class ProviderIntentResolver
12462            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12463        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12464                boolean defaultOnly, int userId) {
12465            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12466            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12467        }
12468
12469        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12470                int userId) {
12471            if (!sUserManager.exists(userId))
12472                return null;
12473            mFlags = flags;
12474            return super.queryIntent(intent, resolvedType,
12475                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12476                    userId);
12477        }
12478
12479        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12480                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12481            if (!sUserManager.exists(userId))
12482                return null;
12483            if (packageProviders == null) {
12484                return null;
12485            }
12486            mFlags = flags;
12487            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12488            final int N = packageProviders.size();
12489            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12490                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12491
12492            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12493            for (int i = 0; i < N; ++i) {
12494                intentFilters = packageProviders.get(i).intents;
12495                if (intentFilters != null && intentFilters.size() > 0) {
12496                    PackageParser.ProviderIntentInfo[] array =
12497                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12498                    intentFilters.toArray(array);
12499                    listCut.add(array);
12500                }
12501            }
12502            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12503        }
12504
12505        public final void addProvider(PackageParser.Provider p) {
12506            if (mProviders.containsKey(p.getComponentName())) {
12507                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12508                return;
12509            }
12510
12511            mProviders.put(p.getComponentName(), p);
12512            if (DEBUG_SHOW_INFO) {
12513                Log.v(TAG, "  "
12514                        + (p.info.nonLocalizedLabel != null
12515                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12516                Log.v(TAG, "    Class=" + p.info.name);
12517            }
12518            final int NI = p.intents.size();
12519            int j;
12520            for (j = 0; j < NI; j++) {
12521                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12522                if (DEBUG_SHOW_INFO) {
12523                    Log.v(TAG, "    IntentFilter:");
12524                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12525                }
12526                if (!intent.debugCheck()) {
12527                    Log.w(TAG, "==> For Provider " + p.info.name);
12528                }
12529                addFilter(intent);
12530            }
12531        }
12532
12533        public final void removeProvider(PackageParser.Provider p) {
12534            mProviders.remove(p.getComponentName());
12535            if (DEBUG_SHOW_INFO) {
12536                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12537                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12538                Log.v(TAG, "    Class=" + p.info.name);
12539            }
12540            final int NI = p.intents.size();
12541            int j;
12542            for (j = 0; j < NI; j++) {
12543                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12544                if (DEBUG_SHOW_INFO) {
12545                    Log.v(TAG, "    IntentFilter:");
12546                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12547                }
12548                removeFilter(intent);
12549            }
12550        }
12551
12552        @Override
12553        protected boolean allowFilterResult(
12554                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12555            ProviderInfo filterPi = filter.provider.info;
12556            for (int i = dest.size() - 1; i >= 0; i--) {
12557                ProviderInfo destPi = dest.get(i).providerInfo;
12558                if (destPi.name == filterPi.name
12559                        && destPi.packageName == filterPi.packageName) {
12560                    return false;
12561                }
12562            }
12563            return true;
12564        }
12565
12566        @Override
12567        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12568            return new PackageParser.ProviderIntentInfo[size];
12569        }
12570
12571        @Override
12572        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12573            if (!sUserManager.exists(userId))
12574                return true;
12575            PackageParser.Package p = filter.provider.owner;
12576            if (p != null) {
12577                PackageSetting ps = (PackageSetting) p.mExtras;
12578                if (ps != null) {
12579                    // System apps are never considered stopped for purposes of
12580                    // filtering, because there may be no way for the user to
12581                    // actually re-launch them.
12582                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12583                            && ps.getStopped(userId);
12584                }
12585            }
12586            return false;
12587        }
12588
12589        @Override
12590        protected boolean isPackageForFilter(String packageName,
12591                PackageParser.ProviderIntentInfo info) {
12592            return packageName.equals(info.provider.owner.packageName);
12593        }
12594
12595        @Override
12596        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12597                int match, int userId) {
12598            if (!sUserManager.exists(userId))
12599                return null;
12600            final PackageParser.ProviderIntentInfo info = filter;
12601            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12602                return null;
12603            }
12604            final PackageParser.Provider provider = info.provider;
12605            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12606            if (ps == null) {
12607                return null;
12608            }
12609            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12610                    ps.readUserState(userId), userId);
12611            if (pi == null) {
12612                return null;
12613            }
12614            final ResolveInfo res = new ResolveInfo();
12615            res.providerInfo = pi;
12616            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12617                res.filter = filter;
12618            }
12619            res.priority = info.getPriority();
12620            res.preferredOrder = provider.owner.mPreferredOrder;
12621            res.match = match;
12622            res.isDefault = info.hasDefault;
12623            res.labelRes = info.labelRes;
12624            res.nonLocalizedLabel = info.nonLocalizedLabel;
12625            res.icon = info.icon;
12626            res.system = res.providerInfo.applicationInfo.isSystemApp();
12627            return res;
12628        }
12629
12630        @Override
12631        protected void sortResults(List<ResolveInfo> results) {
12632            Collections.sort(results, mResolvePrioritySorter);
12633        }
12634
12635        @Override
12636        protected void dumpFilter(PrintWriter out, String prefix,
12637                PackageParser.ProviderIntentInfo filter) {
12638            out.print(prefix);
12639            out.print(
12640                    Integer.toHexString(System.identityHashCode(filter.provider)));
12641            out.print(' ');
12642            filter.provider.printComponentShortName(out);
12643            out.print(" filter ");
12644            out.println(Integer.toHexString(System.identityHashCode(filter)));
12645        }
12646
12647        @Override
12648        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12649            return filter.provider;
12650        }
12651
12652        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12653            PackageParser.Provider provider = (PackageParser.Provider)label;
12654            out.print(prefix); out.print(
12655                    Integer.toHexString(System.identityHashCode(provider)));
12656                    out.print(' ');
12657                    provider.printComponentShortName(out);
12658            if (count > 1) {
12659                out.print(" ("); out.print(count); out.print(" filters)");
12660            }
12661            out.println();
12662        }
12663
12664        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12665                = new ArrayMap<ComponentName, PackageParser.Provider>();
12666        private int mFlags;
12667    }
12668
12669    static final class EphemeralIntentResolver
12670            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12671        /**
12672         * The result that has the highest defined order. Ordering applies on a
12673         * per-package basis. Mapping is from package name to Pair of order and
12674         * EphemeralResolveInfo.
12675         * <p>
12676         * NOTE: This is implemented as a field variable for convenience and efficiency.
12677         * By having a field variable, we're able to track filter ordering as soon as
12678         * a non-zero order is defined. Otherwise, multiple loops across the result set
12679         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12680         * this needs to be contained entirely within {@link #filterResults}.
12681         */
12682        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12683
12684        @Override
12685        protected AuxiliaryResolveInfo[] newArray(int size) {
12686            return new AuxiliaryResolveInfo[size];
12687        }
12688
12689        @Override
12690        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12691            return true;
12692        }
12693
12694        @Override
12695        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12696                int userId) {
12697            if (!sUserManager.exists(userId)) {
12698                return null;
12699            }
12700            final String packageName = responseObj.resolveInfo.getPackageName();
12701            final Integer order = responseObj.getOrder();
12702            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12703                    mOrderResult.get(packageName);
12704            // ordering is enabled and this item's order isn't high enough
12705            if (lastOrderResult != null && lastOrderResult.first >= order) {
12706                return null;
12707            }
12708            final InstantAppResolveInfo res = responseObj.resolveInfo;
12709            if (order > 0) {
12710                // non-zero order, enable ordering
12711                mOrderResult.put(packageName, new Pair<>(order, res));
12712            }
12713            return responseObj;
12714        }
12715
12716        @Override
12717        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12718            // only do work if ordering is enabled [most of the time it won't be]
12719            if (mOrderResult.size() == 0) {
12720                return;
12721            }
12722            int resultSize = results.size();
12723            for (int i = 0; i < resultSize; i++) {
12724                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12725                final String packageName = info.getPackageName();
12726                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12727                if (savedInfo == null) {
12728                    // package doesn't having ordering
12729                    continue;
12730                }
12731                if (savedInfo.second == info) {
12732                    // circled back to the highest ordered item; remove from order list
12733                    mOrderResult.remove(savedInfo);
12734                    if (mOrderResult.size() == 0) {
12735                        // no more ordered items
12736                        break;
12737                    }
12738                    continue;
12739                }
12740                // item has a worse order, remove it from the result list
12741                results.remove(i);
12742                resultSize--;
12743                i--;
12744            }
12745        }
12746    }
12747
12748    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12749            new Comparator<ResolveInfo>() {
12750        public int compare(ResolveInfo r1, ResolveInfo r2) {
12751            int v1 = r1.priority;
12752            int v2 = r2.priority;
12753            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12754            if (v1 != v2) {
12755                return (v1 > v2) ? -1 : 1;
12756            }
12757            v1 = r1.preferredOrder;
12758            v2 = r2.preferredOrder;
12759            if (v1 != v2) {
12760                return (v1 > v2) ? -1 : 1;
12761            }
12762            if (r1.isDefault != r2.isDefault) {
12763                return r1.isDefault ? -1 : 1;
12764            }
12765            v1 = r1.match;
12766            v2 = r2.match;
12767            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12768            if (v1 != v2) {
12769                return (v1 > v2) ? -1 : 1;
12770            }
12771            if (r1.system != r2.system) {
12772                return r1.system ? -1 : 1;
12773            }
12774            if (r1.activityInfo != null) {
12775                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12776            }
12777            if (r1.serviceInfo != null) {
12778                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12779            }
12780            if (r1.providerInfo != null) {
12781                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12782            }
12783            return 0;
12784        }
12785    };
12786
12787    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12788            new Comparator<ProviderInfo>() {
12789        public int compare(ProviderInfo p1, ProviderInfo p2) {
12790            final int v1 = p1.initOrder;
12791            final int v2 = p2.initOrder;
12792            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12793        }
12794    };
12795
12796    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12797            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12798            final int[] userIds) {
12799        mHandler.post(new Runnable() {
12800            @Override
12801            public void run() {
12802                try {
12803                    final IActivityManager am = ActivityManager.getService();
12804                    if (am == null) return;
12805                    final int[] resolvedUserIds;
12806                    if (userIds == null) {
12807                        resolvedUserIds = am.getRunningUserIds();
12808                    } else {
12809                        resolvedUserIds = userIds;
12810                    }
12811                    for (int id : resolvedUserIds) {
12812                        final Intent intent = new Intent(action,
12813                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12814                        if (extras != null) {
12815                            intent.putExtras(extras);
12816                        }
12817                        if (targetPkg != null) {
12818                            intent.setPackage(targetPkg);
12819                        }
12820                        // Modify the UID when posting to other users
12821                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12822                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12823                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12824                            intent.putExtra(Intent.EXTRA_UID, uid);
12825                        }
12826                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12827                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12828                        if (DEBUG_BROADCASTS) {
12829                            RuntimeException here = new RuntimeException("here");
12830                            here.fillInStackTrace();
12831                            Slog.d(TAG, "Sending to user " + id + ": "
12832                                    + intent.toShortString(false, true, false, false)
12833                                    + " " + intent.getExtras(), here);
12834                        }
12835                        am.broadcastIntent(null, intent, null, finishedReceiver,
12836                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12837                                null, finishedReceiver != null, false, id);
12838                    }
12839                } catch (RemoteException ex) {
12840                }
12841            }
12842        });
12843    }
12844
12845    /**
12846     * Check if the external storage media is available. This is true if there
12847     * is a mounted external storage medium or if the external storage is
12848     * emulated.
12849     */
12850    private boolean isExternalMediaAvailable() {
12851        return mMediaMounted || Environment.isExternalStorageEmulated();
12852    }
12853
12854    @Override
12855    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12856        // writer
12857        synchronized (mPackages) {
12858            if (!isExternalMediaAvailable()) {
12859                // If the external storage is no longer mounted at this point,
12860                // the caller may not have been able to delete all of this
12861                // packages files and can not delete any more.  Bail.
12862                return null;
12863            }
12864            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12865            if (lastPackage != null) {
12866                pkgs.remove(lastPackage);
12867            }
12868            if (pkgs.size() > 0) {
12869                return pkgs.get(0);
12870            }
12871        }
12872        return null;
12873    }
12874
12875    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12876        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12877                userId, andCode ? 1 : 0, packageName);
12878        if (mSystemReady) {
12879            msg.sendToTarget();
12880        } else {
12881            if (mPostSystemReadyMessages == null) {
12882                mPostSystemReadyMessages = new ArrayList<>();
12883            }
12884            mPostSystemReadyMessages.add(msg);
12885        }
12886    }
12887
12888    void startCleaningPackages() {
12889        // reader
12890        if (!isExternalMediaAvailable()) {
12891            return;
12892        }
12893        synchronized (mPackages) {
12894            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12895                return;
12896            }
12897        }
12898        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12899        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12900        IActivityManager am = ActivityManager.getService();
12901        if (am != null) {
12902            try {
12903                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12904                        UserHandle.USER_SYSTEM);
12905            } catch (RemoteException e) {
12906            }
12907        }
12908    }
12909
12910    @Override
12911    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12912            int installFlags, String installerPackageName, int userId) {
12913        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12914
12915        final int callingUid = Binder.getCallingUid();
12916        enforceCrossUserPermission(callingUid, userId,
12917                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12918
12919        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12920            try {
12921                if (observer != null) {
12922                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12923                }
12924            } catch (RemoteException re) {
12925            }
12926            return;
12927        }
12928
12929        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12930            installFlags |= PackageManager.INSTALL_FROM_ADB;
12931
12932        } else {
12933            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12934            // about installerPackageName.
12935
12936            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12937            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12938        }
12939
12940        UserHandle user;
12941        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12942            user = UserHandle.ALL;
12943        } else {
12944            user = new UserHandle(userId);
12945        }
12946
12947        // Only system components can circumvent runtime permissions when installing.
12948        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12949                && mContext.checkCallingOrSelfPermission(Manifest.permission
12950                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12951            throw new SecurityException("You need the "
12952                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12953                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12954        }
12955
12956        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12957                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12958            throw new IllegalArgumentException(
12959                    "New installs into ASEC containers no longer supported");
12960        }
12961
12962        final File originFile = new File(originPath);
12963        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12964
12965        final Message msg = mHandler.obtainMessage(INIT_COPY);
12966        final VerificationInfo verificationInfo = new VerificationInfo(
12967                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12968        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12969                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12970                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12971                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12972        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12973        msg.obj = params;
12974
12975        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12976                System.identityHashCode(msg.obj));
12977        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12978                System.identityHashCode(msg.obj));
12979
12980        mHandler.sendMessage(msg);
12981    }
12982
12983
12984    /**
12985     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12986     * it is acting on behalf on an enterprise or the user).
12987     *
12988     * Note that the ordering of the conditionals in this method is important. The checks we perform
12989     * are as follows, in this order:
12990     *
12991     * 1) If the install is being performed by a system app, we can trust the app to have set the
12992     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12993     *    what it is.
12994     * 2) If the install is being performed by a device or profile owner app, the install reason
12995     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12996     *    set the install reason correctly. If the app targets an older SDK version where install
12997     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12998     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12999     * 3) In all other cases, the install is being performed by a regular app that is neither part
13000     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13001     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13002     *    set to enterprise policy and if so, change it to unknown instead.
13003     */
13004    private int fixUpInstallReason(String installerPackageName, int installerUid,
13005            int installReason) {
13006        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13007                == PERMISSION_GRANTED) {
13008            // If the install is being performed by a system app, we trust that app to have set the
13009            // install reason correctly.
13010            return installReason;
13011        }
13012
13013        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13014            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13015        if (dpm != null) {
13016            ComponentName owner = null;
13017            try {
13018                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13019                if (owner == null) {
13020                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13021                }
13022            } catch (RemoteException e) {
13023            }
13024            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13025                // If the install is being performed by a device or profile owner, the install
13026                // reason should be enterprise policy.
13027                return PackageManager.INSTALL_REASON_POLICY;
13028            }
13029        }
13030
13031        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13032            // If the install is being performed by a regular app (i.e. neither system app nor
13033            // device or profile owner), we have no reason to believe that the app is acting on
13034            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13035            // change it to unknown instead.
13036            return PackageManager.INSTALL_REASON_UNKNOWN;
13037        }
13038
13039        // If the install is being performed by a regular app and the install reason was set to any
13040        // value but enterprise policy, leave the install reason unchanged.
13041        return installReason;
13042    }
13043
13044    void installStage(String packageName, File stagedDir, String stagedCid,
13045            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13046            String installerPackageName, int installerUid, UserHandle user,
13047            Certificate[][] certificates) {
13048        if (DEBUG_EPHEMERAL) {
13049            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13050                Slog.d(TAG, "Ephemeral install of " + packageName);
13051            }
13052        }
13053        final VerificationInfo verificationInfo = new VerificationInfo(
13054                sessionParams.originatingUri, sessionParams.referrerUri,
13055                sessionParams.originatingUid, installerUid);
13056
13057        final OriginInfo origin;
13058        if (stagedDir != null) {
13059            origin = OriginInfo.fromStagedFile(stagedDir);
13060        } else {
13061            origin = OriginInfo.fromStagedContainer(stagedCid);
13062        }
13063
13064        final Message msg = mHandler.obtainMessage(INIT_COPY);
13065        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13066                sessionParams.installReason);
13067        final InstallParams params = new InstallParams(origin, null, observer,
13068                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13069                verificationInfo, user, sessionParams.abiOverride,
13070                sessionParams.grantedRuntimePermissions, certificates, installReason);
13071        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13072        msg.obj = params;
13073
13074        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13075                System.identityHashCode(msg.obj));
13076        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13077                System.identityHashCode(msg.obj));
13078
13079        mHandler.sendMessage(msg);
13080    }
13081
13082    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13083            int userId) {
13084        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13085        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13086    }
13087
13088    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13089            int appId, int... userIds) {
13090        if (ArrayUtils.isEmpty(userIds)) {
13091            return;
13092        }
13093        Bundle extras = new Bundle(1);
13094        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13095        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13096
13097        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13098                packageName, extras, 0, null, null, userIds);
13099        if (isSystem) {
13100            mHandler.post(() -> {
13101                        for (int userId : userIds) {
13102                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13103                        }
13104                    }
13105            );
13106        }
13107    }
13108
13109    /**
13110     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13111     * automatically without needing an explicit launch.
13112     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13113     */
13114    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13115        // If user is not running, the app didn't miss any broadcast
13116        if (!mUserManagerInternal.isUserRunning(userId)) {
13117            return;
13118        }
13119        final IActivityManager am = ActivityManager.getService();
13120        try {
13121            // Deliver LOCKED_BOOT_COMPLETED first
13122            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13123                    .setPackage(packageName);
13124            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13125            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13126                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13127
13128            // Deliver BOOT_COMPLETED only if user is unlocked
13129            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13130                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13131                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13132                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13133            }
13134        } catch (RemoteException e) {
13135            throw e.rethrowFromSystemServer();
13136        }
13137    }
13138
13139    @Override
13140    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13141            int userId) {
13142        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13143        PackageSetting pkgSetting;
13144        final int uid = Binder.getCallingUid();
13145        enforceCrossUserPermission(uid, userId,
13146                true /* requireFullPermission */, true /* checkShell */,
13147                "setApplicationHiddenSetting for user " + userId);
13148
13149        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13150            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13151            return false;
13152        }
13153
13154        long callingId = Binder.clearCallingIdentity();
13155        try {
13156            boolean sendAdded = false;
13157            boolean sendRemoved = false;
13158            // writer
13159            synchronized (mPackages) {
13160                pkgSetting = mSettings.mPackages.get(packageName);
13161                if (pkgSetting == null) {
13162                    return false;
13163                }
13164                // Do not allow "android" is being disabled
13165                if ("android".equals(packageName)) {
13166                    Slog.w(TAG, "Cannot hide package: android");
13167                    return false;
13168                }
13169                // Cannot hide static shared libs as they are considered
13170                // a part of the using app (emulating static linking). Also
13171                // static libs are installed always on internal storage.
13172                PackageParser.Package pkg = mPackages.get(packageName);
13173                if (pkg != null && pkg.staticSharedLibName != null) {
13174                    Slog.w(TAG, "Cannot hide package: " + packageName
13175                            + " providing static shared library: "
13176                            + pkg.staticSharedLibName);
13177                    return false;
13178                }
13179                // Only allow protected packages to hide themselves.
13180                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13181                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13182                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13183                    return false;
13184                }
13185
13186                if (pkgSetting.getHidden(userId) != hidden) {
13187                    pkgSetting.setHidden(hidden, userId);
13188                    mSettings.writePackageRestrictionsLPr(userId);
13189                    if (hidden) {
13190                        sendRemoved = true;
13191                    } else {
13192                        sendAdded = true;
13193                    }
13194                }
13195            }
13196            if (sendAdded) {
13197                sendPackageAddedForUser(packageName, pkgSetting, userId);
13198                return true;
13199            }
13200            if (sendRemoved) {
13201                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13202                        "hiding pkg");
13203                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13204                return true;
13205            }
13206        } finally {
13207            Binder.restoreCallingIdentity(callingId);
13208        }
13209        return false;
13210    }
13211
13212    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13213            int userId) {
13214        final PackageRemovedInfo info = new PackageRemovedInfo();
13215        info.removedPackage = packageName;
13216        info.removedUsers = new int[] {userId};
13217        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13218        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13219    }
13220
13221    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13222        if (pkgList.length > 0) {
13223            Bundle extras = new Bundle(1);
13224            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13225
13226            sendPackageBroadcast(
13227                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13228                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13229                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13230                    new int[] {userId});
13231        }
13232    }
13233
13234    /**
13235     * Returns true if application is not found or there was an error. Otherwise it returns
13236     * the hidden state of the package for the given user.
13237     */
13238    @Override
13239    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13240        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13241        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13242                true /* requireFullPermission */, false /* checkShell */,
13243                "getApplicationHidden for user " + userId);
13244        PackageSetting pkgSetting;
13245        long callingId = Binder.clearCallingIdentity();
13246        try {
13247            // writer
13248            synchronized (mPackages) {
13249                pkgSetting = mSettings.mPackages.get(packageName);
13250                if (pkgSetting == null) {
13251                    return true;
13252                }
13253                return pkgSetting.getHidden(userId);
13254            }
13255        } finally {
13256            Binder.restoreCallingIdentity(callingId);
13257        }
13258    }
13259
13260    /**
13261     * @hide
13262     */
13263    @Override
13264    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13265            int installReason) {
13266        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13267                null);
13268        PackageSetting pkgSetting;
13269        final int uid = Binder.getCallingUid();
13270        enforceCrossUserPermission(uid, userId,
13271                true /* requireFullPermission */, true /* checkShell */,
13272                "installExistingPackage for user " + userId);
13273        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13274            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13275        }
13276
13277        long callingId = Binder.clearCallingIdentity();
13278        try {
13279            boolean installed = false;
13280            final boolean instantApp =
13281                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13282            final boolean fullApp =
13283                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13284
13285            // writer
13286            synchronized (mPackages) {
13287                pkgSetting = mSettings.mPackages.get(packageName);
13288                if (pkgSetting == null) {
13289                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13290                }
13291                if (!pkgSetting.getInstalled(userId)) {
13292                    pkgSetting.setInstalled(true, userId);
13293                    pkgSetting.setHidden(false, userId);
13294                    pkgSetting.setInstallReason(installReason, userId);
13295                    mSettings.writePackageRestrictionsLPr(userId);
13296                    mSettings.writeKernelMappingLPr(pkgSetting);
13297                    installed = true;
13298                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13299                    // upgrade app from instant to full; we don't allow app downgrade
13300                    installed = true;
13301                }
13302                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13303            }
13304
13305            if (installed) {
13306                if (pkgSetting.pkg != null) {
13307                    synchronized (mInstallLock) {
13308                        // We don't need to freeze for a brand new install
13309                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13310                    }
13311                }
13312                sendPackageAddedForUser(packageName, pkgSetting, userId);
13313                synchronized (mPackages) {
13314                    updateSequenceNumberLP(packageName, new int[]{ userId });
13315                }
13316            }
13317        } finally {
13318            Binder.restoreCallingIdentity(callingId);
13319        }
13320
13321        return PackageManager.INSTALL_SUCCEEDED;
13322    }
13323
13324    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13325            boolean instantApp, boolean fullApp) {
13326        // no state specified; do nothing
13327        if (!instantApp && !fullApp) {
13328            return;
13329        }
13330        if (userId != UserHandle.USER_ALL) {
13331            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13332                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13333            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13334                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13335            }
13336        } else {
13337            for (int currentUserId : sUserManager.getUserIds()) {
13338                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13339                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13340                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13341                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13342                }
13343            }
13344        }
13345    }
13346
13347    boolean isUserRestricted(int userId, String restrictionKey) {
13348        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13349        if (restrictions.getBoolean(restrictionKey, false)) {
13350            Log.w(TAG, "User is restricted: " + restrictionKey);
13351            return true;
13352        }
13353        return false;
13354    }
13355
13356    @Override
13357    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13358            int userId) {
13359        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13360        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13361                true /* requireFullPermission */, true /* checkShell */,
13362                "setPackagesSuspended for user " + userId);
13363
13364        if (ArrayUtils.isEmpty(packageNames)) {
13365            return packageNames;
13366        }
13367
13368        // List of package names for whom the suspended state has changed.
13369        List<String> changedPackages = new ArrayList<>(packageNames.length);
13370        // List of package names for whom the suspended state is not set as requested in this
13371        // method.
13372        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13373        long callingId = Binder.clearCallingIdentity();
13374        try {
13375            for (int i = 0; i < packageNames.length; i++) {
13376                String packageName = packageNames[i];
13377                boolean changed = false;
13378                final int appId;
13379                synchronized (mPackages) {
13380                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13381                    if (pkgSetting == null) {
13382                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13383                                + "\". Skipping suspending/un-suspending.");
13384                        unactionedPackages.add(packageName);
13385                        continue;
13386                    }
13387                    appId = pkgSetting.appId;
13388                    if (pkgSetting.getSuspended(userId) != suspended) {
13389                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13390                            unactionedPackages.add(packageName);
13391                            continue;
13392                        }
13393                        pkgSetting.setSuspended(suspended, userId);
13394                        mSettings.writePackageRestrictionsLPr(userId);
13395                        changed = true;
13396                        changedPackages.add(packageName);
13397                    }
13398                }
13399
13400                if (changed && suspended) {
13401                    killApplication(packageName, UserHandle.getUid(userId, appId),
13402                            "suspending package");
13403                }
13404            }
13405        } finally {
13406            Binder.restoreCallingIdentity(callingId);
13407        }
13408
13409        if (!changedPackages.isEmpty()) {
13410            sendPackagesSuspendedForUser(changedPackages.toArray(
13411                    new String[changedPackages.size()]), userId, suspended);
13412        }
13413
13414        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13415    }
13416
13417    @Override
13418    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13419        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13420                true /* requireFullPermission */, false /* checkShell */,
13421                "isPackageSuspendedForUser for user " + userId);
13422        synchronized (mPackages) {
13423            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13424            if (pkgSetting == null) {
13425                throw new IllegalArgumentException("Unknown target package: " + packageName);
13426            }
13427            return pkgSetting.getSuspended(userId);
13428        }
13429    }
13430
13431    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13432        if (isPackageDeviceAdmin(packageName, userId)) {
13433            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13434                    + "\": has an active device admin");
13435            return false;
13436        }
13437
13438        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13439        if (packageName.equals(activeLauncherPackageName)) {
13440            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13441                    + "\": contains the active launcher");
13442            return false;
13443        }
13444
13445        if (packageName.equals(mRequiredInstallerPackage)) {
13446            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13447                    + "\": required for package installation");
13448            return false;
13449        }
13450
13451        if (packageName.equals(mRequiredUninstallerPackage)) {
13452            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13453                    + "\": required for package uninstallation");
13454            return false;
13455        }
13456
13457        if (packageName.equals(mRequiredVerifierPackage)) {
13458            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13459                    + "\": required for package verification");
13460            return false;
13461        }
13462
13463        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13464            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13465                    + "\": is the default dialer");
13466            return false;
13467        }
13468
13469        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13470            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13471                    + "\": protected package");
13472            return false;
13473        }
13474
13475        // Cannot suspend static shared libs as they are considered
13476        // a part of the using app (emulating static linking). Also
13477        // static libs are installed always on internal storage.
13478        PackageParser.Package pkg = mPackages.get(packageName);
13479        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13480            Slog.w(TAG, "Cannot suspend package: " + packageName
13481                    + " providing static shared library: "
13482                    + pkg.staticSharedLibName);
13483            return false;
13484        }
13485
13486        return true;
13487    }
13488
13489    private String getActiveLauncherPackageName(int userId) {
13490        Intent intent = new Intent(Intent.ACTION_MAIN);
13491        intent.addCategory(Intent.CATEGORY_HOME);
13492        ResolveInfo resolveInfo = resolveIntent(
13493                intent,
13494                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13495                PackageManager.MATCH_DEFAULT_ONLY,
13496                userId);
13497
13498        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13499    }
13500
13501    private String getDefaultDialerPackageName(int userId) {
13502        synchronized (mPackages) {
13503            return mSettings.getDefaultDialerPackageNameLPw(userId);
13504        }
13505    }
13506
13507    @Override
13508    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13509        mContext.enforceCallingOrSelfPermission(
13510                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13511                "Only package verification agents can verify applications");
13512
13513        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13514        final PackageVerificationResponse response = new PackageVerificationResponse(
13515                verificationCode, Binder.getCallingUid());
13516        msg.arg1 = id;
13517        msg.obj = response;
13518        mHandler.sendMessage(msg);
13519    }
13520
13521    @Override
13522    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13523            long millisecondsToDelay) {
13524        mContext.enforceCallingOrSelfPermission(
13525                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13526                "Only package verification agents can extend verification timeouts");
13527
13528        final PackageVerificationState state = mPendingVerification.get(id);
13529        final PackageVerificationResponse response = new PackageVerificationResponse(
13530                verificationCodeAtTimeout, Binder.getCallingUid());
13531
13532        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13533            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13534        }
13535        if (millisecondsToDelay < 0) {
13536            millisecondsToDelay = 0;
13537        }
13538        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13539                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13540            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13541        }
13542
13543        if ((state != null) && !state.timeoutExtended()) {
13544            state.extendTimeout();
13545
13546            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13547            msg.arg1 = id;
13548            msg.obj = response;
13549            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13550        }
13551    }
13552
13553    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13554            int verificationCode, UserHandle user) {
13555        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13556        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13557        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13558        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13559        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13560
13561        mContext.sendBroadcastAsUser(intent, user,
13562                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13563    }
13564
13565    private ComponentName matchComponentForVerifier(String packageName,
13566            List<ResolveInfo> receivers) {
13567        ActivityInfo targetReceiver = null;
13568
13569        final int NR = receivers.size();
13570        for (int i = 0; i < NR; i++) {
13571            final ResolveInfo info = receivers.get(i);
13572            if (info.activityInfo == null) {
13573                continue;
13574            }
13575
13576            if (packageName.equals(info.activityInfo.packageName)) {
13577                targetReceiver = info.activityInfo;
13578                break;
13579            }
13580        }
13581
13582        if (targetReceiver == null) {
13583            return null;
13584        }
13585
13586        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13587    }
13588
13589    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13590            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13591        if (pkgInfo.verifiers.length == 0) {
13592            return null;
13593        }
13594
13595        final int N = pkgInfo.verifiers.length;
13596        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13597        for (int i = 0; i < N; i++) {
13598            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13599
13600            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13601                    receivers);
13602            if (comp == null) {
13603                continue;
13604            }
13605
13606            final int verifierUid = getUidForVerifier(verifierInfo);
13607            if (verifierUid == -1) {
13608                continue;
13609            }
13610
13611            if (DEBUG_VERIFY) {
13612                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13613                        + " with the correct signature");
13614            }
13615            sufficientVerifiers.add(comp);
13616            verificationState.addSufficientVerifier(verifierUid);
13617        }
13618
13619        return sufficientVerifiers;
13620    }
13621
13622    private int getUidForVerifier(VerifierInfo verifierInfo) {
13623        synchronized (mPackages) {
13624            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13625            if (pkg == null) {
13626                return -1;
13627            } else if (pkg.mSignatures.length != 1) {
13628                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13629                        + " has more than one signature; ignoring");
13630                return -1;
13631            }
13632
13633            /*
13634             * If the public key of the package's signature does not match
13635             * our expected public key, then this is a different package and
13636             * we should skip.
13637             */
13638
13639            final byte[] expectedPublicKey;
13640            try {
13641                final Signature verifierSig = pkg.mSignatures[0];
13642                final PublicKey publicKey = verifierSig.getPublicKey();
13643                expectedPublicKey = publicKey.getEncoded();
13644            } catch (CertificateException e) {
13645                return -1;
13646            }
13647
13648            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13649
13650            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13651                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13652                        + " does not have the expected public key; ignoring");
13653                return -1;
13654            }
13655
13656            return pkg.applicationInfo.uid;
13657        }
13658    }
13659
13660    @Override
13661    public void finishPackageInstall(int token, boolean didLaunch) {
13662        enforceSystemOrRoot("Only the system is allowed to finish installs");
13663
13664        if (DEBUG_INSTALL) {
13665            Slog.v(TAG, "BM finishing package install for " + token);
13666        }
13667        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13668
13669        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13670        mHandler.sendMessage(msg);
13671    }
13672
13673    /**
13674     * Get the verification agent timeout.
13675     *
13676     * @return verification timeout in milliseconds
13677     */
13678    private long getVerificationTimeout() {
13679        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13680                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13681                DEFAULT_VERIFICATION_TIMEOUT);
13682    }
13683
13684    /**
13685     * Get the default verification agent response code.
13686     *
13687     * @return default verification response code
13688     */
13689    private int getDefaultVerificationResponse() {
13690        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13691                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13692                DEFAULT_VERIFICATION_RESPONSE);
13693    }
13694
13695    /**
13696     * Check whether or not package verification has been enabled.
13697     *
13698     * @return true if verification should be performed
13699     */
13700    private boolean isVerificationEnabled(int userId, int installFlags) {
13701        if (!DEFAULT_VERIFY_ENABLE) {
13702            return false;
13703        }
13704
13705        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13706
13707        // Check if installing from ADB
13708        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13709            // Do not run verification in a test harness environment
13710            if (ActivityManager.isRunningInTestHarness()) {
13711                return false;
13712            }
13713            if (ensureVerifyAppsEnabled) {
13714                return true;
13715            }
13716            // Check if the developer does not want package verification for ADB installs
13717            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13718                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13719                return false;
13720            }
13721        }
13722
13723        if (ensureVerifyAppsEnabled) {
13724            return true;
13725        }
13726
13727        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13728                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13729    }
13730
13731    @Override
13732    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13733            throws RemoteException {
13734        mContext.enforceCallingOrSelfPermission(
13735                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13736                "Only intentfilter verification agents can verify applications");
13737
13738        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13739        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13740                Binder.getCallingUid(), verificationCode, failedDomains);
13741        msg.arg1 = id;
13742        msg.obj = response;
13743        mHandler.sendMessage(msg);
13744    }
13745
13746    @Override
13747    public int getIntentVerificationStatus(String packageName, int userId) {
13748        synchronized (mPackages) {
13749            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13750        }
13751    }
13752
13753    @Override
13754    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13755        mContext.enforceCallingOrSelfPermission(
13756                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13757
13758        boolean result = false;
13759        synchronized (mPackages) {
13760            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13761        }
13762        if (result) {
13763            scheduleWritePackageRestrictionsLocked(userId);
13764        }
13765        return result;
13766    }
13767
13768    @Override
13769    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13770            String packageName) {
13771        synchronized (mPackages) {
13772            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13773        }
13774    }
13775
13776    @Override
13777    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13778        if (TextUtils.isEmpty(packageName)) {
13779            return ParceledListSlice.emptyList();
13780        }
13781        synchronized (mPackages) {
13782            PackageParser.Package pkg = mPackages.get(packageName);
13783            if (pkg == null || pkg.activities == null) {
13784                return ParceledListSlice.emptyList();
13785            }
13786            final int count = pkg.activities.size();
13787            ArrayList<IntentFilter> result = new ArrayList<>();
13788            for (int n=0; n<count; n++) {
13789                PackageParser.Activity activity = pkg.activities.get(n);
13790                if (activity.intents != null && activity.intents.size() > 0) {
13791                    result.addAll(activity.intents);
13792                }
13793            }
13794            return new ParceledListSlice<>(result);
13795        }
13796    }
13797
13798    @Override
13799    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13800        mContext.enforceCallingOrSelfPermission(
13801                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13802
13803        synchronized (mPackages) {
13804            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13805            if (packageName != null) {
13806                result |= updateIntentVerificationStatus(packageName,
13807                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13808                        userId);
13809                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13810                        packageName, userId);
13811            }
13812            return result;
13813        }
13814    }
13815
13816    @Override
13817    public String getDefaultBrowserPackageName(int userId) {
13818        synchronized (mPackages) {
13819            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13820        }
13821    }
13822
13823    /**
13824     * Get the "allow unknown sources" setting.
13825     *
13826     * @return the current "allow unknown sources" setting
13827     */
13828    private int getUnknownSourcesSettings() {
13829        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13830                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13831                -1);
13832    }
13833
13834    @Override
13835    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13836        final int uid = Binder.getCallingUid();
13837        // writer
13838        synchronized (mPackages) {
13839            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13840            if (targetPackageSetting == null) {
13841                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13842            }
13843
13844            PackageSetting installerPackageSetting;
13845            if (installerPackageName != null) {
13846                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13847                if (installerPackageSetting == null) {
13848                    throw new IllegalArgumentException("Unknown installer package: "
13849                            + installerPackageName);
13850                }
13851            } else {
13852                installerPackageSetting = null;
13853            }
13854
13855            Signature[] callerSignature;
13856            Object obj = mSettings.getUserIdLPr(uid);
13857            if (obj != null) {
13858                if (obj instanceof SharedUserSetting) {
13859                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13860                } else if (obj instanceof PackageSetting) {
13861                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13862                } else {
13863                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13864                }
13865            } else {
13866                throw new SecurityException("Unknown calling UID: " + uid);
13867            }
13868
13869            // Verify: can't set installerPackageName to a package that is
13870            // not signed with the same cert as the caller.
13871            if (installerPackageSetting != null) {
13872                if (compareSignatures(callerSignature,
13873                        installerPackageSetting.signatures.mSignatures)
13874                        != PackageManager.SIGNATURE_MATCH) {
13875                    throw new SecurityException(
13876                            "Caller does not have same cert as new installer package "
13877                            + installerPackageName);
13878                }
13879            }
13880
13881            // Verify: if target already has an installer package, it must
13882            // be signed with the same cert as the caller.
13883            if (targetPackageSetting.installerPackageName != null) {
13884                PackageSetting setting = mSettings.mPackages.get(
13885                        targetPackageSetting.installerPackageName);
13886                // If the currently set package isn't valid, then it's always
13887                // okay to change it.
13888                if (setting != null) {
13889                    if (compareSignatures(callerSignature,
13890                            setting.signatures.mSignatures)
13891                            != PackageManager.SIGNATURE_MATCH) {
13892                        throw new SecurityException(
13893                                "Caller does not have same cert as old installer package "
13894                                + targetPackageSetting.installerPackageName);
13895                    }
13896                }
13897            }
13898
13899            // Okay!
13900            targetPackageSetting.installerPackageName = installerPackageName;
13901            if (installerPackageName != null) {
13902                mSettings.mInstallerPackages.add(installerPackageName);
13903            }
13904            scheduleWriteSettingsLocked();
13905        }
13906    }
13907
13908    @Override
13909    public void setApplicationCategoryHint(String packageName, int categoryHint,
13910            String callerPackageName) {
13911        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13912                callerPackageName);
13913        synchronized (mPackages) {
13914            PackageSetting ps = mSettings.mPackages.get(packageName);
13915            if (ps == null) {
13916                throw new IllegalArgumentException("Unknown target package " + packageName);
13917            }
13918
13919            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13920                throw new IllegalArgumentException("Calling package " + callerPackageName
13921                        + " is not installer for " + packageName);
13922            }
13923
13924            if (ps.categoryHint != categoryHint) {
13925                ps.categoryHint = categoryHint;
13926                scheduleWriteSettingsLocked();
13927            }
13928        }
13929    }
13930
13931    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13932        // Queue up an async operation since the package installation may take a little while.
13933        mHandler.post(new Runnable() {
13934            public void run() {
13935                mHandler.removeCallbacks(this);
13936                 // Result object to be returned
13937                PackageInstalledInfo res = new PackageInstalledInfo();
13938                res.setReturnCode(currentStatus);
13939                res.uid = -1;
13940                res.pkg = null;
13941                res.removedInfo = null;
13942                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13943                    args.doPreInstall(res.returnCode);
13944                    synchronized (mInstallLock) {
13945                        installPackageTracedLI(args, res);
13946                    }
13947                    args.doPostInstall(res.returnCode, res.uid);
13948                }
13949
13950                // A restore should be performed at this point if (a) the install
13951                // succeeded, (b) the operation is not an update, and (c) the new
13952                // package has not opted out of backup participation.
13953                final boolean update = res.removedInfo != null
13954                        && res.removedInfo.removedPackage != null;
13955                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13956                boolean doRestore = !update
13957                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13958
13959                // Set up the post-install work request bookkeeping.  This will be used
13960                // and cleaned up by the post-install event handling regardless of whether
13961                // there's a restore pass performed.  Token values are >= 1.
13962                int token;
13963                if (mNextInstallToken < 0) mNextInstallToken = 1;
13964                token = mNextInstallToken++;
13965
13966                PostInstallData data = new PostInstallData(args, res);
13967                mRunningInstalls.put(token, data);
13968                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13969
13970                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13971                    // Pass responsibility to the Backup Manager.  It will perform a
13972                    // restore if appropriate, then pass responsibility back to the
13973                    // Package Manager to run the post-install observer callbacks
13974                    // and broadcasts.
13975                    IBackupManager bm = IBackupManager.Stub.asInterface(
13976                            ServiceManager.getService(Context.BACKUP_SERVICE));
13977                    if (bm != null) {
13978                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13979                                + " to BM for possible restore");
13980                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13981                        try {
13982                            // TODO: http://b/22388012
13983                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13984                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13985                            } else {
13986                                doRestore = false;
13987                            }
13988                        } catch (RemoteException e) {
13989                            // can't happen; the backup manager is local
13990                        } catch (Exception e) {
13991                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13992                            doRestore = false;
13993                        }
13994                    } else {
13995                        Slog.e(TAG, "Backup Manager not found!");
13996                        doRestore = false;
13997                    }
13998                }
13999
14000                if (!doRestore) {
14001                    // No restore possible, or the Backup Manager was mysteriously not
14002                    // available -- just fire the post-install work request directly.
14003                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14004
14005                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14006
14007                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14008                    mHandler.sendMessage(msg);
14009                }
14010            }
14011        });
14012    }
14013
14014    /**
14015     * Callback from PackageSettings whenever an app is first transitioned out of the
14016     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14017     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14018     * here whether the app is the target of an ongoing install, and only send the
14019     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14020     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14021     * handling.
14022     */
14023    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14024        // Serialize this with the rest of the install-process message chain.  In the
14025        // restore-at-install case, this Runnable will necessarily run before the
14026        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14027        // are coherent.  In the non-restore case, the app has already completed install
14028        // and been launched through some other means, so it is not in a problematic
14029        // state for observers to see the FIRST_LAUNCH signal.
14030        mHandler.post(new Runnable() {
14031            @Override
14032            public void run() {
14033                for (int i = 0; i < mRunningInstalls.size(); i++) {
14034                    final PostInstallData data = mRunningInstalls.valueAt(i);
14035                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14036                        continue;
14037                    }
14038                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14039                        // right package; but is it for the right user?
14040                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14041                            if (userId == data.res.newUsers[uIndex]) {
14042                                if (DEBUG_BACKUP) {
14043                                    Slog.i(TAG, "Package " + pkgName
14044                                            + " being restored so deferring FIRST_LAUNCH");
14045                                }
14046                                return;
14047                            }
14048                        }
14049                    }
14050                }
14051                // didn't find it, so not being restored
14052                if (DEBUG_BACKUP) {
14053                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14054                }
14055                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14056            }
14057        });
14058    }
14059
14060    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14061        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14062                installerPkg, null, userIds);
14063    }
14064
14065    private abstract class HandlerParams {
14066        private static final int MAX_RETRIES = 4;
14067
14068        /**
14069         * Number of times startCopy() has been attempted and had a non-fatal
14070         * error.
14071         */
14072        private int mRetries = 0;
14073
14074        /** User handle for the user requesting the information or installation. */
14075        private final UserHandle mUser;
14076        String traceMethod;
14077        int traceCookie;
14078
14079        HandlerParams(UserHandle user) {
14080            mUser = user;
14081        }
14082
14083        UserHandle getUser() {
14084            return mUser;
14085        }
14086
14087        HandlerParams setTraceMethod(String traceMethod) {
14088            this.traceMethod = traceMethod;
14089            return this;
14090        }
14091
14092        HandlerParams setTraceCookie(int traceCookie) {
14093            this.traceCookie = traceCookie;
14094            return this;
14095        }
14096
14097        final boolean startCopy() {
14098            boolean res;
14099            try {
14100                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14101
14102                if (++mRetries > MAX_RETRIES) {
14103                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14104                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14105                    handleServiceError();
14106                    return false;
14107                } else {
14108                    handleStartCopy();
14109                    res = true;
14110                }
14111            } catch (RemoteException e) {
14112                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14113                mHandler.sendEmptyMessage(MCS_RECONNECT);
14114                res = false;
14115            }
14116            handleReturnCode();
14117            return res;
14118        }
14119
14120        final void serviceError() {
14121            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14122            handleServiceError();
14123            handleReturnCode();
14124        }
14125
14126        abstract void handleStartCopy() throws RemoteException;
14127        abstract void handleServiceError();
14128        abstract void handleReturnCode();
14129    }
14130
14131    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14132        for (File path : paths) {
14133            try {
14134                mcs.clearDirectory(path.getAbsolutePath());
14135            } catch (RemoteException e) {
14136            }
14137        }
14138    }
14139
14140    static class OriginInfo {
14141        /**
14142         * Location where install is coming from, before it has been
14143         * copied/renamed into place. This could be a single monolithic APK
14144         * file, or a cluster directory. This location may be untrusted.
14145         */
14146        final File file;
14147        final String cid;
14148
14149        /**
14150         * Flag indicating that {@link #file} or {@link #cid} has already been
14151         * staged, meaning downstream users don't need to defensively copy the
14152         * contents.
14153         */
14154        final boolean staged;
14155
14156        /**
14157         * Flag indicating that {@link #file} or {@link #cid} is an already
14158         * installed app that is being moved.
14159         */
14160        final boolean existing;
14161
14162        final String resolvedPath;
14163        final File resolvedFile;
14164
14165        static OriginInfo fromNothing() {
14166            return new OriginInfo(null, null, false, false);
14167        }
14168
14169        static OriginInfo fromUntrustedFile(File file) {
14170            return new OriginInfo(file, null, false, false);
14171        }
14172
14173        static OriginInfo fromExistingFile(File file) {
14174            return new OriginInfo(file, null, false, true);
14175        }
14176
14177        static OriginInfo fromStagedFile(File file) {
14178            return new OriginInfo(file, null, true, false);
14179        }
14180
14181        static OriginInfo fromStagedContainer(String cid) {
14182            return new OriginInfo(null, cid, true, false);
14183        }
14184
14185        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14186            this.file = file;
14187            this.cid = cid;
14188            this.staged = staged;
14189            this.existing = existing;
14190
14191            if (cid != null) {
14192                resolvedPath = PackageHelper.getSdDir(cid);
14193                resolvedFile = new File(resolvedPath);
14194            } else if (file != null) {
14195                resolvedPath = file.getAbsolutePath();
14196                resolvedFile = file;
14197            } else {
14198                resolvedPath = null;
14199                resolvedFile = null;
14200            }
14201        }
14202    }
14203
14204    static class MoveInfo {
14205        final int moveId;
14206        final String fromUuid;
14207        final String toUuid;
14208        final String packageName;
14209        final String dataAppName;
14210        final int appId;
14211        final String seinfo;
14212        final int targetSdkVersion;
14213
14214        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14215                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14216            this.moveId = moveId;
14217            this.fromUuid = fromUuid;
14218            this.toUuid = toUuid;
14219            this.packageName = packageName;
14220            this.dataAppName = dataAppName;
14221            this.appId = appId;
14222            this.seinfo = seinfo;
14223            this.targetSdkVersion = targetSdkVersion;
14224        }
14225    }
14226
14227    static class VerificationInfo {
14228        /** A constant used to indicate that a uid value is not present. */
14229        public static final int NO_UID = -1;
14230
14231        /** URI referencing where the package was downloaded from. */
14232        final Uri originatingUri;
14233
14234        /** HTTP referrer URI associated with the originatingURI. */
14235        final Uri referrer;
14236
14237        /** UID of the application that the install request originated from. */
14238        final int originatingUid;
14239
14240        /** UID of application requesting the install */
14241        final int installerUid;
14242
14243        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14244            this.originatingUri = originatingUri;
14245            this.referrer = referrer;
14246            this.originatingUid = originatingUid;
14247            this.installerUid = installerUid;
14248        }
14249    }
14250
14251    class InstallParams extends HandlerParams {
14252        final OriginInfo origin;
14253        final MoveInfo move;
14254        final IPackageInstallObserver2 observer;
14255        int installFlags;
14256        final String installerPackageName;
14257        final String volumeUuid;
14258        private InstallArgs mArgs;
14259        private int mRet;
14260        final String packageAbiOverride;
14261        final String[] grantedRuntimePermissions;
14262        final VerificationInfo verificationInfo;
14263        final Certificate[][] certificates;
14264        final int installReason;
14265
14266        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14267                int installFlags, String installerPackageName, String volumeUuid,
14268                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14269                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14270            super(user);
14271            this.origin = origin;
14272            this.move = move;
14273            this.observer = observer;
14274            this.installFlags = installFlags;
14275            this.installerPackageName = installerPackageName;
14276            this.volumeUuid = volumeUuid;
14277            this.verificationInfo = verificationInfo;
14278            this.packageAbiOverride = packageAbiOverride;
14279            this.grantedRuntimePermissions = grantedPermissions;
14280            this.certificates = certificates;
14281            this.installReason = installReason;
14282        }
14283
14284        @Override
14285        public String toString() {
14286            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14287                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14288        }
14289
14290        private int installLocationPolicy(PackageInfoLite pkgLite) {
14291            String packageName = pkgLite.packageName;
14292            int installLocation = pkgLite.installLocation;
14293            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14294            // reader
14295            synchronized (mPackages) {
14296                // Currently installed package which the new package is attempting to replace or
14297                // null if no such package is installed.
14298                PackageParser.Package installedPkg = mPackages.get(packageName);
14299                // Package which currently owns the data which the new package will own if installed.
14300                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14301                // will be null whereas dataOwnerPkg will contain information about the package
14302                // which was uninstalled while keeping its data.
14303                PackageParser.Package dataOwnerPkg = installedPkg;
14304                if (dataOwnerPkg  == null) {
14305                    PackageSetting ps = mSettings.mPackages.get(packageName);
14306                    if (ps != null) {
14307                        dataOwnerPkg = ps.pkg;
14308                    }
14309                }
14310
14311                if (dataOwnerPkg != null) {
14312                    // If installed, the package will get access to data left on the device by its
14313                    // predecessor. As a security measure, this is permited only if this is not a
14314                    // version downgrade or if the predecessor package is marked as debuggable and
14315                    // a downgrade is explicitly requested.
14316                    //
14317                    // On debuggable platform builds, downgrades are permitted even for
14318                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14319                    // not offer security guarantees and thus it's OK to disable some security
14320                    // mechanisms to make debugging/testing easier on those builds. However, even on
14321                    // debuggable builds downgrades of packages are permitted only if requested via
14322                    // installFlags. This is because we aim to keep the behavior of debuggable
14323                    // platform builds as close as possible to the behavior of non-debuggable
14324                    // platform builds.
14325                    final boolean downgradeRequested =
14326                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14327                    final boolean packageDebuggable =
14328                                (dataOwnerPkg.applicationInfo.flags
14329                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14330                    final boolean downgradePermitted =
14331                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14332                    if (!downgradePermitted) {
14333                        try {
14334                            checkDowngrade(dataOwnerPkg, pkgLite);
14335                        } catch (PackageManagerException e) {
14336                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14337                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14338                        }
14339                    }
14340                }
14341
14342                if (installedPkg != null) {
14343                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14344                        // Check for updated system application.
14345                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14346                            if (onSd) {
14347                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14348                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14349                            }
14350                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14351                        } else {
14352                            if (onSd) {
14353                                // Install flag overrides everything.
14354                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14355                            }
14356                            // If current upgrade specifies particular preference
14357                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14358                                // Application explicitly specified internal.
14359                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14360                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14361                                // App explictly prefers external. Let policy decide
14362                            } else {
14363                                // Prefer previous location
14364                                if (isExternal(installedPkg)) {
14365                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14366                                }
14367                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14368                            }
14369                        }
14370                    } else {
14371                        // Invalid install. Return error code
14372                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14373                    }
14374                }
14375            }
14376            // All the special cases have been taken care of.
14377            // Return result based on recommended install location.
14378            if (onSd) {
14379                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14380            }
14381            return pkgLite.recommendedInstallLocation;
14382        }
14383
14384        /*
14385         * Invoke remote method to get package information and install
14386         * location values. Override install location based on default
14387         * policy if needed and then create install arguments based
14388         * on the install location.
14389         */
14390        public void handleStartCopy() throws RemoteException {
14391            int ret = PackageManager.INSTALL_SUCCEEDED;
14392
14393            // If we're already staged, we've firmly committed to an install location
14394            if (origin.staged) {
14395                if (origin.file != null) {
14396                    installFlags |= PackageManager.INSTALL_INTERNAL;
14397                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14398                } else if (origin.cid != null) {
14399                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14400                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14401                } else {
14402                    throw new IllegalStateException("Invalid stage location");
14403                }
14404            }
14405
14406            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14407            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14408            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14409            PackageInfoLite pkgLite = null;
14410
14411            if (onInt && onSd) {
14412                // Check if both bits are set.
14413                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14414                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14415            } else if (onSd && ephemeral) {
14416                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14417                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14418            } else {
14419                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14420                        packageAbiOverride);
14421
14422                if (DEBUG_EPHEMERAL && ephemeral) {
14423                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14424                }
14425
14426                /*
14427                 * If we have too little free space, try to free cache
14428                 * before giving up.
14429                 */
14430                if (!origin.staged && pkgLite.recommendedInstallLocation
14431                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14432                    // TODO: focus freeing disk space on the target device
14433                    final StorageManager storage = StorageManager.from(mContext);
14434                    final long lowThreshold = storage.getStorageLowBytes(
14435                            Environment.getDataDirectory());
14436
14437                    final long sizeBytes = mContainerService.calculateInstalledSize(
14438                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14439
14440                    try {
14441                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14442                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14443                                installFlags, packageAbiOverride);
14444                    } catch (InstallerException e) {
14445                        Slog.w(TAG, "Failed to free cache", e);
14446                    }
14447
14448                    /*
14449                     * The cache free must have deleted the file we
14450                     * downloaded to install.
14451                     *
14452                     * TODO: fix the "freeCache" call to not delete
14453                     *       the file we care about.
14454                     */
14455                    if (pkgLite.recommendedInstallLocation
14456                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14457                        pkgLite.recommendedInstallLocation
14458                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14459                    }
14460                }
14461            }
14462
14463            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14464                int loc = pkgLite.recommendedInstallLocation;
14465                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14466                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14467                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14468                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14469                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14470                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14471                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14472                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14473                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14474                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14475                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14476                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14477                } else {
14478                    // Override with defaults if needed.
14479                    loc = installLocationPolicy(pkgLite);
14480                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14481                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14482                    } else if (!onSd && !onInt) {
14483                        // Override install location with flags
14484                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14485                            // Set the flag to install on external media.
14486                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14487                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14488                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14489                            if (DEBUG_EPHEMERAL) {
14490                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14491                            }
14492                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14493                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14494                                    |PackageManager.INSTALL_INTERNAL);
14495                        } else {
14496                            // Make sure the flag for installing on external
14497                            // media is unset
14498                            installFlags |= PackageManager.INSTALL_INTERNAL;
14499                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14500                        }
14501                    }
14502                }
14503            }
14504
14505            final InstallArgs args = createInstallArgs(this);
14506            mArgs = args;
14507
14508            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14509                // TODO: http://b/22976637
14510                // Apps installed for "all" users use the device owner to verify the app
14511                UserHandle verifierUser = getUser();
14512                if (verifierUser == UserHandle.ALL) {
14513                    verifierUser = UserHandle.SYSTEM;
14514                }
14515
14516                /*
14517                 * Determine if we have any installed package verifiers. If we
14518                 * do, then we'll defer to them to verify the packages.
14519                 */
14520                final int requiredUid = mRequiredVerifierPackage == null ? -1
14521                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14522                                verifierUser.getIdentifier());
14523                if (!origin.existing && requiredUid != -1
14524                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14525                    final Intent verification = new Intent(
14526                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14527                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14528                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14529                            PACKAGE_MIME_TYPE);
14530                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14531
14532                    // Query all live verifiers based on current user state
14533                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14534                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14535
14536                    if (DEBUG_VERIFY) {
14537                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14538                                + verification.toString() + " with " + pkgLite.verifiers.length
14539                                + " optional verifiers");
14540                    }
14541
14542                    final int verificationId = mPendingVerificationToken++;
14543
14544                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14545
14546                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14547                            installerPackageName);
14548
14549                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14550                            installFlags);
14551
14552                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14553                            pkgLite.packageName);
14554
14555                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14556                            pkgLite.versionCode);
14557
14558                    if (verificationInfo != null) {
14559                        if (verificationInfo.originatingUri != null) {
14560                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14561                                    verificationInfo.originatingUri);
14562                        }
14563                        if (verificationInfo.referrer != null) {
14564                            verification.putExtra(Intent.EXTRA_REFERRER,
14565                                    verificationInfo.referrer);
14566                        }
14567                        if (verificationInfo.originatingUid >= 0) {
14568                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14569                                    verificationInfo.originatingUid);
14570                        }
14571                        if (verificationInfo.installerUid >= 0) {
14572                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14573                                    verificationInfo.installerUid);
14574                        }
14575                    }
14576
14577                    final PackageVerificationState verificationState = new PackageVerificationState(
14578                            requiredUid, args);
14579
14580                    mPendingVerification.append(verificationId, verificationState);
14581
14582                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14583                            receivers, verificationState);
14584
14585                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14586                    final long idleDuration = getVerificationTimeout();
14587
14588                    /*
14589                     * If any sufficient verifiers were listed in the package
14590                     * manifest, attempt to ask them.
14591                     */
14592                    if (sufficientVerifiers != null) {
14593                        final int N = sufficientVerifiers.size();
14594                        if (N == 0) {
14595                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14596                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14597                        } else {
14598                            for (int i = 0; i < N; i++) {
14599                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14600                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14601                                        verifierComponent.getPackageName(), idleDuration,
14602                                        verifierUser.getIdentifier(), false, "package verifier");
14603
14604                                final Intent sufficientIntent = new Intent(verification);
14605                                sufficientIntent.setComponent(verifierComponent);
14606                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14607                            }
14608                        }
14609                    }
14610
14611                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14612                            mRequiredVerifierPackage, receivers);
14613                    if (ret == PackageManager.INSTALL_SUCCEEDED
14614                            && mRequiredVerifierPackage != null) {
14615                        Trace.asyncTraceBegin(
14616                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14617                        /*
14618                         * Send the intent to the required verification agent,
14619                         * but only start the verification timeout after the
14620                         * target BroadcastReceivers have run.
14621                         */
14622                        verification.setComponent(requiredVerifierComponent);
14623                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14624                                mRequiredVerifierPackage, idleDuration,
14625                                verifierUser.getIdentifier(), false, "package verifier");
14626                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14627                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14628                                new BroadcastReceiver() {
14629                                    @Override
14630                                    public void onReceive(Context context, Intent intent) {
14631                                        final Message msg = mHandler
14632                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14633                                        msg.arg1 = verificationId;
14634                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14635                                    }
14636                                }, null, 0, null, null);
14637
14638                        /*
14639                         * We don't want the copy to proceed until verification
14640                         * succeeds, so null out this field.
14641                         */
14642                        mArgs = null;
14643                    }
14644                } else {
14645                    /*
14646                     * No package verification is enabled, so immediately start
14647                     * the remote call to initiate copy using temporary file.
14648                     */
14649                    ret = args.copyApk(mContainerService, true);
14650                }
14651            }
14652
14653            mRet = ret;
14654        }
14655
14656        @Override
14657        void handleReturnCode() {
14658            // If mArgs is null, then MCS couldn't be reached. When it
14659            // reconnects, it will try again to install. At that point, this
14660            // will succeed.
14661            if (mArgs != null) {
14662                processPendingInstall(mArgs, mRet);
14663            }
14664        }
14665
14666        @Override
14667        void handleServiceError() {
14668            mArgs = createInstallArgs(this);
14669            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14670        }
14671
14672        public boolean isForwardLocked() {
14673            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14674        }
14675    }
14676
14677    /**
14678     * Used during creation of InstallArgs
14679     *
14680     * @param installFlags package installation flags
14681     * @return true if should be installed on external storage
14682     */
14683    private static boolean installOnExternalAsec(int installFlags) {
14684        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14685            return false;
14686        }
14687        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14688            return true;
14689        }
14690        return false;
14691    }
14692
14693    /**
14694     * Used during creation of InstallArgs
14695     *
14696     * @param installFlags package installation flags
14697     * @return true if should be installed as forward locked
14698     */
14699    private static boolean installForwardLocked(int installFlags) {
14700        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14701    }
14702
14703    private InstallArgs createInstallArgs(InstallParams params) {
14704        if (params.move != null) {
14705            return new MoveInstallArgs(params);
14706        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14707            return new AsecInstallArgs(params);
14708        } else {
14709            return new FileInstallArgs(params);
14710        }
14711    }
14712
14713    /**
14714     * Create args that describe an existing installed package. Typically used
14715     * when cleaning up old installs, or used as a move source.
14716     */
14717    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14718            String resourcePath, String[] instructionSets) {
14719        final boolean isInAsec;
14720        if (installOnExternalAsec(installFlags)) {
14721            /* Apps on SD card are always in ASEC containers. */
14722            isInAsec = true;
14723        } else if (installForwardLocked(installFlags)
14724                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14725            /*
14726             * Forward-locked apps are only in ASEC containers if they're the
14727             * new style
14728             */
14729            isInAsec = true;
14730        } else {
14731            isInAsec = false;
14732        }
14733
14734        if (isInAsec) {
14735            return new AsecInstallArgs(codePath, instructionSets,
14736                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14737        } else {
14738            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14739        }
14740    }
14741
14742    static abstract class InstallArgs {
14743        /** @see InstallParams#origin */
14744        final OriginInfo origin;
14745        /** @see InstallParams#move */
14746        final MoveInfo move;
14747
14748        final IPackageInstallObserver2 observer;
14749        // Always refers to PackageManager flags only
14750        final int installFlags;
14751        final String installerPackageName;
14752        final String volumeUuid;
14753        final UserHandle user;
14754        final String abiOverride;
14755        final String[] installGrantPermissions;
14756        /** If non-null, drop an async trace when the install completes */
14757        final String traceMethod;
14758        final int traceCookie;
14759        final Certificate[][] certificates;
14760        final int installReason;
14761
14762        // The list of instruction sets supported by this app. This is currently
14763        // only used during the rmdex() phase to clean up resources. We can get rid of this
14764        // if we move dex files under the common app path.
14765        /* nullable */ String[] instructionSets;
14766
14767        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14768                int installFlags, String installerPackageName, String volumeUuid,
14769                UserHandle user, String[] instructionSets,
14770                String abiOverride, String[] installGrantPermissions,
14771                String traceMethod, int traceCookie, Certificate[][] certificates,
14772                int installReason) {
14773            this.origin = origin;
14774            this.move = move;
14775            this.installFlags = installFlags;
14776            this.observer = observer;
14777            this.installerPackageName = installerPackageName;
14778            this.volumeUuid = volumeUuid;
14779            this.user = user;
14780            this.instructionSets = instructionSets;
14781            this.abiOverride = abiOverride;
14782            this.installGrantPermissions = installGrantPermissions;
14783            this.traceMethod = traceMethod;
14784            this.traceCookie = traceCookie;
14785            this.certificates = certificates;
14786            this.installReason = installReason;
14787        }
14788
14789        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14790        abstract int doPreInstall(int status);
14791
14792        /**
14793         * Rename package into final resting place. All paths on the given
14794         * scanned package should be updated to reflect the rename.
14795         */
14796        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14797        abstract int doPostInstall(int status, int uid);
14798
14799        /** @see PackageSettingBase#codePathString */
14800        abstract String getCodePath();
14801        /** @see PackageSettingBase#resourcePathString */
14802        abstract String getResourcePath();
14803
14804        // Need installer lock especially for dex file removal.
14805        abstract void cleanUpResourcesLI();
14806        abstract boolean doPostDeleteLI(boolean delete);
14807
14808        /**
14809         * Called before the source arguments are copied. This is used mostly
14810         * for MoveParams when it needs to read the source file to put it in the
14811         * destination.
14812         */
14813        int doPreCopy() {
14814            return PackageManager.INSTALL_SUCCEEDED;
14815        }
14816
14817        /**
14818         * Called after the source arguments are copied. This is used mostly for
14819         * MoveParams when it needs to read the source file to put it in the
14820         * destination.
14821         */
14822        int doPostCopy(int uid) {
14823            return PackageManager.INSTALL_SUCCEEDED;
14824        }
14825
14826        protected boolean isFwdLocked() {
14827            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14828        }
14829
14830        protected boolean isExternalAsec() {
14831            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14832        }
14833
14834        protected boolean isEphemeral() {
14835            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14836        }
14837
14838        UserHandle getUser() {
14839            return user;
14840        }
14841    }
14842
14843    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14844        if (!allCodePaths.isEmpty()) {
14845            if (instructionSets == null) {
14846                throw new IllegalStateException("instructionSet == null");
14847            }
14848            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14849            for (String codePath : allCodePaths) {
14850                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14851                    try {
14852                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14853                    } catch (InstallerException ignored) {
14854                    }
14855                }
14856            }
14857        }
14858    }
14859
14860    /**
14861     * Logic to handle installation of non-ASEC applications, including copying
14862     * and renaming logic.
14863     */
14864    class FileInstallArgs extends InstallArgs {
14865        private File codeFile;
14866        private File resourceFile;
14867
14868        // Example topology:
14869        // /data/app/com.example/base.apk
14870        // /data/app/com.example/split_foo.apk
14871        // /data/app/com.example/lib/arm/libfoo.so
14872        // /data/app/com.example/lib/arm64/libfoo.so
14873        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14874
14875        /** New install */
14876        FileInstallArgs(InstallParams params) {
14877            super(params.origin, params.move, params.observer, params.installFlags,
14878                    params.installerPackageName, params.volumeUuid,
14879                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14880                    params.grantedRuntimePermissions,
14881                    params.traceMethod, params.traceCookie, params.certificates,
14882                    params.installReason);
14883            if (isFwdLocked()) {
14884                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14885            }
14886        }
14887
14888        /** Existing install */
14889        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14890            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14891                    null, null, null, 0, null /*certificates*/,
14892                    PackageManager.INSTALL_REASON_UNKNOWN);
14893            this.codeFile = (codePath != null) ? new File(codePath) : null;
14894            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14895        }
14896
14897        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14898            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14899            try {
14900                return doCopyApk(imcs, temp);
14901            } finally {
14902                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14903            }
14904        }
14905
14906        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14907            if (origin.staged) {
14908                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14909                codeFile = origin.file;
14910                resourceFile = origin.file;
14911                return PackageManager.INSTALL_SUCCEEDED;
14912            }
14913
14914            try {
14915                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14916                final File tempDir =
14917                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14918                codeFile = tempDir;
14919                resourceFile = tempDir;
14920            } catch (IOException e) {
14921                Slog.w(TAG, "Failed to create copy file: " + e);
14922                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14923            }
14924
14925            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14926                @Override
14927                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14928                    if (!FileUtils.isValidExtFilename(name)) {
14929                        throw new IllegalArgumentException("Invalid filename: " + name);
14930                    }
14931                    try {
14932                        final File file = new File(codeFile, name);
14933                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14934                                O_RDWR | O_CREAT, 0644);
14935                        Os.chmod(file.getAbsolutePath(), 0644);
14936                        return new ParcelFileDescriptor(fd);
14937                    } catch (ErrnoException e) {
14938                        throw new RemoteException("Failed to open: " + e.getMessage());
14939                    }
14940                }
14941            };
14942
14943            int ret = PackageManager.INSTALL_SUCCEEDED;
14944            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14945            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14946                Slog.e(TAG, "Failed to copy package");
14947                return ret;
14948            }
14949
14950            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14951            NativeLibraryHelper.Handle handle = null;
14952            try {
14953                handle = NativeLibraryHelper.Handle.create(codeFile);
14954                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14955                        abiOverride);
14956            } catch (IOException e) {
14957                Slog.e(TAG, "Copying native libraries failed", e);
14958                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14959            } finally {
14960                IoUtils.closeQuietly(handle);
14961            }
14962
14963            return ret;
14964        }
14965
14966        int doPreInstall(int status) {
14967            if (status != PackageManager.INSTALL_SUCCEEDED) {
14968                cleanUp();
14969            }
14970            return status;
14971        }
14972
14973        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14974            if (status != PackageManager.INSTALL_SUCCEEDED) {
14975                cleanUp();
14976                return false;
14977            }
14978
14979            final File targetDir = codeFile.getParentFile();
14980            final File beforeCodeFile = codeFile;
14981            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14982
14983            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14984            try {
14985                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14986            } catch (ErrnoException e) {
14987                Slog.w(TAG, "Failed to rename", e);
14988                return false;
14989            }
14990
14991            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14992                Slog.w(TAG, "Failed to restorecon");
14993                return false;
14994            }
14995
14996            // Reflect the rename internally
14997            codeFile = afterCodeFile;
14998            resourceFile = afterCodeFile;
14999
15000            // Reflect the rename in scanned details
15001            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15002            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15003                    afterCodeFile, pkg.baseCodePath));
15004            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15005                    afterCodeFile, pkg.splitCodePaths));
15006
15007            // Reflect the rename in app info
15008            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15009            pkg.setApplicationInfoCodePath(pkg.codePath);
15010            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15011            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15012            pkg.setApplicationInfoResourcePath(pkg.codePath);
15013            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15014            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15015
15016            return true;
15017        }
15018
15019        int doPostInstall(int status, int uid) {
15020            if (status != PackageManager.INSTALL_SUCCEEDED) {
15021                cleanUp();
15022            }
15023            return status;
15024        }
15025
15026        @Override
15027        String getCodePath() {
15028            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15029        }
15030
15031        @Override
15032        String getResourcePath() {
15033            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15034        }
15035
15036        private boolean cleanUp() {
15037            if (codeFile == null || !codeFile.exists()) {
15038                return false;
15039            }
15040
15041            removeCodePathLI(codeFile);
15042
15043            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15044                resourceFile.delete();
15045            }
15046
15047            return true;
15048        }
15049
15050        void cleanUpResourcesLI() {
15051            // Try enumerating all code paths before deleting
15052            List<String> allCodePaths = Collections.EMPTY_LIST;
15053            if (codeFile != null && codeFile.exists()) {
15054                try {
15055                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15056                    allCodePaths = pkg.getAllCodePaths();
15057                } catch (PackageParserException e) {
15058                    // Ignored; we tried our best
15059                }
15060            }
15061
15062            cleanUp();
15063            removeDexFiles(allCodePaths, instructionSets);
15064        }
15065
15066        boolean doPostDeleteLI(boolean delete) {
15067            // XXX err, shouldn't we respect the delete flag?
15068            cleanUpResourcesLI();
15069            return true;
15070        }
15071    }
15072
15073    private boolean isAsecExternal(String cid) {
15074        final String asecPath = PackageHelper.getSdFilesystem(cid);
15075        return !asecPath.startsWith(mAsecInternalPath);
15076    }
15077
15078    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15079            PackageManagerException {
15080        if (copyRet < 0) {
15081            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15082                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15083                throw new PackageManagerException(copyRet, message);
15084            }
15085        }
15086    }
15087
15088    /**
15089     * Extract the StorageManagerService "container ID" from the full code path of an
15090     * .apk.
15091     */
15092    static String cidFromCodePath(String fullCodePath) {
15093        int eidx = fullCodePath.lastIndexOf("/");
15094        String subStr1 = fullCodePath.substring(0, eidx);
15095        int sidx = subStr1.lastIndexOf("/");
15096        return subStr1.substring(sidx+1, eidx);
15097    }
15098
15099    /**
15100     * Logic to handle installation of ASEC applications, including copying and
15101     * renaming logic.
15102     */
15103    class AsecInstallArgs extends InstallArgs {
15104        static final String RES_FILE_NAME = "pkg.apk";
15105        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15106
15107        String cid;
15108        String packagePath;
15109        String resourcePath;
15110
15111        /** New install */
15112        AsecInstallArgs(InstallParams params) {
15113            super(params.origin, params.move, params.observer, params.installFlags,
15114                    params.installerPackageName, params.volumeUuid,
15115                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15116                    params.grantedRuntimePermissions,
15117                    params.traceMethod, params.traceCookie, params.certificates,
15118                    params.installReason);
15119        }
15120
15121        /** Existing install */
15122        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15123                        boolean isExternal, boolean isForwardLocked) {
15124            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15125                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15126                    instructionSets, null, null, null, 0, null /*certificates*/,
15127                    PackageManager.INSTALL_REASON_UNKNOWN);
15128            // Hackily pretend we're still looking at a full code path
15129            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15130                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15131            }
15132
15133            // Extract cid from fullCodePath
15134            int eidx = fullCodePath.lastIndexOf("/");
15135            String subStr1 = fullCodePath.substring(0, eidx);
15136            int sidx = subStr1.lastIndexOf("/");
15137            cid = subStr1.substring(sidx+1, eidx);
15138            setMountPath(subStr1);
15139        }
15140
15141        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15142            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15143                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15144                    instructionSets, null, null, null, 0, null /*certificates*/,
15145                    PackageManager.INSTALL_REASON_UNKNOWN);
15146            this.cid = cid;
15147            setMountPath(PackageHelper.getSdDir(cid));
15148        }
15149
15150        void createCopyFile() {
15151            cid = mInstallerService.allocateExternalStageCidLegacy();
15152        }
15153
15154        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15155            if (origin.staged && origin.cid != null) {
15156                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15157                cid = origin.cid;
15158                setMountPath(PackageHelper.getSdDir(cid));
15159                return PackageManager.INSTALL_SUCCEEDED;
15160            }
15161
15162            if (temp) {
15163                createCopyFile();
15164            } else {
15165                /*
15166                 * Pre-emptively destroy the container since it's destroyed if
15167                 * copying fails due to it existing anyway.
15168                 */
15169                PackageHelper.destroySdDir(cid);
15170            }
15171
15172            final String newMountPath = imcs.copyPackageToContainer(
15173                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15174                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15175
15176            if (newMountPath != null) {
15177                setMountPath(newMountPath);
15178                return PackageManager.INSTALL_SUCCEEDED;
15179            } else {
15180                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15181            }
15182        }
15183
15184        @Override
15185        String getCodePath() {
15186            return packagePath;
15187        }
15188
15189        @Override
15190        String getResourcePath() {
15191            return resourcePath;
15192        }
15193
15194        int doPreInstall(int status) {
15195            if (status != PackageManager.INSTALL_SUCCEEDED) {
15196                // Destroy container
15197                PackageHelper.destroySdDir(cid);
15198            } else {
15199                boolean mounted = PackageHelper.isContainerMounted(cid);
15200                if (!mounted) {
15201                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15202                            Process.SYSTEM_UID);
15203                    if (newMountPath != null) {
15204                        setMountPath(newMountPath);
15205                    } else {
15206                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15207                    }
15208                }
15209            }
15210            return status;
15211        }
15212
15213        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15214            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15215            String newMountPath = null;
15216            if (PackageHelper.isContainerMounted(cid)) {
15217                // Unmount the container
15218                if (!PackageHelper.unMountSdDir(cid)) {
15219                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15220                    return false;
15221                }
15222            }
15223            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15224                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15225                        " which might be stale. Will try to clean up.");
15226                // Clean up the stale container and proceed to recreate.
15227                if (!PackageHelper.destroySdDir(newCacheId)) {
15228                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15229                    return false;
15230                }
15231                // Successfully cleaned up stale container. Try to rename again.
15232                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15233                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15234                            + " inspite of cleaning it up.");
15235                    return false;
15236                }
15237            }
15238            if (!PackageHelper.isContainerMounted(newCacheId)) {
15239                Slog.w(TAG, "Mounting container " + newCacheId);
15240                newMountPath = PackageHelper.mountSdDir(newCacheId,
15241                        getEncryptKey(), Process.SYSTEM_UID);
15242            } else {
15243                newMountPath = PackageHelper.getSdDir(newCacheId);
15244            }
15245            if (newMountPath == null) {
15246                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15247                return false;
15248            }
15249            Log.i(TAG, "Succesfully renamed " + cid +
15250                    " to " + newCacheId +
15251                    " at new path: " + newMountPath);
15252            cid = newCacheId;
15253
15254            final File beforeCodeFile = new File(packagePath);
15255            setMountPath(newMountPath);
15256            final File afterCodeFile = new File(packagePath);
15257
15258            // Reflect the rename in scanned details
15259            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15260            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15261                    afterCodeFile, pkg.baseCodePath));
15262            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15263                    afterCodeFile, pkg.splitCodePaths));
15264
15265            // Reflect the rename in app info
15266            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15267            pkg.setApplicationInfoCodePath(pkg.codePath);
15268            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15269            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15270            pkg.setApplicationInfoResourcePath(pkg.codePath);
15271            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15272            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15273
15274            return true;
15275        }
15276
15277        private void setMountPath(String mountPath) {
15278            final File mountFile = new File(mountPath);
15279
15280            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15281            if (monolithicFile.exists()) {
15282                packagePath = monolithicFile.getAbsolutePath();
15283                if (isFwdLocked()) {
15284                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15285                } else {
15286                    resourcePath = packagePath;
15287                }
15288            } else {
15289                packagePath = mountFile.getAbsolutePath();
15290                resourcePath = packagePath;
15291            }
15292        }
15293
15294        int doPostInstall(int status, int uid) {
15295            if (status != PackageManager.INSTALL_SUCCEEDED) {
15296                cleanUp();
15297            } else {
15298                final int groupOwner;
15299                final String protectedFile;
15300                if (isFwdLocked()) {
15301                    groupOwner = UserHandle.getSharedAppGid(uid);
15302                    protectedFile = RES_FILE_NAME;
15303                } else {
15304                    groupOwner = -1;
15305                    protectedFile = null;
15306                }
15307
15308                if (uid < Process.FIRST_APPLICATION_UID
15309                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15310                    Slog.e(TAG, "Failed to finalize " + cid);
15311                    PackageHelper.destroySdDir(cid);
15312                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15313                }
15314
15315                boolean mounted = PackageHelper.isContainerMounted(cid);
15316                if (!mounted) {
15317                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15318                }
15319            }
15320            return status;
15321        }
15322
15323        private void cleanUp() {
15324            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15325
15326            // Destroy secure container
15327            PackageHelper.destroySdDir(cid);
15328        }
15329
15330        private List<String> getAllCodePaths() {
15331            final File codeFile = new File(getCodePath());
15332            if (codeFile != null && codeFile.exists()) {
15333                try {
15334                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15335                    return pkg.getAllCodePaths();
15336                } catch (PackageParserException e) {
15337                    // Ignored; we tried our best
15338                }
15339            }
15340            return Collections.EMPTY_LIST;
15341        }
15342
15343        void cleanUpResourcesLI() {
15344            // Enumerate all code paths before deleting
15345            cleanUpResourcesLI(getAllCodePaths());
15346        }
15347
15348        private void cleanUpResourcesLI(List<String> allCodePaths) {
15349            cleanUp();
15350            removeDexFiles(allCodePaths, instructionSets);
15351        }
15352
15353        String getPackageName() {
15354            return getAsecPackageName(cid);
15355        }
15356
15357        boolean doPostDeleteLI(boolean delete) {
15358            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15359            final List<String> allCodePaths = getAllCodePaths();
15360            boolean mounted = PackageHelper.isContainerMounted(cid);
15361            if (mounted) {
15362                // Unmount first
15363                if (PackageHelper.unMountSdDir(cid)) {
15364                    mounted = false;
15365                }
15366            }
15367            if (!mounted && delete) {
15368                cleanUpResourcesLI(allCodePaths);
15369            }
15370            return !mounted;
15371        }
15372
15373        @Override
15374        int doPreCopy() {
15375            if (isFwdLocked()) {
15376                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15377                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15378                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15379                }
15380            }
15381
15382            return PackageManager.INSTALL_SUCCEEDED;
15383        }
15384
15385        @Override
15386        int doPostCopy(int uid) {
15387            if (isFwdLocked()) {
15388                if (uid < Process.FIRST_APPLICATION_UID
15389                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15390                                RES_FILE_NAME)) {
15391                    Slog.e(TAG, "Failed to finalize " + cid);
15392                    PackageHelper.destroySdDir(cid);
15393                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15394                }
15395            }
15396
15397            return PackageManager.INSTALL_SUCCEEDED;
15398        }
15399    }
15400
15401    /**
15402     * Logic to handle movement of existing installed applications.
15403     */
15404    class MoveInstallArgs extends InstallArgs {
15405        private File codeFile;
15406        private File resourceFile;
15407
15408        /** New install */
15409        MoveInstallArgs(InstallParams params) {
15410            super(params.origin, params.move, params.observer, params.installFlags,
15411                    params.installerPackageName, params.volumeUuid,
15412                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15413                    params.grantedRuntimePermissions,
15414                    params.traceMethod, params.traceCookie, params.certificates,
15415                    params.installReason);
15416        }
15417
15418        int copyApk(IMediaContainerService imcs, boolean temp) {
15419            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15420                    + move.fromUuid + " to " + move.toUuid);
15421            synchronized (mInstaller) {
15422                try {
15423                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15424                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15425                } catch (InstallerException e) {
15426                    Slog.w(TAG, "Failed to move app", e);
15427                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15428                }
15429            }
15430
15431            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15432            resourceFile = codeFile;
15433            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15434
15435            return PackageManager.INSTALL_SUCCEEDED;
15436        }
15437
15438        int doPreInstall(int status) {
15439            if (status != PackageManager.INSTALL_SUCCEEDED) {
15440                cleanUp(move.toUuid);
15441            }
15442            return status;
15443        }
15444
15445        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15446            if (status != PackageManager.INSTALL_SUCCEEDED) {
15447                cleanUp(move.toUuid);
15448                return false;
15449            }
15450
15451            // Reflect the move in app info
15452            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15453            pkg.setApplicationInfoCodePath(pkg.codePath);
15454            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15455            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15456            pkg.setApplicationInfoResourcePath(pkg.codePath);
15457            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15458            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15459
15460            return true;
15461        }
15462
15463        int doPostInstall(int status, int uid) {
15464            if (status == PackageManager.INSTALL_SUCCEEDED) {
15465                cleanUp(move.fromUuid);
15466            } else {
15467                cleanUp(move.toUuid);
15468            }
15469            return status;
15470        }
15471
15472        @Override
15473        String getCodePath() {
15474            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15475        }
15476
15477        @Override
15478        String getResourcePath() {
15479            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15480        }
15481
15482        private boolean cleanUp(String volumeUuid) {
15483            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15484                    move.dataAppName);
15485            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15486            final int[] userIds = sUserManager.getUserIds();
15487            synchronized (mInstallLock) {
15488                // Clean up both app data and code
15489                // All package moves are frozen until finished
15490                for (int userId : userIds) {
15491                    try {
15492                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15493                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15494                    } catch (InstallerException e) {
15495                        Slog.w(TAG, String.valueOf(e));
15496                    }
15497                }
15498                removeCodePathLI(codeFile);
15499            }
15500            return true;
15501        }
15502
15503        void cleanUpResourcesLI() {
15504            throw new UnsupportedOperationException();
15505        }
15506
15507        boolean doPostDeleteLI(boolean delete) {
15508            throw new UnsupportedOperationException();
15509        }
15510    }
15511
15512    static String getAsecPackageName(String packageCid) {
15513        int idx = packageCid.lastIndexOf("-");
15514        if (idx == -1) {
15515            return packageCid;
15516        }
15517        return packageCid.substring(0, idx);
15518    }
15519
15520    // Utility method used to create code paths based on package name and available index.
15521    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15522        String idxStr = "";
15523        int idx = 1;
15524        // Fall back to default value of idx=1 if prefix is not
15525        // part of oldCodePath
15526        if (oldCodePath != null) {
15527            String subStr = oldCodePath;
15528            // Drop the suffix right away
15529            if (suffix != null && subStr.endsWith(suffix)) {
15530                subStr = subStr.substring(0, subStr.length() - suffix.length());
15531            }
15532            // If oldCodePath already contains prefix find out the
15533            // ending index to either increment or decrement.
15534            int sidx = subStr.lastIndexOf(prefix);
15535            if (sidx != -1) {
15536                subStr = subStr.substring(sidx + prefix.length());
15537                if (subStr != null) {
15538                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15539                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15540                    }
15541                    try {
15542                        idx = Integer.parseInt(subStr);
15543                        if (idx <= 1) {
15544                            idx++;
15545                        } else {
15546                            idx--;
15547                        }
15548                    } catch(NumberFormatException e) {
15549                    }
15550                }
15551            }
15552        }
15553        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15554        return prefix + idxStr;
15555    }
15556
15557    private File getNextCodePath(File targetDir, String packageName) {
15558        File result;
15559        SecureRandom random = new SecureRandom();
15560        byte[] bytes = new byte[16];
15561        do {
15562            random.nextBytes(bytes);
15563            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15564            result = new File(targetDir, packageName + "-" + suffix);
15565        } while (result.exists());
15566        return result;
15567    }
15568
15569    // Utility method that returns the relative package path with respect
15570    // to the installation directory. Like say for /data/data/com.test-1.apk
15571    // string com.test-1 is returned.
15572    static String deriveCodePathName(String codePath) {
15573        if (codePath == null) {
15574            return null;
15575        }
15576        final File codeFile = new File(codePath);
15577        final String name = codeFile.getName();
15578        if (codeFile.isDirectory()) {
15579            return name;
15580        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15581            final int lastDot = name.lastIndexOf('.');
15582            return name.substring(0, lastDot);
15583        } else {
15584            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15585            return null;
15586        }
15587    }
15588
15589    static class PackageInstalledInfo {
15590        String name;
15591        int uid;
15592        // The set of users that originally had this package installed.
15593        int[] origUsers;
15594        // The set of users that now have this package installed.
15595        int[] newUsers;
15596        PackageParser.Package pkg;
15597        int returnCode;
15598        String returnMsg;
15599        PackageRemovedInfo removedInfo;
15600        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15601
15602        public void setError(int code, String msg) {
15603            setReturnCode(code);
15604            setReturnMessage(msg);
15605            Slog.w(TAG, msg);
15606        }
15607
15608        public void setError(String msg, PackageParserException e) {
15609            setReturnCode(e.error);
15610            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15611            Slog.w(TAG, msg, e);
15612        }
15613
15614        public void setError(String msg, PackageManagerException e) {
15615            returnCode = e.error;
15616            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15617            Slog.w(TAG, msg, e);
15618        }
15619
15620        public void setReturnCode(int returnCode) {
15621            this.returnCode = returnCode;
15622            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15623            for (int i = 0; i < childCount; i++) {
15624                addedChildPackages.valueAt(i).returnCode = returnCode;
15625            }
15626        }
15627
15628        private void setReturnMessage(String returnMsg) {
15629            this.returnMsg = returnMsg;
15630            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15631            for (int i = 0; i < childCount; i++) {
15632                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15633            }
15634        }
15635
15636        // In some error cases we want to convey more info back to the observer
15637        String origPackage;
15638        String origPermission;
15639    }
15640
15641    /*
15642     * Install a non-existing package.
15643     */
15644    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15645            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15646            PackageInstalledInfo res, int installReason) {
15647        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15648
15649        // Remember this for later, in case we need to rollback this install
15650        String pkgName = pkg.packageName;
15651
15652        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15653
15654        synchronized(mPackages) {
15655            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15656            if (renamedPackage != null) {
15657                // A package with the same name is already installed, though
15658                // it has been renamed to an older name.  The package we
15659                // are trying to install should be installed as an update to
15660                // the existing one, but that has not been requested, so bail.
15661                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15662                        + " without first uninstalling package running as "
15663                        + renamedPackage);
15664                return;
15665            }
15666            if (mPackages.containsKey(pkgName)) {
15667                // Don't allow installation over an existing package with the same name.
15668                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15669                        + " without first uninstalling.");
15670                return;
15671            }
15672        }
15673
15674        try {
15675            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15676                    System.currentTimeMillis(), user);
15677
15678            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15679
15680            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15681                prepareAppDataAfterInstallLIF(newPackage);
15682
15683            } else {
15684                // Remove package from internal structures, but keep around any
15685                // data that might have already existed
15686                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15687                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15688            }
15689        } catch (PackageManagerException e) {
15690            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15691        }
15692
15693        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15694    }
15695
15696    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15697        // Can't rotate keys during boot or if sharedUser.
15698        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15699                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15700            return false;
15701        }
15702        // app is using upgradeKeySets; make sure all are valid
15703        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15704        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15705        for (int i = 0; i < upgradeKeySets.length; i++) {
15706            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15707                Slog.wtf(TAG, "Package "
15708                         + (oldPs.name != null ? oldPs.name : "<null>")
15709                         + " contains upgrade-key-set reference to unknown key-set: "
15710                         + upgradeKeySets[i]
15711                         + " reverting to signatures check.");
15712                return false;
15713            }
15714        }
15715        return true;
15716    }
15717
15718    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15719        // Upgrade keysets are being used.  Determine if new package has a superset of the
15720        // required keys.
15721        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15722        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15723        for (int i = 0; i < upgradeKeySets.length; i++) {
15724            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15725            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15726                return true;
15727            }
15728        }
15729        return false;
15730    }
15731
15732    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15733        try (DigestInputStream digestStream =
15734                new DigestInputStream(new FileInputStream(file), digest)) {
15735            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15736        }
15737    }
15738
15739    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15740            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15741            int installReason) {
15742        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15743
15744        final PackageParser.Package oldPackage;
15745        final String pkgName = pkg.packageName;
15746        final int[] allUsers;
15747        final int[] installedUsers;
15748
15749        synchronized(mPackages) {
15750            oldPackage = mPackages.get(pkgName);
15751            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15752
15753            // don't allow upgrade to target a release SDK from a pre-release SDK
15754            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15755                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15756            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15757                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15758            if (oldTargetsPreRelease
15759                    && !newTargetsPreRelease
15760                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15761                Slog.w(TAG, "Can't install package targeting released sdk");
15762                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15763                return;
15764            }
15765
15766            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15767
15768            // verify signatures are valid
15769            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15770                if (!checkUpgradeKeySetLP(ps, pkg)) {
15771                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15772                            "New package not signed by keys specified by upgrade-keysets: "
15773                                    + pkgName);
15774                    return;
15775                }
15776            } else {
15777                // default to original signature matching
15778                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15779                        != PackageManager.SIGNATURE_MATCH) {
15780                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15781                            "New package has a different signature: " + pkgName);
15782                    return;
15783                }
15784            }
15785
15786            // don't allow a system upgrade unless the upgrade hash matches
15787            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15788                byte[] digestBytes = null;
15789                try {
15790                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15791                    updateDigest(digest, new File(pkg.baseCodePath));
15792                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15793                        for (String path : pkg.splitCodePaths) {
15794                            updateDigest(digest, new File(path));
15795                        }
15796                    }
15797                    digestBytes = digest.digest();
15798                } catch (NoSuchAlgorithmException | IOException e) {
15799                    res.setError(INSTALL_FAILED_INVALID_APK,
15800                            "Could not compute hash: " + pkgName);
15801                    return;
15802                }
15803                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15804                    res.setError(INSTALL_FAILED_INVALID_APK,
15805                            "New package fails restrict-update check: " + pkgName);
15806                    return;
15807                }
15808                // retain upgrade restriction
15809                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15810            }
15811
15812            // Check for shared user id changes
15813            String invalidPackageName =
15814                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15815            if (invalidPackageName != null) {
15816                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15817                        "Package " + invalidPackageName + " tried to change user "
15818                                + oldPackage.mSharedUserId);
15819                return;
15820            }
15821
15822            // In case of rollback, remember per-user/profile install state
15823            allUsers = sUserManager.getUserIds();
15824            installedUsers = ps.queryInstalledUsers(allUsers, true);
15825
15826            // don't allow an upgrade from full to ephemeral
15827            if (isInstantApp) {
15828                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15829                    for (int currentUser : allUsers) {
15830                        if (!ps.getInstantApp(currentUser)) {
15831                            // can't downgrade from full to instant
15832                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15833                                    + " for user: " + currentUser);
15834                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15835                            return;
15836                        }
15837                    }
15838                } else if (!ps.getInstantApp(user.getIdentifier())) {
15839                    // can't downgrade from full to instant
15840                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15841                            + " for user: " + user.getIdentifier());
15842                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15843                    return;
15844                }
15845            }
15846        }
15847
15848        // Update what is removed
15849        res.removedInfo = new PackageRemovedInfo();
15850        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15851        res.removedInfo.removedPackage = oldPackage.packageName;
15852        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15853        res.removedInfo.isUpdate = true;
15854        res.removedInfo.origUsers = installedUsers;
15855        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15856        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15857        for (int i = 0; i < installedUsers.length; i++) {
15858            final int userId = installedUsers[i];
15859            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15860        }
15861
15862        final int childCount = (oldPackage.childPackages != null)
15863                ? oldPackage.childPackages.size() : 0;
15864        for (int i = 0; i < childCount; i++) {
15865            boolean childPackageUpdated = false;
15866            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15867            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15868            if (res.addedChildPackages != null) {
15869                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15870                if (childRes != null) {
15871                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15872                    childRes.removedInfo.removedPackage = childPkg.packageName;
15873                    childRes.removedInfo.isUpdate = true;
15874                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15875                    childPackageUpdated = true;
15876                }
15877            }
15878            if (!childPackageUpdated) {
15879                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15880                childRemovedRes.removedPackage = childPkg.packageName;
15881                childRemovedRes.isUpdate = false;
15882                childRemovedRes.dataRemoved = true;
15883                synchronized (mPackages) {
15884                    if (childPs != null) {
15885                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15886                    }
15887                }
15888                if (res.removedInfo.removedChildPackages == null) {
15889                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15890                }
15891                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15892            }
15893        }
15894
15895        boolean sysPkg = (isSystemApp(oldPackage));
15896        if (sysPkg) {
15897            // Set the system/privileged flags as needed
15898            final boolean privileged =
15899                    (oldPackage.applicationInfo.privateFlags
15900                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15901            final int systemPolicyFlags = policyFlags
15902                    | PackageParser.PARSE_IS_SYSTEM
15903                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15904
15905            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15906                    user, allUsers, installerPackageName, res, installReason);
15907        } else {
15908            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15909                    user, allUsers, installerPackageName, res, installReason);
15910        }
15911    }
15912
15913    public List<String> getPreviousCodePaths(String packageName) {
15914        final PackageSetting ps = mSettings.mPackages.get(packageName);
15915        final List<String> result = new ArrayList<String>();
15916        if (ps != null && ps.oldCodePaths != null) {
15917            result.addAll(ps.oldCodePaths);
15918        }
15919        return result;
15920    }
15921
15922    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15923            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15924            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15925            int installReason) {
15926        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15927                + deletedPackage);
15928
15929        String pkgName = deletedPackage.packageName;
15930        boolean deletedPkg = true;
15931        boolean addedPkg = false;
15932        boolean updatedSettings = false;
15933        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15934        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15935                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15936
15937        final long origUpdateTime = (pkg.mExtras != null)
15938                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15939
15940        // First delete the existing package while retaining the data directory
15941        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15942                res.removedInfo, true, pkg)) {
15943            // If the existing package wasn't successfully deleted
15944            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15945            deletedPkg = false;
15946        } else {
15947            // Successfully deleted the old package; proceed with replace.
15948
15949            // If deleted package lived in a container, give users a chance to
15950            // relinquish resources before killing.
15951            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15952                if (DEBUG_INSTALL) {
15953                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15954                }
15955                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15956                final ArrayList<String> pkgList = new ArrayList<String>(1);
15957                pkgList.add(deletedPackage.applicationInfo.packageName);
15958                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15959            }
15960
15961            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15962                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15963            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15964
15965            try {
15966                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15967                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15968                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15969                        installReason);
15970
15971                // Update the in-memory copy of the previous code paths.
15972                PackageSetting ps = mSettings.mPackages.get(pkgName);
15973                if (!killApp) {
15974                    if (ps.oldCodePaths == null) {
15975                        ps.oldCodePaths = new ArraySet<>();
15976                    }
15977                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15978                    if (deletedPackage.splitCodePaths != null) {
15979                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15980                    }
15981                } else {
15982                    ps.oldCodePaths = null;
15983                }
15984                if (ps.childPackageNames != null) {
15985                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15986                        final String childPkgName = ps.childPackageNames.get(i);
15987                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15988                        childPs.oldCodePaths = ps.oldCodePaths;
15989                    }
15990                }
15991                // set instant app status, but, only if it's explicitly specified
15992                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15993                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15994                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15995                prepareAppDataAfterInstallLIF(newPackage);
15996                addedPkg = true;
15997                mDexManager.notifyPackageUpdated(newPackage.packageName,
15998                        newPackage.baseCodePath, newPackage.splitCodePaths);
15999            } catch (PackageManagerException e) {
16000                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16001            }
16002        }
16003
16004        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16005            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16006
16007            // Revert all internal state mutations and added folders for the failed install
16008            if (addedPkg) {
16009                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16010                        res.removedInfo, true, null);
16011            }
16012
16013            // Restore the old package
16014            if (deletedPkg) {
16015                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16016                File restoreFile = new File(deletedPackage.codePath);
16017                // Parse old package
16018                boolean oldExternal = isExternal(deletedPackage);
16019                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16020                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16021                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16022                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16023                try {
16024                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16025                            null);
16026                } catch (PackageManagerException e) {
16027                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16028                            + e.getMessage());
16029                    return;
16030                }
16031
16032                synchronized (mPackages) {
16033                    // Ensure the installer package name up to date
16034                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16035
16036                    // Update permissions for restored package
16037                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16038
16039                    mSettings.writeLPr();
16040                }
16041
16042                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16043            }
16044        } else {
16045            synchronized (mPackages) {
16046                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16047                if (ps != null) {
16048                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16049                    if (res.removedInfo.removedChildPackages != null) {
16050                        final int childCount = res.removedInfo.removedChildPackages.size();
16051                        // Iterate in reverse as we may modify the collection
16052                        for (int i = childCount - 1; i >= 0; i--) {
16053                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16054                            if (res.addedChildPackages.containsKey(childPackageName)) {
16055                                res.removedInfo.removedChildPackages.removeAt(i);
16056                            } else {
16057                                PackageRemovedInfo childInfo = res.removedInfo
16058                                        .removedChildPackages.valueAt(i);
16059                                childInfo.removedForAllUsers = mPackages.get(
16060                                        childInfo.removedPackage) == null;
16061                            }
16062                        }
16063                    }
16064                }
16065            }
16066        }
16067    }
16068
16069    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16070            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16071            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16072            int installReason) {
16073        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16074                + ", old=" + deletedPackage);
16075
16076        final boolean disabledSystem;
16077
16078        // Remove existing system package
16079        removePackageLI(deletedPackage, true);
16080
16081        synchronized (mPackages) {
16082            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16083        }
16084        if (!disabledSystem) {
16085            // We didn't need to disable the .apk as a current system package,
16086            // which means we are replacing another update that is already
16087            // installed.  We need to make sure to delete the older one's .apk.
16088            res.removedInfo.args = createInstallArgsForExisting(0,
16089                    deletedPackage.applicationInfo.getCodePath(),
16090                    deletedPackage.applicationInfo.getResourcePath(),
16091                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16092        } else {
16093            res.removedInfo.args = null;
16094        }
16095
16096        // Successfully disabled the old package. Now proceed with re-installation
16097        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16098                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16099        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16100
16101        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16102        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16103                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16104
16105        PackageParser.Package newPackage = null;
16106        try {
16107            // Add the package to the internal data structures
16108            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16109
16110            // Set the update and install times
16111            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16112            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16113                    System.currentTimeMillis());
16114
16115            // Update the package dynamic state if succeeded
16116            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16117                // Now that the install succeeded make sure we remove data
16118                // directories for any child package the update removed.
16119                final int deletedChildCount = (deletedPackage.childPackages != null)
16120                        ? deletedPackage.childPackages.size() : 0;
16121                final int newChildCount = (newPackage.childPackages != null)
16122                        ? newPackage.childPackages.size() : 0;
16123                for (int i = 0; i < deletedChildCount; i++) {
16124                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16125                    boolean childPackageDeleted = true;
16126                    for (int j = 0; j < newChildCount; j++) {
16127                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16128                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16129                            childPackageDeleted = false;
16130                            break;
16131                        }
16132                    }
16133                    if (childPackageDeleted) {
16134                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16135                                deletedChildPkg.packageName);
16136                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16137                            PackageRemovedInfo removedChildRes = res.removedInfo
16138                                    .removedChildPackages.get(deletedChildPkg.packageName);
16139                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16140                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16141                        }
16142                    }
16143                }
16144
16145                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16146                        installReason);
16147                prepareAppDataAfterInstallLIF(newPackage);
16148
16149                mDexManager.notifyPackageUpdated(newPackage.packageName,
16150                            newPackage.baseCodePath, newPackage.splitCodePaths);
16151            }
16152        } catch (PackageManagerException e) {
16153            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16154            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16155        }
16156
16157        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16158            // Re installation failed. Restore old information
16159            // Remove new pkg information
16160            if (newPackage != null) {
16161                removeInstalledPackageLI(newPackage, true);
16162            }
16163            // Add back the old system package
16164            try {
16165                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16166            } catch (PackageManagerException e) {
16167                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16168            }
16169
16170            synchronized (mPackages) {
16171                if (disabledSystem) {
16172                    enableSystemPackageLPw(deletedPackage);
16173                }
16174
16175                // Ensure the installer package name up to date
16176                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16177
16178                // Update permissions for restored package
16179                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16180
16181                mSettings.writeLPr();
16182            }
16183
16184            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16185                    + " after failed upgrade");
16186        }
16187    }
16188
16189    /**
16190     * Checks whether the parent or any of the child packages have a change shared
16191     * user. For a package to be a valid update the shred users of the parent and
16192     * the children should match. We may later support changing child shared users.
16193     * @param oldPkg The updated package.
16194     * @param newPkg The update package.
16195     * @return The shared user that change between the versions.
16196     */
16197    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16198            PackageParser.Package newPkg) {
16199        // Check parent shared user
16200        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16201            return newPkg.packageName;
16202        }
16203        // Check child shared users
16204        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16205        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16206        for (int i = 0; i < newChildCount; i++) {
16207            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16208            // If this child was present, did it have the same shared user?
16209            for (int j = 0; j < oldChildCount; j++) {
16210                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16211                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16212                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16213                    return newChildPkg.packageName;
16214                }
16215            }
16216        }
16217        return null;
16218    }
16219
16220    private void removeNativeBinariesLI(PackageSetting ps) {
16221        // Remove the lib path for the parent package
16222        if (ps != null) {
16223            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16224            // Remove the lib path for the child packages
16225            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16226            for (int i = 0; i < childCount; i++) {
16227                PackageSetting childPs = null;
16228                synchronized (mPackages) {
16229                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16230                }
16231                if (childPs != null) {
16232                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16233                            .legacyNativeLibraryPathString);
16234                }
16235            }
16236        }
16237    }
16238
16239    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16240        // Enable the parent package
16241        mSettings.enableSystemPackageLPw(pkg.packageName);
16242        // Enable the child packages
16243        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16244        for (int i = 0; i < childCount; i++) {
16245            PackageParser.Package childPkg = pkg.childPackages.get(i);
16246            mSettings.enableSystemPackageLPw(childPkg.packageName);
16247        }
16248    }
16249
16250    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16251            PackageParser.Package newPkg) {
16252        // Disable the parent package (parent always replaced)
16253        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16254        // Disable the child packages
16255        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16256        for (int i = 0; i < childCount; i++) {
16257            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16258            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16259            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16260        }
16261        return disabled;
16262    }
16263
16264    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16265            String installerPackageName) {
16266        // Enable the parent package
16267        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16268        // Enable the child packages
16269        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16270        for (int i = 0; i < childCount; i++) {
16271            PackageParser.Package childPkg = pkg.childPackages.get(i);
16272            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16273        }
16274    }
16275
16276    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16277        // Collect all used permissions in the UID
16278        ArraySet<String> usedPermissions = new ArraySet<>();
16279        final int packageCount = su.packages.size();
16280        for (int i = 0; i < packageCount; i++) {
16281            PackageSetting ps = su.packages.valueAt(i);
16282            if (ps.pkg == null) {
16283                continue;
16284            }
16285            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16286            for (int j = 0; j < requestedPermCount; j++) {
16287                String permission = ps.pkg.requestedPermissions.get(j);
16288                BasePermission bp = mSettings.mPermissions.get(permission);
16289                if (bp != null) {
16290                    usedPermissions.add(permission);
16291                }
16292            }
16293        }
16294
16295        PermissionsState permissionsState = su.getPermissionsState();
16296        // Prune install permissions
16297        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16298        final int installPermCount = installPermStates.size();
16299        for (int i = installPermCount - 1; i >= 0;  i--) {
16300            PermissionState permissionState = installPermStates.get(i);
16301            if (!usedPermissions.contains(permissionState.getName())) {
16302                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16303                if (bp != null) {
16304                    permissionsState.revokeInstallPermission(bp);
16305                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16306                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16307                }
16308            }
16309        }
16310
16311        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16312
16313        // Prune runtime permissions
16314        for (int userId : allUserIds) {
16315            List<PermissionState> runtimePermStates = permissionsState
16316                    .getRuntimePermissionStates(userId);
16317            final int runtimePermCount = runtimePermStates.size();
16318            for (int i = runtimePermCount - 1; i >= 0; i--) {
16319                PermissionState permissionState = runtimePermStates.get(i);
16320                if (!usedPermissions.contains(permissionState.getName())) {
16321                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16322                    if (bp != null) {
16323                        permissionsState.revokeRuntimePermission(bp, userId);
16324                        permissionsState.updatePermissionFlags(bp, userId,
16325                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16326                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16327                                runtimePermissionChangedUserIds, userId);
16328                    }
16329                }
16330            }
16331        }
16332
16333        return runtimePermissionChangedUserIds;
16334    }
16335
16336    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16337            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16338        // Update the parent package setting
16339        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16340                res, user, installReason);
16341        // Update the child packages setting
16342        final int childCount = (newPackage.childPackages != null)
16343                ? newPackage.childPackages.size() : 0;
16344        for (int i = 0; i < childCount; i++) {
16345            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16346            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16347            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16348                    childRes.origUsers, childRes, user, installReason);
16349        }
16350    }
16351
16352    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16353            String installerPackageName, int[] allUsers, int[] installedForUsers,
16354            PackageInstalledInfo res, UserHandle user, int installReason) {
16355        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16356
16357        String pkgName = newPackage.packageName;
16358        synchronized (mPackages) {
16359            //write settings. the installStatus will be incomplete at this stage.
16360            //note that the new package setting would have already been
16361            //added to mPackages. It hasn't been persisted yet.
16362            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16363            // TODO: Remove this write? It's also written at the end of this method
16364            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16365            mSettings.writeLPr();
16366            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16367        }
16368
16369        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16370        synchronized (mPackages) {
16371            updatePermissionsLPw(newPackage.packageName, newPackage,
16372                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16373                            ? UPDATE_PERMISSIONS_ALL : 0));
16374            // For system-bundled packages, we assume that installing an upgraded version
16375            // of the package implies that the user actually wants to run that new code,
16376            // so we enable the package.
16377            PackageSetting ps = mSettings.mPackages.get(pkgName);
16378            final int userId = user.getIdentifier();
16379            if (ps != null) {
16380                if (isSystemApp(newPackage)) {
16381                    if (DEBUG_INSTALL) {
16382                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16383                    }
16384                    // Enable system package for requested users
16385                    if (res.origUsers != null) {
16386                        for (int origUserId : res.origUsers) {
16387                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16388                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16389                                        origUserId, installerPackageName);
16390                            }
16391                        }
16392                    }
16393                    // Also convey the prior install/uninstall state
16394                    if (allUsers != null && installedForUsers != null) {
16395                        for (int currentUserId : allUsers) {
16396                            final boolean installed = ArrayUtils.contains(
16397                                    installedForUsers, currentUserId);
16398                            if (DEBUG_INSTALL) {
16399                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16400                            }
16401                            ps.setInstalled(installed, currentUserId);
16402                        }
16403                        // these install state changes will be persisted in the
16404                        // upcoming call to mSettings.writeLPr().
16405                    }
16406                }
16407                // It's implied that when a user requests installation, they want the app to be
16408                // installed and enabled.
16409                if (userId != UserHandle.USER_ALL) {
16410                    ps.setInstalled(true, userId);
16411                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16412                }
16413
16414                // When replacing an existing package, preserve the original install reason for all
16415                // users that had the package installed before.
16416                final Set<Integer> previousUserIds = new ArraySet<>();
16417                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16418                    final int installReasonCount = res.removedInfo.installReasons.size();
16419                    for (int i = 0; i < installReasonCount; i++) {
16420                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16421                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16422                        ps.setInstallReason(previousInstallReason, previousUserId);
16423                        previousUserIds.add(previousUserId);
16424                    }
16425                }
16426
16427                // Set install reason for users that are having the package newly installed.
16428                if (userId == UserHandle.USER_ALL) {
16429                    for (int currentUserId : sUserManager.getUserIds()) {
16430                        if (!previousUserIds.contains(currentUserId)) {
16431                            ps.setInstallReason(installReason, currentUserId);
16432                        }
16433                    }
16434                } else if (!previousUserIds.contains(userId)) {
16435                    ps.setInstallReason(installReason, userId);
16436                }
16437                mSettings.writeKernelMappingLPr(ps);
16438            }
16439            res.name = pkgName;
16440            res.uid = newPackage.applicationInfo.uid;
16441            res.pkg = newPackage;
16442            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16443            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16444            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16445            //to update install status
16446            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16447            mSettings.writeLPr();
16448            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16449        }
16450
16451        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16452    }
16453
16454    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16455        try {
16456            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16457            installPackageLI(args, res);
16458        } finally {
16459            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16460        }
16461    }
16462
16463    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16464        final int installFlags = args.installFlags;
16465        final String installerPackageName = args.installerPackageName;
16466        final String volumeUuid = args.volumeUuid;
16467        final File tmpPackageFile = new File(args.getCodePath());
16468        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16469        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16470                || (args.volumeUuid != null));
16471        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16472        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16473        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16474        boolean replace = false;
16475        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16476        if (args.move != null) {
16477            // moving a complete application; perform an initial scan on the new install location
16478            scanFlags |= SCAN_INITIAL;
16479        }
16480        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16481            scanFlags |= SCAN_DONT_KILL_APP;
16482        }
16483        if (instantApp) {
16484            scanFlags |= SCAN_AS_INSTANT_APP;
16485        }
16486        if (fullApp) {
16487            scanFlags |= SCAN_AS_FULL_APP;
16488        }
16489
16490        // Result object to be returned
16491        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16492
16493        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16494
16495        // Sanity check
16496        if (instantApp && (forwardLocked || onExternal)) {
16497            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16498                    + " external=" + onExternal);
16499            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16500            return;
16501        }
16502
16503        // Retrieve PackageSettings and parse package
16504        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16505                | PackageParser.PARSE_ENFORCE_CODE
16506                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16507                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16508                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16509                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16510        PackageParser pp = new PackageParser();
16511        pp.setSeparateProcesses(mSeparateProcesses);
16512        pp.setDisplayMetrics(mMetrics);
16513        pp.setCallback(mPackageParserCallback);
16514
16515        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16516        final PackageParser.Package pkg;
16517        try {
16518            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16519        } catch (PackageParserException e) {
16520            res.setError("Failed parse during installPackageLI", e);
16521            return;
16522        } finally {
16523            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16524        }
16525
16526        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16527        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16528            Slog.w(TAG, "Instant app package " + pkg.packageName
16529                    + " does not target O, this will be a fatal error.");
16530            // STOPSHIP: Make this a fatal error
16531            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16532        }
16533        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16534            Slog.w(TAG, "Instant app package " + pkg.packageName
16535                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16536            // STOPSHIP: Make this a fatal error
16537            pkg.applicationInfo.targetSandboxVersion = 2;
16538        }
16539
16540        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16541            // Static shared libraries have synthetic package names
16542            renameStaticSharedLibraryPackage(pkg);
16543
16544            // No static shared libs on external storage
16545            if (onExternal) {
16546                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16547                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16548                        "Packages declaring static-shared libs cannot be updated");
16549                return;
16550            }
16551        }
16552
16553        // If we are installing a clustered package add results for the children
16554        if (pkg.childPackages != null) {
16555            synchronized (mPackages) {
16556                final int childCount = pkg.childPackages.size();
16557                for (int i = 0; i < childCount; i++) {
16558                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16559                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16560                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16561                    childRes.pkg = childPkg;
16562                    childRes.name = childPkg.packageName;
16563                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16564                    if (childPs != null) {
16565                        childRes.origUsers = childPs.queryInstalledUsers(
16566                                sUserManager.getUserIds(), true);
16567                    }
16568                    if ((mPackages.containsKey(childPkg.packageName))) {
16569                        childRes.removedInfo = new PackageRemovedInfo();
16570                        childRes.removedInfo.removedPackage = childPkg.packageName;
16571                    }
16572                    if (res.addedChildPackages == null) {
16573                        res.addedChildPackages = new ArrayMap<>();
16574                    }
16575                    res.addedChildPackages.put(childPkg.packageName, childRes);
16576                }
16577            }
16578        }
16579
16580        // If package doesn't declare API override, mark that we have an install
16581        // time CPU ABI override.
16582        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16583            pkg.cpuAbiOverride = args.abiOverride;
16584        }
16585
16586        String pkgName = res.name = pkg.packageName;
16587        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16588            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16589                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16590                return;
16591            }
16592        }
16593
16594        try {
16595            // either use what we've been given or parse directly from the APK
16596            if (args.certificates != null) {
16597                try {
16598                    PackageParser.populateCertificates(pkg, args.certificates);
16599                } catch (PackageParserException e) {
16600                    // there was something wrong with the certificates we were given;
16601                    // try to pull them from the APK
16602                    PackageParser.collectCertificates(pkg, parseFlags);
16603                }
16604            } else {
16605                PackageParser.collectCertificates(pkg, parseFlags);
16606            }
16607        } catch (PackageParserException e) {
16608            res.setError("Failed collect during installPackageLI", e);
16609            return;
16610        }
16611
16612        // Get rid of all references to package scan path via parser.
16613        pp = null;
16614        String oldCodePath = null;
16615        boolean systemApp = false;
16616        synchronized (mPackages) {
16617            // Check if installing already existing package
16618            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16619                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16620                if (pkg.mOriginalPackages != null
16621                        && pkg.mOriginalPackages.contains(oldName)
16622                        && mPackages.containsKey(oldName)) {
16623                    // This package is derived from an original package,
16624                    // and this device has been updating from that original
16625                    // name.  We must continue using the original name, so
16626                    // rename the new package here.
16627                    pkg.setPackageName(oldName);
16628                    pkgName = pkg.packageName;
16629                    replace = true;
16630                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16631                            + oldName + " pkgName=" + pkgName);
16632                } else if (mPackages.containsKey(pkgName)) {
16633                    // This package, under its official name, already exists
16634                    // on the device; we should replace it.
16635                    replace = true;
16636                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16637                }
16638
16639                // Child packages are installed through the parent package
16640                if (pkg.parentPackage != null) {
16641                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16642                            "Package " + pkg.packageName + " is child of package "
16643                                    + pkg.parentPackage.parentPackage + ". Child packages "
16644                                    + "can be updated only through the parent package.");
16645                    return;
16646                }
16647
16648                if (replace) {
16649                    // Prevent apps opting out from runtime permissions
16650                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16651                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16652                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16653                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16654                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16655                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16656                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16657                                        + " doesn't support runtime permissions but the old"
16658                                        + " target SDK " + oldTargetSdk + " does.");
16659                        return;
16660                    }
16661                    // Prevent apps from downgrading their targetSandbox.
16662                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16663                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16664                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16665                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16666                                "Package " + pkg.packageName + " new target sandbox "
16667                                + newTargetSandbox + " is incompatible with the previous value of"
16668                                + oldTargetSandbox + ".");
16669                        return;
16670                    }
16671
16672                    // Prevent installing of child packages
16673                    if (oldPackage.parentPackage != null) {
16674                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16675                                "Package " + pkg.packageName + " is child of package "
16676                                        + oldPackage.parentPackage + ". Child packages "
16677                                        + "can be updated only through the parent package.");
16678                        return;
16679                    }
16680                }
16681            }
16682
16683            PackageSetting ps = mSettings.mPackages.get(pkgName);
16684            if (ps != null) {
16685                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16686
16687                // Static shared libs have same package with different versions where
16688                // we internally use a synthetic package name to allow multiple versions
16689                // of the same package, therefore we need to compare signatures against
16690                // the package setting for the latest library version.
16691                PackageSetting signatureCheckPs = ps;
16692                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16693                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16694                    if (libraryEntry != null) {
16695                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16696                    }
16697                }
16698
16699                // Quick sanity check that we're signed correctly if updating;
16700                // we'll check this again later when scanning, but we want to
16701                // bail early here before tripping over redefined permissions.
16702                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16703                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16704                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16705                                + pkg.packageName + " upgrade keys do not match the "
16706                                + "previously installed version");
16707                        return;
16708                    }
16709                } else {
16710                    try {
16711                        verifySignaturesLP(signatureCheckPs, pkg);
16712                    } catch (PackageManagerException e) {
16713                        res.setError(e.error, e.getMessage());
16714                        return;
16715                    }
16716                }
16717
16718                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16719                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16720                    systemApp = (ps.pkg.applicationInfo.flags &
16721                            ApplicationInfo.FLAG_SYSTEM) != 0;
16722                }
16723                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16724            }
16725
16726            int N = pkg.permissions.size();
16727            for (int i = N-1; i >= 0; i--) {
16728                PackageParser.Permission perm = pkg.permissions.get(i);
16729                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16730
16731                // Don't allow anyone but the platform to define ephemeral permissions.
16732                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16733                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16734                    Slog.w(TAG, "Package " + pkg.packageName
16735                            + " attempting to delcare ephemeral permission "
16736                            + perm.info.name + "; Removing ephemeral.");
16737                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16738                }
16739                // Check whether the newly-scanned package wants to define an already-defined perm
16740                if (bp != null) {
16741                    // If the defining package is signed with our cert, it's okay.  This
16742                    // also includes the "updating the same package" case, of course.
16743                    // "updating same package" could also involve key-rotation.
16744                    final boolean sigsOk;
16745                    if (bp.sourcePackage.equals(pkg.packageName)
16746                            && (bp.packageSetting instanceof PackageSetting)
16747                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16748                                    scanFlags))) {
16749                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16750                    } else {
16751                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16752                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16753                    }
16754                    if (!sigsOk) {
16755                        // If the owning package is the system itself, we log but allow
16756                        // install to proceed; we fail the install on all other permission
16757                        // redefinitions.
16758                        if (!bp.sourcePackage.equals("android")) {
16759                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16760                                    + pkg.packageName + " attempting to redeclare permission "
16761                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16762                            res.origPermission = perm.info.name;
16763                            res.origPackage = bp.sourcePackage;
16764                            return;
16765                        } else {
16766                            Slog.w(TAG, "Package " + pkg.packageName
16767                                    + " attempting to redeclare system permission "
16768                                    + perm.info.name + "; ignoring new declaration");
16769                            pkg.permissions.remove(i);
16770                        }
16771                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16772                        // Prevent apps to change protection level to dangerous from any other
16773                        // type as this would allow a privilege escalation where an app adds a
16774                        // normal/signature permission in other app's group and later redefines
16775                        // it as dangerous leading to the group auto-grant.
16776                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16777                                == PermissionInfo.PROTECTION_DANGEROUS) {
16778                            if (bp != null && !bp.isRuntime()) {
16779                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16780                                        + "non-runtime permission " + perm.info.name
16781                                        + " to runtime; keeping old protection level");
16782                                perm.info.protectionLevel = bp.protectionLevel;
16783                            }
16784                        }
16785                    }
16786                }
16787            }
16788        }
16789
16790        if (systemApp) {
16791            if (onExternal) {
16792                // Abort update; system app can't be replaced with app on sdcard
16793                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16794                        "Cannot install updates to system apps on sdcard");
16795                return;
16796            } else if (instantApp) {
16797                // Abort update; system app can't be replaced with an instant app
16798                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16799                        "Cannot update a system app with an instant app");
16800                return;
16801            }
16802        }
16803
16804        if (args.move != null) {
16805            // We did an in-place move, so dex is ready to roll
16806            scanFlags |= SCAN_NO_DEX;
16807            scanFlags |= SCAN_MOVE;
16808
16809            synchronized (mPackages) {
16810                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16811                if (ps == null) {
16812                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16813                            "Missing settings for moved package " + pkgName);
16814                }
16815
16816                // We moved the entire application as-is, so bring over the
16817                // previously derived ABI information.
16818                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16819                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16820            }
16821
16822        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16823            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16824            scanFlags |= SCAN_NO_DEX;
16825
16826            try {
16827                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16828                    args.abiOverride : pkg.cpuAbiOverride);
16829                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16830                        true /*extractLibs*/, mAppLib32InstallDir);
16831            } catch (PackageManagerException pme) {
16832                Slog.e(TAG, "Error deriving application ABI", pme);
16833                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16834                return;
16835            }
16836
16837            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16838            // Do not run PackageDexOptimizer through the local performDexOpt
16839            // method because `pkg` may not be in `mPackages` yet.
16840            //
16841            // Also, don't fail application installs if the dexopt step fails.
16842            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16843                    null /* instructionSets */, false /* checkProfiles */,
16844                    getCompilerFilterForReason(REASON_INSTALL),
16845                    getOrCreateCompilerPackageStats(pkg),
16846                    mDexManager.isUsedByOtherApps(pkg.packageName));
16847            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16848
16849            // Notify BackgroundDexOptService that the package has been changed.
16850            // If this is an update of a package which used to fail to compile,
16851            // BDOS will remove it from its blacklist.
16852            // TODO: Layering violation
16853            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16854        }
16855
16856        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16857            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16858            return;
16859        }
16860
16861        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16862
16863        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16864                "installPackageLI")) {
16865            if (replace) {
16866                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16867                    // Static libs have a synthetic package name containing the version
16868                    // and cannot be updated as an update would get a new package name,
16869                    // unless this is the exact same version code which is useful for
16870                    // development.
16871                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16872                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16873                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16874                                + "static-shared libs cannot be updated");
16875                        return;
16876                    }
16877                }
16878                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16879                        installerPackageName, res, args.installReason);
16880            } else {
16881                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16882                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16883            }
16884        }
16885        synchronized (mPackages) {
16886            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16887            if (ps != null) {
16888                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16889                ps.setUpdateAvailable(false /*updateAvailable*/);
16890            }
16891
16892            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16893            for (int i = 0; i < childCount; i++) {
16894                PackageParser.Package childPkg = pkg.childPackages.get(i);
16895                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16896                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16897                if (childPs != null) {
16898                    childRes.newUsers = childPs.queryInstalledUsers(
16899                            sUserManager.getUserIds(), true);
16900                }
16901            }
16902
16903            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16904                updateSequenceNumberLP(pkgName, res.newUsers);
16905                updateInstantAppInstallerLocked();
16906            }
16907        }
16908    }
16909
16910    private void startIntentFilterVerifications(int userId, boolean replacing,
16911            PackageParser.Package pkg) {
16912        if (mIntentFilterVerifierComponent == null) {
16913            Slog.w(TAG, "No IntentFilter verification will not be done as "
16914                    + "there is no IntentFilterVerifier available!");
16915            return;
16916        }
16917
16918        final int verifierUid = getPackageUid(
16919                mIntentFilterVerifierComponent.getPackageName(),
16920                MATCH_DEBUG_TRIAGED_MISSING,
16921                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16922
16923        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16924        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16925        mHandler.sendMessage(msg);
16926
16927        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16928        for (int i = 0; i < childCount; i++) {
16929            PackageParser.Package childPkg = pkg.childPackages.get(i);
16930            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16931            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16932            mHandler.sendMessage(msg);
16933        }
16934    }
16935
16936    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16937            PackageParser.Package pkg) {
16938        int size = pkg.activities.size();
16939        if (size == 0) {
16940            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16941                    "No activity, so no need to verify any IntentFilter!");
16942            return;
16943        }
16944
16945        final boolean hasDomainURLs = hasDomainURLs(pkg);
16946        if (!hasDomainURLs) {
16947            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16948                    "No domain URLs, so no need to verify any IntentFilter!");
16949            return;
16950        }
16951
16952        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16953                + " if any IntentFilter from the " + size
16954                + " Activities needs verification ...");
16955
16956        int count = 0;
16957        final String packageName = pkg.packageName;
16958
16959        synchronized (mPackages) {
16960            // If this is a new install and we see that we've already run verification for this
16961            // package, we have nothing to do: it means the state was restored from backup.
16962            if (!replacing) {
16963                IntentFilterVerificationInfo ivi =
16964                        mSettings.getIntentFilterVerificationLPr(packageName);
16965                if (ivi != null) {
16966                    if (DEBUG_DOMAIN_VERIFICATION) {
16967                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16968                                + ivi.getStatusString());
16969                    }
16970                    return;
16971                }
16972            }
16973
16974            // If any filters need to be verified, then all need to be.
16975            boolean needToVerify = false;
16976            for (PackageParser.Activity a : pkg.activities) {
16977                for (ActivityIntentInfo filter : a.intents) {
16978                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16979                        if (DEBUG_DOMAIN_VERIFICATION) {
16980                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16981                        }
16982                        needToVerify = true;
16983                        break;
16984                    }
16985                }
16986            }
16987
16988            if (needToVerify) {
16989                final int verificationId = mIntentFilterVerificationToken++;
16990                for (PackageParser.Activity a : pkg.activities) {
16991                    for (ActivityIntentInfo filter : a.intents) {
16992                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16993                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16994                                    "Verification needed for IntentFilter:" + filter.toString());
16995                            mIntentFilterVerifier.addOneIntentFilterVerification(
16996                                    verifierUid, userId, verificationId, filter, packageName);
16997                            count++;
16998                        }
16999                    }
17000                }
17001            }
17002        }
17003
17004        if (count > 0) {
17005            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17006                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17007                    +  " for userId:" + userId);
17008            mIntentFilterVerifier.startVerifications(userId);
17009        } else {
17010            if (DEBUG_DOMAIN_VERIFICATION) {
17011                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17012            }
17013        }
17014    }
17015
17016    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17017        final ComponentName cn  = filter.activity.getComponentName();
17018        final String packageName = cn.getPackageName();
17019
17020        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17021                packageName);
17022        if (ivi == null) {
17023            return true;
17024        }
17025        int status = ivi.getStatus();
17026        switch (status) {
17027            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17028            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17029                return true;
17030
17031            default:
17032                // Nothing to do
17033                return false;
17034        }
17035    }
17036
17037    private static boolean isMultiArch(ApplicationInfo info) {
17038        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17039    }
17040
17041    private static boolean isExternal(PackageParser.Package pkg) {
17042        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17043    }
17044
17045    private static boolean isExternal(PackageSetting ps) {
17046        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17047    }
17048
17049    private static boolean isSystemApp(PackageParser.Package pkg) {
17050        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17051    }
17052
17053    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17054        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17055    }
17056
17057    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17058        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17059    }
17060
17061    private static boolean isSystemApp(PackageSetting ps) {
17062        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17063    }
17064
17065    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17066        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17067    }
17068
17069    private int packageFlagsToInstallFlags(PackageSetting ps) {
17070        int installFlags = 0;
17071        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17072            // This existing package was an external ASEC install when we have
17073            // the external flag without a UUID
17074            installFlags |= PackageManager.INSTALL_EXTERNAL;
17075        }
17076        if (ps.isForwardLocked()) {
17077            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17078        }
17079        return installFlags;
17080    }
17081
17082    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17083        if (isExternal(pkg)) {
17084            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17085                return StorageManager.UUID_PRIMARY_PHYSICAL;
17086            } else {
17087                return pkg.volumeUuid;
17088            }
17089        } else {
17090            return StorageManager.UUID_PRIVATE_INTERNAL;
17091        }
17092    }
17093
17094    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17095        if (isExternal(pkg)) {
17096            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17097                return mSettings.getExternalVersion();
17098            } else {
17099                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17100            }
17101        } else {
17102            return mSettings.getInternalVersion();
17103        }
17104    }
17105
17106    private void deleteTempPackageFiles() {
17107        final FilenameFilter filter = new FilenameFilter() {
17108            public boolean accept(File dir, String name) {
17109                return name.startsWith("vmdl") && name.endsWith(".tmp");
17110            }
17111        };
17112        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17113            file.delete();
17114        }
17115    }
17116
17117    @Override
17118    public void deletePackageAsUser(String packageName, int versionCode,
17119            IPackageDeleteObserver observer, int userId, int flags) {
17120        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17121                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17122    }
17123
17124    @Override
17125    public void deletePackageVersioned(VersionedPackage versionedPackage,
17126            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17127        mContext.enforceCallingOrSelfPermission(
17128                android.Manifest.permission.DELETE_PACKAGES, null);
17129        Preconditions.checkNotNull(versionedPackage);
17130        Preconditions.checkNotNull(observer);
17131        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17132                PackageManager.VERSION_CODE_HIGHEST,
17133                Integer.MAX_VALUE, "versionCode must be >= -1");
17134
17135        final String packageName = versionedPackage.getPackageName();
17136        // TODO: We will change version code to long, so in the new API it is long
17137        final int versionCode = (int) versionedPackage.getVersionCode();
17138        final String internalPackageName;
17139        synchronized (mPackages) {
17140            // Normalize package name to handle renamed packages and static libs
17141            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17142                    // TODO: We will change version code to long, so in the new API it is long
17143                    (int) versionedPackage.getVersionCode());
17144        }
17145
17146        final int uid = Binder.getCallingUid();
17147        if (!isOrphaned(internalPackageName)
17148                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17149            try {
17150                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17151                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17152                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17153                observer.onUserActionRequired(intent);
17154            } catch (RemoteException re) {
17155            }
17156            return;
17157        }
17158        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17159        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17160        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17161            mContext.enforceCallingOrSelfPermission(
17162                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17163                    "deletePackage for user " + userId);
17164        }
17165
17166        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17167            try {
17168                observer.onPackageDeleted(packageName,
17169                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17170            } catch (RemoteException re) {
17171            }
17172            return;
17173        }
17174
17175        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17176            try {
17177                observer.onPackageDeleted(packageName,
17178                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17179            } catch (RemoteException re) {
17180            }
17181            return;
17182        }
17183
17184        if (DEBUG_REMOVE) {
17185            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17186                    + " deleteAllUsers: " + deleteAllUsers + " version="
17187                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17188                    ? "VERSION_CODE_HIGHEST" : versionCode));
17189        }
17190        // Queue up an async operation since the package deletion may take a little while.
17191        mHandler.post(new Runnable() {
17192            public void run() {
17193                mHandler.removeCallbacks(this);
17194                int returnCode;
17195                if (!deleteAllUsers) {
17196                    returnCode = deletePackageX(internalPackageName, versionCode,
17197                            userId, deleteFlags);
17198                } else {
17199                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17200                            internalPackageName, users);
17201                    // If nobody is blocking uninstall, proceed with delete for all users
17202                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17203                        returnCode = deletePackageX(internalPackageName, versionCode,
17204                                userId, deleteFlags);
17205                    } else {
17206                        // Otherwise uninstall individually for users with blockUninstalls=false
17207                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17208                        for (int userId : users) {
17209                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17210                                returnCode = deletePackageX(internalPackageName, versionCode,
17211                                        userId, userFlags);
17212                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17213                                    Slog.w(TAG, "Package delete failed for user " + userId
17214                                            + ", returnCode " + returnCode);
17215                                }
17216                            }
17217                        }
17218                        // The app has only been marked uninstalled for certain users.
17219                        // We still need to report that delete was blocked
17220                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17221                    }
17222                }
17223                try {
17224                    observer.onPackageDeleted(packageName, returnCode, null);
17225                } catch (RemoteException e) {
17226                    Log.i(TAG, "Observer no longer exists.");
17227                } //end catch
17228            } //end run
17229        });
17230    }
17231
17232    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17233        if (pkg.staticSharedLibName != null) {
17234            return pkg.manifestPackageName;
17235        }
17236        return pkg.packageName;
17237    }
17238
17239    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17240        // Handle renamed packages
17241        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17242        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17243
17244        // Is this a static library?
17245        SparseArray<SharedLibraryEntry> versionedLib =
17246                mStaticLibsByDeclaringPackage.get(packageName);
17247        if (versionedLib == null || versionedLib.size() <= 0) {
17248            return packageName;
17249        }
17250
17251        // Figure out which lib versions the caller can see
17252        SparseIntArray versionsCallerCanSee = null;
17253        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17254        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17255                && callingAppId != Process.ROOT_UID) {
17256            versionsCallerCanSee = new SparseIntArray();
17257            String libName = versionedLib.valueAt(0).info.getName();
17258            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17259            if (uidPackages != null) {
17260                for (String uidPackage : uidPackages) {
17261                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17262                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17263                    if (libIdx >= 0) {
17264                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17265                        versionsCallerCanSee.append(libVersion, libVersion);
17266                    }
17267                }
17268            }
17269        }
17270
17271        // Caller can see nothing - done
17272        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17273            return packageName;
17274        }
17275
17276        // Find the version the caller can see and the app version code
17277        SharedLibraryEntry highestVersion = null;
17278        final int versionCount = versionedLib.size();
17279        for (int i = 0; i < versionCount; i++) {
17280            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17281            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17282                    libEntry.info.getVersion()) < 0) {
17283                continue;
17284            }
17285            // TODO: We will change version code to long, so in the new API it is long
17286            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17287            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17288                if (libVersionCode == versionCode) {
17289                    return libEntry.apk;
17290                }
17291            } else if (highestVersion == null) {
17292                highestVersion = libEntry;
17293            } else if (libVersionCode  > highestVersion.info
17294                    .getDeclaringPackage().getVersionCode()) {
17295                highestVersion = libEntry;
17296            }
17297        }
17298
17299        if (highestVersion != null) {
17300            return highestVersion.apk;
17301        }
17302
17303        return packageName;
17304    }
17305
17306    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17307        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17308              || callingUid == Process.SYSTEM_UID) {
17309            return true;
17310        }
17311        final int callingUserId = UserHandle.getUserId(callingUid);
17312        // If the caller installed the pkgName, then allow it to silently uninstall.
17313        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17314            return true;
17315        }
17316
17317        // Allow package verifier to silently uninstall.
17318        if (mRequiredVerifierPackage != null &&
17319                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17320            return true;
17321        }
17322
17323        // Allow package uninstaller to silently uninstall.
17324        if (mRequiredUninstallerPackage != null &&
17325                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17326            return true;
17327        }
17328
17329        // Allow storage manager to silently uninstall.
17330        if (mStorageManagerPackage != null &&
17331                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17332            return true;
17333        }
17334        return false;
17335    }
17336
17337    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17338        int[] result = EMPTY_INT_ARRAY;
17339        for (int userId : userIds) {
17340            if (getBlockUninstallForUser(packageName, userId)) {
17341                result = ArrayUtils.appendInt(result, userId);
17342            }
17343        }
17344        return result;
17345    }
17346
17347    @Override
17348    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17349        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17350    }
17351
17352    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17353        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17354                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17355        try {
17356            if (dpm != null) {
17357                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17358                        /* callingUserOnly =*/ false);
17359                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17360                        : deviceOwnerComponentName.getPackageName();
17361                // Does the package contains the device owner?
17362                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17363                // this check is probably not needed, since DO should be registered as a device
17364                // admin on some user too. (Original bug for this: b/17657954)
17365                if (packageName.equals(deviceOwnerPackageName)) {
17366                    return true;
17367                }
17368                // Does it contain a device admin for any user?
17369                int[] users;
17370                if (userId == UserHandle.USER_ALL) {
17371                    users = sUserManager.getUserIds();
17372                } else {
17373                    users = new int[]{userId};
17374                }
17375                for (int i = 0; i < users.length; ++i) {
17376                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17377                        return true;
17378                    }
17379                }
17380            }
17381        } catch (RemoteException e) {
17382        }
17383        return false;
17384    }
17385
17386    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17387        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17388    }
17389
17390    /**
17391     *  This method is an internal method that could be get invoked either
17392     *  to delete an installed package or to clean up a failed installation.
17393     *  After deleting an installed package, a broadcast is sent to notify any
17394     *  listeners that the package has been removed. For cleaning up a failed
17395     *  installation, the broadcast is not necessary since the package's
17396     *  installation wouldn't have sent the initial broadcast either
17397     *  The key steps in deleting a package are
17398     *  deleting the package information in internal structures like mPackages,
17399     *  deleting the packages base directories through installd
17400     *  updating mSettings to reflect current status
17401     *  persisting settings for later use
17402     *  sending a broadcast if necessary
17403     */
17404    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17405        final PackageRemovedInfo info = new PackageRemovedInfo();
17406        final boolean res;
17407
17408        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17409                ? UserHandle.USER_ALL : userId;
17410
17411        if (isPackageDeviceAdmin(packageName, removeUser)) {
17412            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17413            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17414        }
17415
17416        PackageSetting uninstalledPs = null;
17417        PackageParser.Package pkg = null;
17418
17419        // for the uninstall-updates case and restricted profiles, remember the per-
17420        // user handle installed state
17421        int[] allUsers;
17422        synchronized (mPackages) {
17423            uninstalledPs = mSettings.mPackages.get(packageName);
17424            if (uninstalledPs == null) {
17425                Slog.w(TAG, "Not removing non-existent package " + packageName);
17426                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17427            }
17428
17429            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17430                    && uninstalledPs.versionCode != versionCode) {
17431                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17432                        + uninstalledPs.versionCode + " != " + versionCode);
17433                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17434            }
17435
17436            // Static shared libs can be declared by any package, so let us not
17437            // allow removing a package if it provides a lib others depend on.
17438            pkg = mPackages.get(packageName);
17439            if (pkg != null && pkg.staticSharedLibName != null) {
17440                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17441                        pkg.staticSharedLibVersion);
17442                if (libEntry != null) {
17443                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17444                            libEntry.info, 0, userId);
17445                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17446                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17447                                + " hosting lib " + libEntry.info.getName() + " version "
17448                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17449                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17450                    }
17451                }
17452            }
17453
17454            allUsers = sUserManager.getUserIds();
17455            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17456        }
17457
17458        final int freezeUser;
17459        if (isUpdatedSystemApp(uninstalledPs)
17460                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17461            // We're downgrading a system app, which will apply to all users, so
17462            // freeze them all during the downgrade
17463            freezeUser = UserHandle.USER_ALL;
17464        } else {
17465            freezeUser = removeUser;
17466        }
17467
17468        synchronized (mInstallLock) {
17469            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17470            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17471                    deleteFlags, "deletePackageX")) {
17472                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17473                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17474            }
17475            synchronized (mPackages) {
17476                if (res) {
17477                    if (pkg != null) {
17478                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17479                    }
17480                    updateSequenceNumberLP(packageName, info.removedUsers);
17481                    updateInstantAppInstallerLocked();
17482                }
17483            }
17484        }
17485
17486        if (res) {
17487            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17488            info.sendPackageRemovedBroadcasts(killApp);
17489            info.sendSystemPackageUpdatedBroadcasts();
17490            info.sendSystemPackageAppearedBroadcasts();
17491        }
17492        // Force a gc here.
17493        Runtime.getRuntime().gc();
17494        // Delete the resources here after sending the broadcast to let
17495        // other processes clean up before deleting resources.
17496        if (info.args != null) {
17497            synchronized (mInstallLock) {
17498                info.args.doPostDeleteLI(true);
17499            }
17500        }
17501
17502        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17503    }
17504
17505    class PackageRemovedInfo {
17506        String removedPackage;
17507        int uid = -1;
17508        int removedAppId = -1;
17509        int[] origUsers;
17510        int[] removedUsers = null;
17511        SparseArray<Integer> installReasons;
17512        boolean isRemovedPackageSystemUpdate = false;
17513        boolean isUpdate;
17514        boolean dataRemoved;
17515        boolean removedForAllUsers;
17516        boolean isStaticSharedLib;
17517        // Clean up resources deleted packages.
17518        InstallArgs args = null;
17519        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17520        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17521
17522        void sendPackageRemovedBroadcasts(boolean killApp) {
17523            sendPackageRemovedBroadcastInternal(killApp);
17524            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17525            for (int i = 0; i < childCount; i++) {
17526                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17527                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17528            }
17529        }
17530
17531        void sendSystemPackageUpdatedBroadcasts() {
17532            if (isRemovedPackageSystemUpdate) {
17533                sendSystemPackageUpdatedBroadcastsInternal();
17534                final int childCount = (removedChildPackages != null)
17535                        ? removedChildPackages.size() : 0;
17536                for (int i = 0; i < childCount; i++) {
17537                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17538                    if (childInfo.isRemovedPackageSystemUpdate) {
17539                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17540                    }
17541                }
17542            }
17543        }
17544
17545        void sendSystemPackageAppearedBroadcasts() {
17546            final int packageCount = (appearedChildPackages != null)
17547                    ? appearedChildPackages.size() : 0;
17548            for (int i = 0; i < packageCount; i++) {
17549                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17550                sendPackageAddedForNewUsers(installedInfo.name, true,
17551                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17552            }
17553        }
17554
17555        private void sendSystemPackageUpdatedBroadcastsInternal() {
17556            Bundle extras = new Bundle(2);
17557            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17558            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17559            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17560                    extras, 0, null, null, null);
17561            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17562                    extras, 0, null, null, null);
17563            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17564                    null, 0, removedPackage, null, null);
17565        }
17566
17567        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17568            // Don't send static shared library removal broadcasts as these
17569            // libs are visible only the the apps that depend on them an one
17570            // cannot remove the library if it has a dependency.
17571            if (isStaticSharedLib) {
17572                return;
17573            }
17574            Bundle extras = new Bundle(2);
17575            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17576            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17577            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17578            if (isUpdate || isRemovedPackageSystemUpdate) {
17579                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17580            }
17581            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17582            if (removedPackage != null) {
17583                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17584                        extras, 0, null, null, removedUsers);
17585                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17586                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17587                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17588                            null, null, removedUsers);
17589                }
17590            }
17591            if (removedAppId >= 0) {
17592                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17593                        removedUsers);
17594            }
17595        }
17596    }
17597
17598    /*
17599     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17600     * flag is not set, the data directory is removed as well.
17601     * make sure this flag is set for partially installed apps. If not its meaningless to
17602     * delete a partially installed application.
17603     */
17604    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17605            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17606        String packageName = ps.name;
17607        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17608        // Retrieve object to delete permissions for shared user later on
17609        final PackageParser.Package deletedPkg;
17610        final PackageSetting deletedPs;
17611        // reader
17612        synchronized (mPackages) {
17613            deletedPkg = mPackages.get(packageName);
17614            deletedPs = mSettings.mPackages.get(packageName);
17615            if (outInfo != null) {
17616                outInfo.removedPackage = packageName;
17617                outInfo.isStaticSharedLib = deletedPkg != null
17618                        && deletedPkg.staticSharedLibName != null;
17619                outInfo.removedUsers = deletedPs != null
17620                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17621                        : null;
17622            }
17623        }
17624
17625        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17626
17627        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17628            final PackageParser.Package resolvedPkg;
17629            if (deletedPkg != null) {
17630                resolvedPkg = deletedPkg;
17631            } else {
17632                // We don't have a parsed package when it lives on an ejected
17633                // adopted storage device, so fake something together
17634                resolvedPkg = new PackageParser.Package(ps.name);
17635                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17636            }
17637            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17638                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17639            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17640            if (outInfo != null) {
17641                outInfo.dataRemoved = true;
17642            }
17643            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17644        }
17645
17646        int removedAppId = -1;
17647
17648        // writer
17649        synchronized (mPackages) {
17650            boolean installedStateChanged = false;
17651            if (deletedPs != null) {
17652                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17653                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17654                    clearDefaultBrowserIfNeeded(packageName);
17655                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17656                    removedAppId = mSettings.removePackageLPw(packageName);
17657                    if (outInfo != null) {
17658                        outInfo.removedAppId = removedAppId;
17659                    }
17660                    updatePermissionsLPw(deletedPs.name, null, 0);
17661                    if (deletedPs.sharedUser != null) {
17662                        // Remove permissions associated with package. Since runtime
17663                        // permissions are per user we have to kill the removed package
17664                        // or packages running under the shared user of the removed
17665                        // package if revoking the permissions requested only by the removed
17666                        // package is successful and this causes a change in gids.
17667                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17668                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17669                                    userId);
17670                            if (userIdToKill == UserHandle.USER_ALL
17671                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17672                                // If gids changed for this user, kill all affected packages.
17673                                mHandler.post(new Runnable() {
17674                                    @Override
17675                                    public void run() {
17676                                        // This has to happen with no lock held.
17677                                        killApplication(deletedPs.name, deletedPs.appId,
17678                                                KILL_APP_REASON_GIDS_CHANGED);
17679                                    }
17680                                });
17681                                break;
17682                            }
17683                        }
17684                    }
17685                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17686                }
17687                // make sure to preserve per-user disabled state if this removal was just
17688                // a downgrade of a system app to the factory package
17689                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17690                    if (DEBUG_REMOVE) {
17691                        Slog.d(TAG, "Propagating install state across downgrade");
17692                    }
17693                    for (int userId : allUserHandles) {
17694                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17695                        if (DEBUG_REMOVE) {
17696                            Slog.d(TAG, "    user " + userId + " => " + installed);
17697                        }
17698                        if (installed != ps.getInstalled(userId)) {
17699                            installedStateChanged = true;
17700                        }
17701                        ps.setInstalled(installed, userId);
17702                    }
17703                }
17704            }
17705            // can downgrade to reader
17706            if (writeSettings) {
17707                // Save settings now
17708                mSettings.writeLPr();
17709            }
17710            if (installedStateChanged) {
17711                mSettings.writeKernelMappingLPr(ps);
17712            }
17713        }
17714        if (removedAppId != -1) {
17715            // A user ID was deleted here. Go through all users and remove it
17716            // from KeyStore.
17717            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17718        }
17719    }
17720
17721    static boolean locationIsPrivileged(File path) {
17722        try {
17723            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17724                    .getCanonicalPath();
17725            return path.getCanonicalPath().startsWith(privilegedAppDir);
17726        } catch (IOException e) {
17727            Slog.e(TAG, "Unable to access code path " + path);
17728        }
17729        return false;
17730    }
17731
17732    /*
17733     * Tries to delete system package.
17734     */
17735    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17736            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17737            boolean writeSettings) {
17738        if (deletedPs.parentPackageName != null) {
17739            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17740            return false;
17741        }
17742
17743        final boolean applyUserRestrictions
17744                = (allUserHandles != null) && (outInfo.origUsers != null);
17745        final PackageSetting disabledPs;
17746        // Confirm if the system package has been updated
17747        // An updated system app can be deleted. This will also have to restore
17748        // the system pkg from system partition
17749        // reader
17750        synchronized (mPackages) {
17751            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17752        }
17753
17754        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17755                + " disabledPs=" + disabledPs);
17756
17757        if (disabledPs == null) {
17758            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17759            return false;
17760        } else if (DEBUG_REMOVE) {
17761            Slog.d(TAG, "Deleting system pkg from data partition");
17762        }
17763
17764        if (DEBUG_REMOVE) {
17765            if (applyUserRestrictions) {
17766                Slog.d(TAG, "Remembering install states:");
17767                for (int userId : allUserHandles) {
17768                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17769                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17770                }
17771            }
17772        }
17773
17774        // Delete the updated package
17775        outInfo.isRemovedPackageSystemUpdate = true;
17776        if (outInfo.removedChildPackages != null) {
17777            final int childCount = (deletedPs.childPackageNames != null)
17778                    ? deletedPs.childPackageNames.size() : 0;
17779            for (int i = 0; i < childCount; i++) {
17780                String childPackageName = deletedPs.childPackageNames.get(i);
17781                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17782                        .contains(childPackageName)) {
17783                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17784                            childPackageName);
17785                    if (childInfo != null) {
17786                        childInfo.isRemovedPackageSystemUpdate = true;
17787                    }
17788                }
17789            }
17790        }
17791
17792        if (disabledPs.versionCode < deletedPs.versionCode) {
17793            // Delete data for downgrades
17794            flags &= ~PackageManager.DELETE_KEEP_DATA;
17795        } else {
17796            // Preserve data by setting flag
17797            flags |= PackageManager.DELETE_KEEP_DATA;
17798        }
17799
17800        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17801                outInfo, writeSettings, disabledPs.pkg);
17802        if (!ret) {
17803            return false;
17804        }
17805
17806        // writer
17807        synchronized (mPackages) {
17808            // Reinstate the old system package
17809            enableSystemPackageLPw(disabledPs.pkg);
17810            // Remove any native libraries from the upgraded package.
17811            removeNativeBinariesLI(deletedPs);
17812        }
17813
17814        // Install the system package
17815        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17816        int parseFlags = mDefParseFlags
17817                | PackageParser.PARSE_MUST_BE_APK
17818                | PackageParser.PARSE_IS_SYSTEM
17819                | PackageParser.PARSE_IS_SYSTEM_DIR;
17820        if (locationIsPrivileged(disabledPs.codePath)) {
17821            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17822        }
17823
17824        final PackageParser.Package newPkg;
17825        try {
17826            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17827                0 /* currentTime */, null);
17828        } catch (PackageManagerException e) {
17829            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17830                    + e.getMessage());
17831            return false;
17832        }
17833
17834        try {
17835            // update shared libraries for the newly re-installed system package
17836            updateSharedLibrariesLPr(newPkg, null);
17837        } catch (PackageManagerException e) {
17838            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17839        }
17840
17841        prepareAppDataAfterInstallLIF(newPkg);
17842
17843        // writer
17844        synchronized (mPackages) {
17845            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17846
17847            // Propagate the permissions state as we do not want to drop on the floor
17848            // runtime permissions. The update permissions method below will take
17849            // care of removing obsolete permissions and grant install permissions.
17850            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17851            updatePermissionsLPw(newPkg.packageName, newPkg,
17852                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17853
17854            if (applyUserRestrictions) {
17855                boolean installedStateChanged = false;
17856                if (DEBUG_REMOVE) {
17857                    Slog.d(TAG, "Propagating install state across reinstall");
17858                }
17859                for (int userId : allUserHandles) {
17860                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17861                    if (DEBUG_REMOVE) {
17862                        Slog.d(TAG, "    user " + userId + " => " + installed);
17863                    }
17864                    if (installed != ps.getInstalled(userId)) {
17865                        installedStateChanged = true;
17866                    }
17867                    ps.setInstalled(installed, userId);
17868
17869                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17870                }
17871                // Regardless of writeSettings we need to ensure that this restriction
17872                // state propagation is persisted
17873                mSettings.writeAllUsersPackageRestrictionsLPr();
17874                if (installedStateChanged) {
17875                    mSettings.writeKernelMappingLPr(ps);
17876                }
17877            }
17878            // can downgrade to reader here
17879            if (writeSettings) {
17880                mSettings.writeLPr();
17881            }
17882        }
17883        return true;
17884    }
17885
17886    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17887            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17888            PackageRemovedInfo outInfo, boolean writeSettings,
17889            PackageParser.Package replacingPackage) {
17890        synchronized (mPackages) {
17891            if (outInfo != null) {
17892                outInfo.uid = ps.appId;
17893            }
17894
17895            if (outInfo != null && outInfo.removedChildPackages != null) {
17896                final int childCount = (ps.childPackageNames != null)
17897                        ? ps.childPackageNames.size() : 0;
17898                for (int i = 0; i < childCount; i++) {
17899                    String childPackageName = ps.childPackageNames.get(i);
17900                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17901                    if (childPs == null) {
17902                        return false;
17903                    }
17904                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17905                            childPackageName);
17906                    if (childInfo != null) {
17907                        childInfo.uid = childPs.appId;
17908                    }
17909                }
17910            }
17911        }
17912
17913        // Delete package data from internal structures and also remove data if flag is set
17914        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17915
17916        // Delete the child packages data
17917        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17918        for (int i = 0; i < childCount; i++) {
17919            PackageSetting childPs;
17920            synchronized (mPackages) {
17921                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17922            }
17923            if (childPs != null) {
17924                PackageRemovedInfo childOutInfo = (outInfo != null
17925                        && outInfo.removedChildPackages != null)
17926                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17927                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17928                        && (replacingPackage != null
17929                        && !replacingPackage.hasChildPackage(childPs.name))
17930                        ? flags & ~DELETE_KEEP_DATA : flags;
17931                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17932                        deleteFlags, writeSettings);
17933            }
17934        }
17935
17936        // Delete application code and resources only for parent packages
17937        if (ps.parentPackageName == null) {
17938            if (deleteCodeAndResources && (outInfo != null)) {
17939                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17940                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17941                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17942            }
17943        }
17944
17945        return true;
17946    }
17947
17948    @Override
17949    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17950            int userId) {
17951        mContext.enforceCallingOrSelfPermission(
17952                android.Manifest.permission.DELETE_PACKAGES, null);
17953        synchronized (mPackages) {
17954            PackageSetting ps = mSettings.mPackages.get(packageName);
17955            if (ps == null) {
17956                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17957                return false;
17958            }
17959            // Cannot block uninstall of static shared libs as they are
17960            // considered a part of the using app (emulating static linking).
17961            // Also static libs are installed always on internal storage.
17962            PackageParser.Package pkg = mPackages.get(packageName);
17963            if (pkg != null && pkg.staticSharedLibName != null) {
17964                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17965                        + " providing static shared library: " + pkg.staticSharedLibName);
17966                return false;
17967            }
17968            if (!ps.getInstalled(userId)) {
17969                // Can't block uninstall for an app that is not installed or enabled.
17970                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17971                return false;
17972            }
17973            ps.setBlockUninstall(blockUninstall, userId);
17974            mSettings.writePackageRestrictionsLPr(userId);
17975        }
17976        return true;
17977    }
17978
17979    @Override
17980    public boolean getBlockUninstallForUser(String packageName, int userId) {
17981        synchronized (mPackages) {
17982            PackageSetting ps = mSettings.mPackages.get(packageName);
17983            if (ps == null) {
17984                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17985                return false;
17986            }
17987            return ps.getBlockUninstall(userId);
17988        }
17989    }
17990
17991    @Override
17992    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17993        int callingUid = Binder.getCallingUid();
17994        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17995            throw new SecurityException(
17996                    "setRequiredForSystemUser can only be run by the system or root");
17997        }
17998        synchronized (mPackages) {
17999            PackageSetting ps = mSettings.mPackages.get(packageName);
18000            if (ps == null) {
18001                Log.w(TAG, "Package doesn't exist: " + packageName);
18002                return false;
18003            }
18004            if (systemUserApp) {
18005                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18006            } else {
18007                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18008            }
18009            mSettings.writeLPr();
18010        }
18011        return true;
18012    }
18013
18014    /*
18015     * This method handles package deletion in general
18016     */
18017    private boolean deletePackageLIF(String packageName, UserHandle user,
18018            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18019            PackageRemovedInfo outInfo, boolean writeSettings,
18020            PackageParser.Package replacingPackage) {
18021        if (packageName == null) {
18022            Slog.w(TAG, "Attempt to delete null packageName.");
18023            return false;
18024        }
18025
18026        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18027
18028        PackageSetting ps;
18029        synchronized (mPackages) {
18030            ps = mSettings.mPackages.get(packageName);
18031            if (ps == null) {
18032                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18033                return false;
18034            }
18035
18036            if (ps.parentPackageName != null && (!isSystemApp(ps)
18037                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18038                if (DEBUG_REMOVE) {
18039                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18040                            + ((user == null) ? UserHandle.USER_ALL : user));
18041                }
18042                final int removedUserId = (user != null) ? user.getIdentifier()
18043                        : UserHandle.USER_ALL;
18044                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18045                    return false;
18046                }
18047                markPackageUninstalledForUserLPw(ps, user);
18048                scheduleWritePackageRestrictionsLocked(user);
18049                return true;
18050            }
18051        }
18052
18053        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18054                && user.getIdentifier() != UserHandle.USER_ALL)) {
18055            // The caller is asking that the package only be deleted for a single
18056            // user.  To do this, we just mark its uninstalled state and delete
18057            // its data. If this is a system app, we only allow this to happen if
18058            // they have set the special DELETE_SYSTEM_APP which requests different
18059            // semantics than normal for uninstalling system apps.
18060            markPackageUninstalledForUserLPw(ps, user);
18061
18062            if (!isSystemApp(ps)) {
18063                // Do not uninstall the APK if an app should be cached
18064                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18065                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18066                    // Other user still have this package installed, so all
18067                    // we need to do is clear this user's data and save that
18068                    // it is uninstalled.
18069                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18070                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18071                        return false;
18072                    }
18073                    scheduleWritePackageRestrictionsLocked(user);
18074                    return true;
18075                } else {
18076                    // We need to set it back to 'installed' so the uninstall
18077                    // broadcasts will be sent correctly.
18078                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18079                    ps.setInstalled(true, user.getIdentifier());
18080                    mSettings.writeKernelMappingLPr(ps);
18081                }
18082            } else {
18083                // This is a system app, so we assume that the
18084                // other users still have this package installed, so all
18085                // we need to do is clear this user's data and save that
18086                // it is uninstalled.
18087                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18088                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18089                    return false;
18090                }
18091                scheduleWritePackageRestrictionsLocked(user);
18092                return true;
18093            }
18094        }
18095
18096        // If we are deleting a composite package for all users, keep track
18097        // of result for each child.
18098        if (ps.childPackageNames != null && outInfo != null) {
18099            synchronized (mPackages) {
18100                final int childCount = ps.childPackageNames.size();
18101                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18102                for (int i = 0; i < childCount; i++) {
18103                    String childPackageName = ps.childPackageNames.get(i);
18104                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18105                    childInfo.removedPackage = childPackageName;
18106                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18107                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18108                    if (childPs != null) {
18109                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18110                    }
18111                }
18112            }
18113        }
18114
18115        boolean ret = false;
18116        if (isSystemApp(ps)) {
18117            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18118            // When an updated system application is deleted we delete the existing resources
18119            // as well and fall back to existing code in system partition
18120            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18121        } else {
18122            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18123            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18124                    outInfo, writeSettings, replacingPackage);
18125        }
18126
18127        // Take a note whether we deleted the package for all users
18128        if (outInfo != null) {
18129            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18130            if (outInfo.removedChildPackages != null) {
18131                synchronized (mPackages) {
18132                    final int childCount = outInfo.removedChildPackages.size();
18133                    for (int i = 0; i < childCount; i++) {
18134                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18135                        if (childInfo != null) {
18136                            childInfo.removedForAllUsers = mPackages.get(
18137                                    childInfo.removedPackage) == null;
18138                        }
18139                    }
18140                }
18141            }
18142            // If we uninstalled an update to a system app there may be some
18143            // child packages that appeared as they are declared in the system
18144            // app but were not declared in the update.
18145            if (isSystemApp(ps)) {
18146                synchronized (mPackages) {
18147                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18148                    final int childCount = (updatedPs.childPackageNames != null)
18149                            ? updatedPs.childPackageNames.size() : 0;
18150                    for (int i = 0; i < childCount; i++) {
18151                        String childPackageName = updatedPs.childPackageNames.get(i);
18152                        if (outInfo.removedChildPackages == null
18153                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18154                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18155                            if (childPs == null) {
18156                                continue;
18157                            }
18158                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18159                            installRes.name = childPackageName;
18160                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18161                            installRes.pkg = mPackages.get(childPackageName);
18162                            installRes.uid = childPs.pkg.applicationInfo.uid;
18163                            if (outInfo.appearedChildPackages == null) {
18164                                outInfo.appearedChildPackages = new ArrayMap<>();
18165                            }
18166                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18167                        }
18168                    }
18169                }
18170            }
18171        }
18172
18173        return ret;
18174    }
18175
18176    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18177        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18178                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18179        for (int nextUserId : userIds) {
18180            if (DEBUG_REMOVE) {
18181                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18182            }
18183            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18184                    false /*installed*/,
18185                    true /*stopped*/,
18186                    true /*notLaunched*/,
18187                    false /*hidden*/,
18188                    false /*suspended*/,
18189                    false /*instantApp*/,
18190                    null /*lastDisableAppCaller*/,
18191                    null /*enabledComponents*/,
18192                    null /*disabledComponents*/,
18193                    false /*blockUninstall*/,
18194                    ps.readUserState(nextUserId).domainVerificationStatus,
18195                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18196        }
18197        mSettings.writeKernelMappingLPr(ps);
18198    }
18199
18200    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18201            PackageRemovedInfo outInfo) {
18202        final PackageParser.Package pkg;
18203        synchronized (mPackages) {
18204            pkg = mPackages.get(ps.name);
18205        }
18206
18207        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18208                : new int[] {userId};
18209        for (int nextUserId : userIds) {
18210            if (DEBUG_REMOVE) {
18211                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18212                        + nextUserId);
18213            }
18214
18215            destroyAppDataLIF(pkg, userId,
18216                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18217            destroyAppProfilesLIF(pkg, userId);
18218            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18219            schedulePackageCleaning(ps.name, nextUserId, false);
18220            synchronized (mPackages) {
18221                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18222                    scheduleWritePackageRestrictionsLocked(nextUserId);
18223                }
18224                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18225            }
18226        }
18227
18228        if (outInfo != null) {
18229            outInfo.removedPackage = ps.name;
18230            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18231            outInfo.removedAppId = ps.appId;
18232            outInfo.removedUsers = userIds;
18233        }
18234
18235        return true;
18236    }
18237
18238    private final class ClearStorageConnection implements ServiceConnection {
18239        IMediaContainerService mContainerService;
18240
18241        @Override
18242        public void onServiceConnected(ComponentName name, IBinder service) {
18243            synchronized (this) {
18244                mContainerService = IMediaContainerService.Stub
18245                        .asInterface(Binder.allowBlocking(service));
18246                notifyAll();
18247            }
18248        }
18249
18250        @Override
18251        public void onServiceDisconnected(ComponentName name) {
18252        }
18253    }
18254
18255    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18256        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18257
18258        final boolean mounted;
18259        if (Environment.isExternalStorageEmulated()) {
18260            mounted = true;
18261        } else {
18262            final String status = Environment.getExternalStorageState();
18263
18264            mounted = status.equals(Environment.MEDIA_MOUNTED)
18265                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18266        }
18267
18268        if (!mounted) {
18269            return;
18270        }
18271
18272        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18273        int[] users;
18274        if (userId == UserHandle.USER_ALL) {
18275            users = sUserManager.getUserIds();
18276        } else {
18277            users = new int[] { userId };
18278        }
18279        final ClearStorageConnection conn = new ClearStorageConnection();
18280        if (mContext.bindServiceAsUser(
18281                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18282            try {
18283                for (int curUser : users) {
18284                    long timeout = SystemClock.uptimeMillis() + 5000;
18285                    synchronized (conn) {
18286                        long now;
18287                        while (conn.mContainerService == null &&
18288                                (now = SystemClock.uptimeMillis()) < timeout) {
18289                            try {
18290                                conn.wait(timeout - now);
18291                            } catch (InterruptedException e) {
18292                            }
18293                        }
18294                    }
18295                    if (conn.mContainerService == null) {
18296                        return;
18297                    }
18298
18299                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18300                    clearDirectory(conn.mContainerService,
18301                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18302                    if (allData) {
18303                        clearDirectory(conn.mContainerService,
18304                                userEnv.buildExternalStorageAppDataDirs(packageName));
18305                        clearDirectory(conn.mContainerService,
18306                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18307                    }
18308                }
18309            } finally {
18310                mContext.unbindService(conn);
18311            }
18312        }
18313    }
18314
18315    @Override
18316    public void clearApplicationProfileData(String packageName) {
18317        enforceSystemOrRoot("Only the system can clear all profile data");
18318
18319        final PackageParser.Package pkg;
18320        synchronized (mPackages) {
18321            pkg = mPackages.get(packageName);
18322        }
18323
18324        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18325            synchronized (mInstallLock) {
18326                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18327            }
18328        }
18329    }
18330
18331    @Override
18332    public void clearApplicationUserData(final String packageName,
18333            final IPackageDataObserver observer, final int userId) {
18334        mContext.enforceCallingOrSelfPermission(
18335                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18336
18337        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18338                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18339
18340        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18341            throw new SecurityException("Cannot clear data for a protected package: "
18342                    + packageName);
18343        }
18344        // Queue up an async operation since the package deletion may take a little while.
18345        mHandler.post(new Runnable() {
18346            public void run() {
18347                mHandler.removeCallbacks(this);
18348                final boolean succeeded;
18349                try (PackageFreezer freezer = freezePackage(packageName,
18350                        "clearApplicationUserData")) {
18351                    synchronized (mInstallLock) {
18352                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18353                    }
18354                    clearExternalStorageDataSync(packageName, userId, true);
18355                    synchronized (mPackages) {
18356                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18357                                packageName, userId);
18358                    }
18359                }
18360                if (succeeded) {
18361                    // invoke DeviceStorageMonitor's update method to clear any notifications
18362                    DeviceStorageMonitorInternal dsm = LocalServices
18363                            .getService(DeviceStorageMonitorInternal.class);
18364                    if (dsm != null) {
18365                        dsm.checkMemory();
18366                    }
18367                }
18368                if(observer != null) {
18369                    try {
18370                        observer.onRemoveCompleted(packageName, succeeded);
18371                    } catch (RemoteException e) {
18372                        Log.i(TAG, "Observer no longer exists.");
18373                    }
18374                } //end if observer
18375            } //end run
18376        });
18377    }
18378
18379    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18380        if (packageName == null) {
18381            Slog.w(TAG, "Attempt to delete null packageName.");
18382            return false;
18383        }
18384
18385        // Try finding details about the requested package
18386        PackageParser.Package pkg;
18387        synchronized (mPackages) {
18388            pkg = mPackages.get(packageName);
18389            if (pkg == null) {
18390                final PackageSetting ps = mSettings.mPackages.get(packageName);
18391                if (ps != null) {
18392                    pkg = ps.pkg;
18393                }
18394            }
18395
18396            if (pkg == null) {
18397                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18398                return false;
18399            }
18400
18401            PackageSetting ps = (PackageSetting) pkg.mExtras;
18402            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18403        }
18404
18405        clearAppDataLIF(pkg, userId,
18406                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18407
18408        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18409        removeKeystoreDataIfNeeded(userId, appId);
18410
18411        UserManagerInternal umInternal = getUserManagerInternal();
18412        final int flags;
18413        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18414            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18415        } else if (umInternal.isUserRunning(userId)) {
18416            flags = StorageManager.FLAG_STORAGE_DE;
18417        } else {
18418            flags = 0;
18419        }
18420        prepareAppDataContentsLIF(pkg, userId, flags);
18421
18422        return true;
18423    }
18424
18425    /**
18426     * Reverts user permission state changes (permissions and flags) in
18427     * all packages for a given user.
18428     *
18429     * @param userId The device user for which to do a reset.
18430     */
18431    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18432        final int packageCount = mPackages.size();
18433        for (int i = 0; i < packageCount; i++) {
18434            PackageParser.Package pkg = mPackages.valueAt(i);
18435            PackageSetting ps = (PackageSetting) pkg.mExtras;
18436            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18437        }
18438    }
18439
18440    private void resetNetworkPolicies(int userId) {
18441        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18442    }
18443
18444    /**
18445     * Reverts user permission state changes (permissions and flags).
18446     *
18447     * @param ps The package for which to reset.
18448     * @param userId The device user for which to do a reset.
18449     */
18450    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18451            final PackageSetting ps, final int userId) {
18452        if (ps.pkg == null) {
18453            return;
18454        }
18455
18456        // These are flags that can change base on user actions.
18457        final int userSettableMask = FLAG_PERMISSION_USER_SET
18458                | FLAG_PERMISSION_USER_FIXED
18459                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18460                | FLAG_PERMISSION_REVIEW_REQUIRED;
18461
18462        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18463                | FLAG_PERMISSION_POLICY_FIXED;
18464
18465        boolean writeInstallPermissions = false;
18466        boolean writeRuntimePermissions = false;
18467
18468        final int permissionCount = ps.pkg.requestedPermissions.size();
18469        for (int i = 0; i < permissionCount; i++) {
18470            String permission = ps.pkg.requestedPermissions.get(i);
18471
18472            BasePermission bp = mSettings.mPermissions.get(permission);
18473            if (bp == null) {
18474                continue;
18475            }
18476
18477            // If shared user we just reset the state to which only this app contributed.
18478            if (ps.sharedUser != null) {
18479                boolean used = false;
18480                final int packageCount = ps.sharedUser.packages.size();
18481                for (int j = 0; j < packageCount; j++) {
18482                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18483                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18484                            && pkg.pkg.requestedPermissions.contains(permission)) {
18485                        used = true;
18486                        break;
18487                    }
18488                }
18489                if (used) {
18490                    continue;
18491                }
18492            }
18493
18494            PermissionsState permissionsState = ps.getPermissionsState();
18495
18496            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18497
18498            // Always clear the user settable flags.
18499            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18500                    bp.name) != null;
18501            // If permission review is enabled and this is a legacy app, mark the
18502            // permission as requiring a review as this is the initial state.
18503            int flags = 0;
18504            if (mPermissionReviewRequired
18505                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18506                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18507            }
18508            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18509                if (hasInstallState) {
18510                    writeInstallPermissions = true;
18511                } else {
18512                    writeRuntimePermissions = true;
18513                }
18514            }
18515
18516            // Below is only runtime permission handling.
18517            if (!bp.isRuntime()) {
18518                continue;
18519            }
18520
18521            // Never clobber system or policy.
18522            if ((oldFlags & policyOrSystemFlags) != 0) {
18523                continue;
18524            }
18525
18526            // If this permission was granted by default, make sure it is.
18527            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18528                if (permissionsState.grantRuntimePermission(bp, userId)
18529                        != PERMISSION_OPERATION_FAILURE) {
18530                    writeRuntimePermissions = true;
18531                }
18532            // If permission review is enabled the permissions for a legacy apps
18533            // are represented as constantly granted runtime ones, so don't revoke.
18534            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18535                // Otherwise, reset the permission.
18536                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18537                switch (revokeResult) {
18538                    case PERMISSION_OPERATION_SUCCESS:
18539                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18540                        writeRuntimePermissions = true;
18541                        final int appId = ps.appId;
18542                        mHandler.post(new Runnable() {
18543                            @Override
18544                            public void run() {
18545                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18546                            }
18547                        });
18548                    } break;
18549                }
18550            }
18551        }
18552
18553        // Synchronously write as we are taking permissions away.
18554        if (writeRuntimePermissions) {
18555            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18556        }
18557
18558        // Synchronously write as we are taking permissions away.
18559        if (writeInstallPermissions) {
18560            mSettings.writeLPr();
18561        }
18562    }
18563
18564    /**
18565     * Remove entries from the keystore daemon. Will only remove it if the
18566     * {@code appId} is valid.
18567     */
18568    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18569        if (appId < 0) {
18570            return;
18571        }
18572
18573        final KeyStore keyStore = KeyStore.getInstance();
18574        if (keyStore != null) {
18575            if (userId == UserHandle.USER_ALL) {
18576                for (final int individual : sUserManager.getUserIds()) {
18577                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18578                }
18579            } else {
18580                keyStore.clearUid(UserHandle.getUid(userId, appId));
18581            }
18582        } else {
18583            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18584        }
18585    }
18586
18587    @Override
18588    public void deleteApplicationCacheFiles(final String packageName,
18589            final IPackageDataObserver observer) {
18590        final int userId = UserHandle.getCallingUserId();
18591        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18592    }
18593
18594    @Override
18595    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18596            final IPackageDataObserver observer) {
18597        mContext.enforceCallingOrSelfPermission(
18598                android.Manifest.permission.DELETE_CACHE_FILES, null);
18599        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18600                /* requireFullPermission= */ true, /* checkShell= */ false,
18601                "delete application cache files");
18602
18603        final PackageParser.Package pkg;
18604        synchronized (mPackages) {
18605            pkg = mPackages.get(packageName);
18606        }
18607
18608        // Queue up an async operation since the package deletion may take a little while.
18609        mHandler.post(new Runnable() {
18610            public void run() {
18611                synchronized (mInstallLock) {
18612                    final int flags = StorageManager.FLAG_STORAGE_DE
18613                            | StorageManager.FLAG_STORAGE_CE;
18614                    // We're only clearing cache files, so we don't care if the
18615                    // app is unfrozen and still able to run
18616                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18617                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18618                }
18619                clearExternalStorageDataSync(packageName, userId, false);
18620                if (observer != null) {
18621                    try {
18622                        observer.onRemoveCompleted(packageName, true);
18623                    } catch (RemoteException e) {
18624                        Log.i(TAG, "Observer no longer exists.");
18625                    }
18626                }
18627            }
18628        });
18629    }
18630
18631    @Override
18632    public void getPackageSizeInfo(final String packageName, int userHandle,
18633            final IPackageStatsObserver observer) {
18634        throw new UnsupportedOperationException(
18635                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18636    }
18637
18638    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18639        final PackageSetting ps;
18640        synchronized (mPackages) {
18641            ps = mSettings.mPackages.get(packageName);
18642            if (ps == null) {
18643                Slog.w(TAG, "Failed to find settings for " + packageName);
18644                return false;
18645            }
18646        }
18647
18648        final String[] packageNames = { packageName };
18649        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18650        final String[] codePaths = { ps.codePathString };
18651
18652        try {
18653            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18654                    ps.appId, ceDataInodes, codePaths, stats);
18655
18656            // For now, ignore code size of packages on system partition
18657            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18658                stats.codeSize = 0;
18659            }
18660
18661            // External clients expect these to be tracked separately
18662            stats.dataSize -= stats.cacheSize;
18663
18664        } catch (InstallerException e) {
18665            Slog.w(TAG, String.valueOf(e));
18666            return false;
18667        }
18668
18669        return true;
18670    }
18671
18672    private int getUidTargetSdkVersionLockedLPr(int uid) {
18673        Object obj = mSettings.getUserIdLPr(uid);
18674        if (obj instanceof SharedUserSetting) {
18675            final SharedUserSetting sus = (SharedUserSetting) obj;
18676            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18677            final Iterator<PackageSetting> it = sus.packages.iterator();
18678            while (it.hasNext()) {
18679                final PackageSetting ps = it.next();
18680                if (ps.pkg != null) {
18681                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18682                    if (v < vers) vers = v;
18683                }
18684            }
18685            return vers;
18686        } else if (obj instanceof PackageSetting) {
18687            final PackageSetting ps = (PackageSetting) obj;
18688            if (ps.pkg != null) {
18689                return ps.pkg.applicationInfo.targetSdkVersion;
18690            }
18691        }
18692        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18693    }
18694
18695    @Override
18696    public void addPreferredActivity(IntentFilter filter, int match,
18697            ComponentName[] set, ComponentName activity, int userId) {
18698        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18699                "Adding preferred");
18700    }
18701
18702    private void addPreferredActivityInternal(IntentFilter filter, int match,
18703            ComponentName[] set, ComponentName activity, boolean always, int userId,
18704            String opname) {
18705        // writer
18706        int callingUid = Binder.getCallingUid();
18707        enforceCrossUserPermission(callingUid, userId,
18708                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18709        if (filter.countActions() == 0) {
18710            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18711            return;
18712        }
18713        synchronized (mPackages) {
18714            if (mContext.checkCallingOrSelfPermission(
18715                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18716                    != PackageManager.PERMISSION_GRANTED) {
18717                if (getUidTargetSdkVersionLockedLPr(callingUid)
18718                        < Build.VERSION_CODES.FROYO) {
18719                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18720                            + callingUid);
18721                    return;
18722                }
18723                mContext.enforceCallingOrSelfPermission(
18724                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18725            }
18726
18727            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18728            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18729                    + userId + ":");
18730            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18731            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18732            scheduleWritePackageRestrictionsLocked(userId);
18733            postPreferredActivityChangedBroadcast(userId);
18734        }
18735    }
18736
18737    private void postPreferredActivityChangedBroadcast(int userId) {
18738        mHandler.post(() -> {
18739            final IActivityManager am = ActivityManager.getService();
18740            if (am == null) {
18741                return;
18742            }
18743
18744            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18745            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18746            try {
18747                am.broadcastIntent(null, intent, null, null,
18748                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18749                        null, false, false, userId);
18750            } catch (RemoteException e) {
18751            }
18752        });
18753    }
18754
18755    @Override
18756    public void replacePreferredActivity(IntentFilter filter, int match,
18757            ComponentName[] set, ComponentName activity, int userId) {
18758        if (filter.countActions() != 1) {
18759            throw new IllegalArgumentException(
18760                    "replacePreferredActivity expects filter to have only 1 action.");
18761        }
18762        if (filter.countDataAuthorities() != 0
18763                || filter.countDataPaths() != 0
18764                || filter.countDataSchemes() > 1
18765                || filter.countDataTypes() != 0) {
18766            throw new IllegalArgumentException(
18767                    "replacePreferredActivity expects filter to have no data authorities, " +
18768                    "paths, or types; and at most one scheme.");
18769        }
18770
18771        final int callingUid = Binder.getCallingUid();
18772        enforceCrossUserPermission(callingUid, userId,
18773                true /* requireFullPermission */, false /* checkShell */,
18774                "replace preferred activity");
18775        synchronized (mPackages) {
18776            if (mContext.checkCallingOrSelfPermission(
18777                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18778                    != PackageManager.PERMISSION_GRANTED) {
18779                if (getUidTargetSdkVersionLockedLPr(callingUid)
18780                        < Build.VERSION_CODES.FROYO) {
18781                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18782                            + Binder.getCallingUid());
18783                    return;
18784                }
18785                mContext.enforceCallingOrSelfPermission(
18786                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18787            }
18788
18789            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18790            if (pir != null) {
18791                // Get all of the existing entries that exactly match this filter.
18792                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18793                if (existing != null && existing.size() == 1) {
18794                    PreferredActivity cur = existing.get(0);
18795                    if (DEBUG_PREFERRED) {
18796                        Slog.i(TAG, "Checking replace of preferred:");
18797                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18798                        if (!cur.mPref.mAlways) {
18799                            Slog.i(TAG, "  -- CUR; not mAlways!");
18800                        } else {
18801                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18802                            Slog.i(TAG, "  -- CUR: mSet="
18803                                    + Arrays.toString(cur.mPref.mSetComponents));
18804                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18805                            Slog.i(TAG, "  -- NEW: mMatch="
18806                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18807                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18808                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18809                        }
18810                    }
18811                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18812                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18813                            && cur.mPref.sameSet(set)) {
18814                        // Setting the preferred activity to what it happens to be already
18815                        if (DEBUG_PREFERRED) {
18816                            Slog.i(TAG, "Replacing with same preferred activity "
18817                                    + cur.mPref.mShortComponent + " for user "
18818                                    + userId + ":");
18819                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18820                        }
18821                        return;
18822                    }
18823                }
18824
18825                if (existing != null) {
18826                    if (DEBUG_PREFERRED) {
18827                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18828                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18829                    }
18830                    for (int i = 0; i < existing.size(); i++) {
18831                        PreferredActivity pa = existing.get(i);
18832                        if (DEBUG_PREFERRED) {
18833                            Slog.i(TAG, "Removing existing preferred activity "
18834                                    + pa.mPref.mComponent + ":");
18835                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18836                        }
18837                        pir.removeFilter(pa);
18838                    }
18839                }
18840            }
18841            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18842                    "Replacing preferred");
18843        }
18844    }
18845
18846    @Override
18847    public void clearPackagePreferredActivities(String packageName) {
18848        final int uid = Binder.getCallingUid();
18849        // writer
18850        synchronized (mPackages) {
18851            PackageParser.Package pkg = mPackages.get(packageName);
18852            if (pkg == null || pkg.applicationInfo.uid != uid) {
18853                if (mContext.checkCallingOrSelfPermission(
18854                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18855                        != PackageManager.PERMISSION_GRANTED) {
18856                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18857                            < Build.VERSION_CODES.FROYO) {
18858                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18859                                + Binder.getCallingUid());
18860                        return;
18861                    }
18862                    mContext.enforceCallingOrSelfPermission(
18863                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18864                }
18865            }
18866
18867            int user = UserHandle.getCallingUserId();
18868            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18869                scheduleWritePackageRestrictionsLocked(user);
18870            }
18871        }
18872    }
18873
18874    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18875    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18876        ArrayList<PreferredActivity> removed = null;
18877        boolean changed = false;
18878        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18879            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18880            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18881            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18882                continue;
18883            }
18884            Iterator<PreferredActivity> it = pir.filterIterator();
18885            while (it.hasNext()) {
18886                PreferredActivity pa = it.next();
18887                // Mark entry for removal only if it matches the package name
18888                // and the entry is of type "always".
18889                if (packageName == null ||
18890                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18891                                && pa.mPref.mAlways)) {
18892                    if (removed == null) {
18893                        removed = new ArrayList<PreferredActivity>();
18894                    }
18895                    removed.add(pa);
18896                }
18897            }
18898            if (removed != null) {
18899                for (int j=0; j<removed.size(); j++) {
18900                    PreferredActivity pa = removed.get(j);
18901                    pir.removeFilter(pa);
18902                }
18903                changed = true;
18904            }
18905        }
18906        if (changed) {
18907            postPreferredActivityChangedBroadcast(userId);
18908        }
18909        return changed;
18910    }
18911
18912    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18913    private void clearIntentFilterVerificationsLPw(int userId) {
18914        final int packageCount = mPackages.size();
18915        for (int i = 0; i < packageCount; i++) {
18916            PackageParser.Package pkg = mPackages.valueAt(i);
18917            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18918        }
18919    }
18920
18921    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18922    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18923        if (userId == UserHandle.USER_ALL) {
18924            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18925                    sUserManager.getUserIds())) {
18926                for (int oneUserId : sUserManager.getUserIds()) {
18927                    scheduleWritePackageRestrictionsLocked(oneUserId);
18928                }
18929            }
18930        } else {
18931            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18932                scheduleWritePackageRestrictionsLocked(userId);
18933            }
18934        }
18935    }
18936
18937    void clearDefaultBrowserIfNeeded(String packageName) {
18938        for (int oneUserId : sUserManager.getUserIds()) {
18939            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18940            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18941            if (packageName.equals(defaultBrowserPackageName)) {
18942                setDefaultBrowserPackageName(null, oneUserId);
18943            }
18944        }
18945    }
18946
18947    @Override
18948    public void resetApplicationPreferences(int userId) {
18949        mContext.enforceCallingOrSelfPermission(
18950                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18951        final long identity = Binder.clearCallingIdentity();
18952        // writer
18953        try {
18954            synchronized (mPackages) {
18955                clearPackagePreferredActivitiesLPw(null, userId);
18956                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18957                // TODO: We have to reset the default SMS and Phone. This requires
18958                // significant refactoring to keep all default apps in the package
18959                // manager (cleaner but more work) or have the services provide
18960                // callbacks to the package manager to request a default app reset.
18961                applyFactoryDefaultBrowserLPw(userId);
18962                clearIntentFilterVerificationsLPw(userId);
18963                primeDomainVerificationsLPw(userId);
18964                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18965                scheduleWritePackageRestrictionsLocked(userId);
18966            }
18967            resetNetworkPolicies(userId);
18968        } finally {
18969            Binder.restoreCallingIdentity(identity);
18970        }
18971    }
18972
18973    @Override
18974    public int getPreferredActivities(List<IntentFilter> outFilters,
18975            List<ComponentName> outActivities, String packageName) {
18976
18977        int num = 0;
18978        final int userId = UserHandle.getCallingUserId();
18979        // reader
18980        synchronized (mPackages) {
18981            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18982            if (pir != null) {
18983                final Iterator<PreferredActivity> it = pir.filterIterator();
18984                while (it.hasNext()) {
18985                    final PreferredActivity pa = it.next();
18986                    if (packageName == null
18987                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18988                                    && pa.mPref.mAlways)) {
18989                        if (outFilters != null) {
18990                            outFilters.add(new IntentFilter(pa));
18991                        }
18992                        if (outActivities != null) {
18993                            outActivities.add(pa.mPref.mComponent);
18994                        }
18995                    }
18996                }
18997            }
18998        }
18999
19000        return num;
19001    }
19002
19003    @Override
19004    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19005            int userId) {
19006        int callingUid = Binder.getCallingUid();
19007        if (callingUid != Process.SYSTEM_UID) {
19008            throw new SecurityException(
19009                    "addPersistentPreferredActivity can only be run by the system");
19010        }
19011        if (filter.countActions() == 0) {
19012            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19013            return;
19014        }
19015        synchronized (mPackages) {
19016            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19017                    ":");
19018            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19019            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19020                    new PersistentPreferredActivity(filter, activity));
19021            scheduleWritePackageRestrictionsLocked(userId);
19022            postPreferredActivityChangedBroadcast(userId);
19023        }
19024    }
19025
19026    @Override
19027    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19028        int callingUid = Binder.getCallingUid();
19029        if (callingUid != Process.SYSTEM_UID) {
19030            throw new SecurityException(
19031                    "clearPackagePersistentPreferredActivities can only be run by the system");
19032        }
19033        ArrayList<PersistentPreferredActivity> removed = null;
19034        boolean changed = false;
19035        synchronized (mPackages) {
19036            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19037                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19038                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19039                        .valueAt(i);
19040                if (userId != thisUserId) {
19041                    continue;
19042                }
19043                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19044                while (it.hasNext()) {
19045                    PersistentPreferredActivity ppa = it.next();
19046                    // Mark entry for removal only if it matches the package name.
19047                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19048                        if (removed == null) {
19049                            removed = new ArrayList<PersistentPreferredActivity>();
19050                        }
19051                        removed.add(ppa);
19052                    }
19053                }
19054                if (removed != null) {
19055                    for (int j=0; j<removed.size(); j++) {
19056                        PersistentPreferredActivity ppa = removed.get(j);
19057                        ppir.removeFilter(ppa);
19058                    }
19059                    changed = true;
19060                }
19061            }
19062
19063            if (changed) {
19064                scheduleWritePackageRestrictionsLocked(userId);
19065                postPreferredActivityChangedBroadcast(userId);
19066            }
19067        }
19068    }
19069
19070    /**
19071     * Common machinery for picking apart a restored XML blob and passing
19072     * it to a caller-supplied functor to be applied to the running system.
19073     */
19074    private void restoreFromXml(XmlPullParser parser, int userId,
19075            String expectedStartTag, BlobXmlRestorer functor)
19076            throws IOException, XmlPullParserException {
19077        int type;
19078        while ((type = parser.next()) != XmlPullParser.START_TAG
19079                && type != XmlPullParser.END_DOCUMENT) {
19080        }
19081        if (type != XmlPullParser.START_TAG) {
19082            // oops didn't find a start tag?!
19083            if (DEBUG_BACKUP) {
19084                Slog.e(TAG, "Didn't find start tag during restore");
19085            }
19086            return;
19087        }
19088Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19089        // this is supposed to be TAG_PREFERRED_BACKUP
19090        if (!expectedStartTag.equals(parser.getName())) {
19091            if (DEBUG_BACKUP) {
19092                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19093            }
19094            return;
19095        }
19096
19097        // skip interfering stuff, then we're aligned with the backing implementation
19098        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19099Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19100        functor.apply(parser, userId);
19101    }
19102
19103    private interface BlobXmlRestorer {
19104        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19105    }
19106
19107    /**
19108     * Non-Binder method, support for the backup/restore mechanism: write the
19109     * full set of preferred activities in its canonical XML format.  Returns the
19110     * XML output as a byte array, or null if there is none.
19111     */
19112    @Override
19113    public byte[] getPreferredActivityBackup(int userId) {
19114        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19115            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19116        }
19117
19118        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19119        try {
19120            final XmlSerializer serializer = new FastXmlSerializer();
19121            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19122            serializer.startDocument(null, true);
19123            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19124
19125            synchronized (mPackages) {
19126                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19127            }
19128
19129            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19130            serializer.endDocument();
19131            serializer.flush();
19132        } catch (Exception e) {
19133            if (DEBUG_BACKUP) {
19134                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19135            }
19136            return null;
19137        }
19138
19139        return dataStream.toByteArray();
19140    }
19141
19142    @Override
19143    public void restorePreferredActivities(byte[] backup, int userId) {
19144        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19145            throw new SecurityException("Only the system may call restorePreferredActivities()");
19146        }
19147
19148        try {
19149            final XmlPullParser parser = Xml.newPullParser();
19150            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19151            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19152                    new BlobXmlRestorer() {
19153                        @Override
19154                        public void apply(XmlPullParser parser, int userId)
19155                                throws XmlPullParserException, IOException {
19156                            synchronized (mPackages) {
19157                                mSettings.readPreferredActivitiesLPw(parser, userId);
19158                            }
19159                        }
19160                    } );
19161        } catch (Exception e) {
19162            if (DEBUG_BACKUP) {
19163                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19164            }
19165        }
19166    }
19167
19168    /**
19169     * Non-Binder method, support for the backup/restore mechanism: write the
19170     * default browser (etc) settings in its canonical XML format.  Returns the default
19171     * browser XML representation as a byte array, or null if there is none.
19172     */
19173    @Override
19174    public byte[] getDefaultAppsBackup(int userId) {
19175        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19176            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19177        }
19178
19179        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19180        try {
19181            final XmlSerializer serializer = new FastXmlSerializer();
19182            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19183            serializer.startDocument(null, true);
19184            serializer.startTag(null, TAG_DEFAULT_APPS);
19185
19186            synchronized (mPackages) {
19187                mSettings.writeDefaultAppsLPr(serializer, userId);
19188            }
19189
19190            serializer.endTag(null, TAG_DEFAULT_APPS);
19191            serializer.endDocument();
19192            serializer.flush();
19193        } catch (Exception e) {
19194            if (DEBUG_BACKUP) {
19195                Slog.e(TAG, "Unable to write default apps for backup", e);
19196            }
19197            return null;
19198        }
19199
19200        return dataStream.toByteArray();
19201    }
19202
19203    @Override
19204    public void restoreDefaultApps(byte[] backup, int userId) {
19205        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19206            throw new SecurityException("Only the system may call restoreDefaultApps()");
19207        }
19208
19209        try {
19210            final XmlPullParser parser = Xml.newPullParser();
19211            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19212            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19213                    new BlobXmlRestorer() {
19214                        @Override
19215                        public void apply(XmlPullParser parser, int userId)
19216                                throws XmlPullParserException, IOException {
19217                            synchronized (mPackages) {
19218                                mSettings.readDefaultAppsLPw(parser, userId);
19219                            }
19220                        }
19221                    } );
19222        } catch (Exception e) {
19223            if (DEBUG_BACKUP) {
19224                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19225            }
19226        }
19227    }
19228
19229    @Override
19230    public byte[] getIntentFilterVerificationBackup(int userId) {
19231        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19232            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19233        }
19234
19235        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19236        try {
19237            final XmlSerializer serializer = new FastXmlSerializer();
19238            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19239            serializer.startDocument(null, true);
19240            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19241
19242            synchronized (mPackages) {
19243                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19244            }
19245
19246            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19247            serializer.endDocument();
19248            serializer.flush();
19249        } catch (Exception e) {
19250            if (DEBUG_BACKUP) {
19251                Slog.e(TAG, "Unable to write default apps for backup", e);
19252            }
19253            return null;
19254        }
19255
19256        return dataStream.toByteArray();
19257    }
19258
19259    @Override
19260    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19261        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19262            throw new SecurityException("Only the system may call restorePreferredActivities()");
19263        }
19264
19265        try {
19266            final XmlPullParser parser = Xml.newPullParser();
19267            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19268            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19269                    new BlobXmlRestorer() {
19270                        @Override
19271                        public void apply(XmlPullParser parser, int userId)
19272                                throws XmlPullParserException, IOException {
19273                            synchronized (mPackages) {
19274                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19275                                mSettings.writeLPr();
19276                            }
19277                        }
19278                    } );
19279        } catch (Exception e) {
19280            if (DEBUG_BACKUP) {
19281                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19282            }
19283        }
19284    }
19285
19286    @Override
19287    public byte[] getPermissionGrantBackup(int userId) {
19288        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19289            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19290        }
19291
19292        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19293        try {
19294            final XmlSerializer serializer = new FastXmlSerializer();
19295            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19296            serializer.startDocument(null, true);
19297            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19298
19299            synchronized (mPackages) {
19300                serializeRuntimePermissionGrantsLPr(serializer, userId);
19301            }
19302
19303            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19304            serializer.endDocument();
19305            serializer.flush();
19306        } catch (Exception e) {
19307            if (DEBUG_BACKUP) {
19308                Slog.e(TAG, "Unable to write default apps for backup", e);
19309            }
19310            return null;
19311        }
19312
19313        return dataStream.toByteArray();
19314    }
19315
19316    @Override
19317    public void restorePermissionGrants(byte[] backup, int userId) {
19318        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19319            throw new SecurityException("Only the system may call restorePermissionGrants()");
19320        }
19321
19322        try {
19323            final XmlPullParser parser = Xml.newPullParser();
19324            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19325            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19326                    new BlobXmlRestorer() {
19327                        @Override
19328                        public void apply(XmlPullParser parser, int userId)
19329                                throws XmlPullParserException, IOException {
19330                            synchronized (mPackages) {
19331                                processRestoredPermissionGrantsLPr(parser, userId);
19332                            }
19333                        }
19334                    } );
19335        } catch (Exception e) {
19336            if (DEBUG_BACKUP) {
19337                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19338            }
19339        }
19340    }
19341
19342    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19343            throws IOException {
19344        serializer.startTag(null, TAG_ALL_GRANTS);
19345
19346        final int N = mSettings.mPackages.size();
19347        for (int i = 0; i < N; i++) {
19348            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19349            boolean pkgGrantsKnown = false;
19350
19351            PermissionsState packagePerms = ps.getPermissionsState();
19352
19353            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19354                final int grantFlags = state.getFlags();
19355                // only look at grants that are not system/policy fixed
19356                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19357                    final boolean isGranted = state.isGranted();
19358                    // And only back up the user-twiddled state bits
19359                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19360                        final String packageName = mSettings.mPackages.keyAt(i);
19361                        if (!pkgGrantsKnown) {
19362                            serializer.startTag(null, TAG_GRANT);
19363                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19364                            pkgGrantsKnown = true;
19365                        }
19366
19367                        final boolean userSet =
19368                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19369                        final boolean userFixed =
19370                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19371                        final boolean revoke =
19372                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19373
19374                        serializer.startTag(null, TAG_PERMISSION);
19375                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19376                        if (isGranted) {
19377                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19378                        }
19379                        if (userSet) {
19380                            serializer.attribute(null, ATTR_USER_SET, "true");
19381                        }
19382                        if (userFixed) {
19383                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19384                        }
19385                        if (revoke) {
19386                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19387                        }
19388                        serializer.endTag(null, TAG_PERMISSION);
19389                    }
19390                }
19391            }
19392
19393            if (pkgGrantsKnown) {
19394                serializer.endTag(null, TAG_GRANT);
19395            }
19396        }
19397
19398        serializer.endTag(null, TAG_ALL_GRANTS);
19399    }
19400
19401    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19402            throws XmlPullParserException, IOException {
19403        String pkgName = null;
19404        int outerDepth = parser.getDepth();
19405        int type;
19406        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19407                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19408            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19409                continue;
19410            }
19411
19412            final String tagName = parser.getName();
19413            if (tagName.equals(TAG_GRANT)) {
19414                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19415                if (DEBUG_BACKUP) {
19416                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19417                }
19418            } else if (tagName.equals(TAG_PERMISSION)) {
19419
19420                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19421                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19422
19423                int newFlagSet = 0;
19424                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19425                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19426                }
19427                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19428                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19429                }
19430                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19431                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19432                }
19433                if (DEBUG_BACKUP) {
19434                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19435                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19436                }
19437                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19438                if (ps != null) {
19439                    // Already installed so we apply the grant immediately
19440                    if (DEBUG_BACKUP) {
19441                        Slog.v(TAG, "        + already installed; applying");
19442                    }
19443                    PermissionsState perms = ps.getPermissionsState();
19444                    BasePermission bp = mSettings.mPermissions.get(permName);
19445                    if (bp != null) {
19446                        if (isGranted) {
19447                            perms.grantRuntimePermission(bp, userId);
19448                        }
19449                        if (newFlagSet != 0) {
19450                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19451                        }
19452                    }
19453                } else {
19454                    // Need to wait for post-restore install to apply the grant
19455                    if (DEBUG_BACKUP) {
19456                        Slog.v(TAG, "        - not yet installed; saving for later");
19457                    }
19458                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19459                            isGranted, newFlagSet, userId);
19460                }
19461            } else {
19462                PackageManagerService.reportSettingsProblem(Log.WARN,
19463                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19464                XmlUtils.skipCurrentTag(parser);
19465            }
19466        }
19467
19468        scheduleWriteSettingsLocked();
19469        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19470    }
19471
19472    @Override
19473    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19474            int sourceUserId, int targetUserId, int flags) {
19475        mContext.enforceCallingOrSelfPermission(
19476                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19477        int callingUid = Binder.getCallingUid();
19478        enforceOwnerRights(ownerPackage, callingUid);
19479        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19480        if (intentFilter.countActions() == 0) {
19481            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19482            return;
19483        }
19484        synchronized (mPackages) {
19485            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19486                    ownerPackage, targetUserId, flags);
19487            CrossProfileIntentResolver resolver =
19488                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19489            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19490            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19491            if (existing != null) {
19492                int size = existing.size();
19493                for (int i = 0; i < size; i++) {
19494                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19495                        return;
19496                    }
19497                }
19498            }
19499            resolver.addFilter(newFilter);
19500            scheduleWritePackageRestrictionsLocked(sourceUserId);
19501        }
19502    }
19503
19504    @Override
19505    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19506        mContext.enforceCallingOrSelfPermission(
19507                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19508        int callingUid = Binder.getCallingUid();
19509        enforceOwnerRights(ownerPackage, callingUid);
19510        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19511        synchronized (mPackages) {
19512            CrossProfileIntentResolver resolver =
19513                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19514            ArraySet<CrossProfileIntentFilter> set =
19515                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19516            for (CrossProfileIntentFilter filter : set) {
19517                if (filter.getOwnerPackage().equals(ownerPackage)) {
19518                    resolver.removeFilter(filter);
19519                }
19520            }
19521            scheduleWritePackageRestrictionsLocked(sourceUserId);
19522        }
19523    }
19524
19525    // Enforcing that callingUid is owning pkg on userId
19526    private void enforceOwnerRights(String pkg, int callingUid) {
19527        // The system owns everything.
19528        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19529            return;
19530        }
19531        int callingUserId = UserHandle.getUserId(callingUid);
19532        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19533        if (pi == null) {
19534            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19535                    + callingUserId);
19536        }
19537        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19538            throw new SecurityException("Calling uid " + callingUid
19539                    + " does not own package " + pkg);
19540        }
19541    }
19542
19543    @Override
19544    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19545        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19546    }
19547
19548    /**
19549     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19550     * then reports the most likely home activity or null if there are more than one.
19551     */
19552    public ComponentName getDefaultHomeActivity(int userId) {
19553        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19554        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19555        if (cn != null) {
19556            return cn;
19557        }
19558
19559        // Find the launcher with the highest priority and return that component if there are no
19560        // other home activity with the same priority.
19561        int lastPriority = Integer.MIN_VALUE;
19562        ComponentName lastComponent = null;
19563        final int size = allHomeCandidates.size();
19564        for (int i = 0; i < size; i++) {
19565            final ResolveInfo ri = allHomeCandidates.get(i);
19566            if (ri.priority > lastPriority) {
19567                lastComponent = ri.activityInfo.getComponentName();
19568                lastPriority = ri.priority;
19569            } else if (ri.priority == lastPriority) {
19570                // Two components found with same priority.
19571                lastComponent = null;
19572            }
19573        }
19574        return lastComponent;
19575    }
19576
19577    private Intent getHomeIntent() {
19578        Intent intent = new Intent(Intent.ACTION_MAIN);
19579        intent.addCategory(Intent.CATEGORY_HOME);
19580        intent.addCategory(Intent.CATEGORY_DEFAULT);
19581        return intent;
19582    }
19583
19584    private IntentFilter getHomeFilter() {
19585        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19586        filter.addCategory(Intent.CATEGORY_HOME);
19587        filter.addCategory(Intent.CATEGORY_DEFAULT);
19588        return filter;
19589    }
19590
19591    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19592            int userId) {
19593        Intent intent  = getHomeIntent();
19594        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19595                PackageManager.GET_META_DATA, userId);
19596        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19597                true, false, false, userId);
19598
19599        allHomeCandidates.clear();
19600        if (list != null) {
19601            for (ResolveInfo ri : list) {
19602                allHomeCandidates.add(ri);
19603            }
19604        }
19605        return (preferred == null || preferred.activityInfo == null)
19606                ? null
19607                : new ComponentName(preferred.activityInfo.packageName,
19608                        preferred.activityInfo.name);
19609    }
19610
19611    @Override
19612    public void setHomeActivity(ComponentName comp, int userId) {
19613        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19614        getHomeActivitiesAsUser(homeActivities, userId);
19615
19616        boolean found = false;
19617
19618        final int size = homeActivities.size();
19619        final ComponentName[] set = new ComponentName[size];
19620        for (int i = 0; i < size; i++) {
19621            final ResolveInfo candidate = homeActivities.get(i);
19622            final ActivityInfo info = candidate.activityInfo;
19623            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19624            set[i] = activityName;
19625            if (!found && activityName.equals(comp)) {
19626                found = true;
19627            }
19628        }
19629        if (!found) {
19630            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19631                    + userId);
19632        }
19633        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19634                set, comp, userId);
19635    }
19636
19637    private @Nullable String getSetupWizardPackageName() {
19638        final Intent intent = new Intent(Intent.ACTION_MAIN);
19639        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19640
19641        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19642                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19643                        | MATCH_DISABLED_COMPONENTS,
19644                UserHandle.myUserId());
19645        if (matches.size() == 1) {
19646            return matches.get(0).getComponentInfo().packageName;
19647        } else {
19648            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19649                    + ": matches=" + matches);
19650            return null;
19651        }
19652    }
19653
19654    private @Nullable String getStorageManagerPackageName() {
19655        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19656
19657        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19658                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19659                        | MATCH_DISABLED_COMPONENTS,
19660                UserHandle.myUserId());
19661        if (matches.size() == 1) {
19662            return matches.get(0).getComponentInfo().packageName;
19663        } else {
19664            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19665                    + matches.size() + ": matches=" + matches);
19666            return null;
19667        }
19668    }
19669
19670    @Override
19671    public void setApplicationEnabledSetting(String appPackageName,
19672            int newState, int flags, int userId, String callingPackage) {
19673        if (!sUserManager.exists(userId)) return;
19674        if (callingPackage == null) {
19675            callingPackage = Integer.toString(Binder.getCallingUid());
19676        }
19677        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19678    }
19679
19680    @Override
19681    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19682        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19683        synchronized (mPackages) {
19684            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19685            if (pkgSetting != null) {
19686                pkgSetting.setUpdateAvailable(updateAvailable);
19687            }
19688        }
19689    }
19690
19691    @Override
19692    public void setComponentEnabledSetting(ComponentName componentName,
19693            int newState, int flags, int userId) {
19694        if (!sUserManager.exists(userId)) return;
19695        setEnabledSetting(componentName.getPackageName(),
19696                componentName.getClassName(), newState, flags, userId, null);
19697    }
19698
19699    private void setEnabledSetting(final String packageName, String className, int newState,
19700            final int flags, int userId, String callingPackage) {
19701        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19702              || newState == COMPONENT_ENABLED_STATE_ENABLED
19703              || newState == COMPONENT_ENABLED_STATE_DISABLED
19704              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19705              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19706            throw new IllegalArgumentException("Invalid new component state: "
19707                    + newState);
19708        }
19709        PackageSetting pkgSetting;
19710        final int uid = Binder.getCallingUid();
19711        final int permission;
19712        if (uid == Process.SYSTEM_UID) {
19713            permission = PackageManager.PERMISSION_GRANTED;
19714        } else {
19715            permission = mContext.checkCallingOrSelfPermission(
19716                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19717        }
19718        enforceCrossUserPermission(uid, userId,
19719                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19720        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19721        boolean sendNow = false;
19722        boolean isApp = (className == null);
19723        String componentName = isApp ? packageName : className;
19724        int packageUid = -1;
19725        ArrayList<String> components;
19726
19727        // writer
19728        synchronized (mPackages) {
19729            pkgSetting = mSettings.mPackages.get(packageName);
19730            if (pkgSetting == null) {
19731                if (className == null) {
19732                    throw new IllegalArgumentException("Unknown package: " + packageName);
19733                }
19734                throw new IllegalArgumentException(
19735                        "Unknown component: " + packageName + "/" + className);
19736            }
19737        }
19738
19739        // Limit who can change which apps
19740        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19741            // Don't allow apps that don't have permission to modify other apps
19742            if (!allowedByPermission) {
19743                throw new SecurityException(
19744                        "Permission Denial: attempt to change component state from pid="
19745                        + Binder.getCallingPid()
19746                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19747            }
19748            // Don't allow changing protected packages.
19749            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19750                throw new SecurityException("Cannot disable a protected package: " + packageName);
19751            }
19752        }
19753
19754        synchronized (mPackages) {
19755            if (uid == Process.SHELL_UID
19756                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19757                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19758                // unless it is a test package.
19759                int oldState = pkgSetting.getEnabled(userId);
19760                if (className == null
19761                    &&
19762                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19763                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19764                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19765                    &&
19766                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19767                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19768                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19769                    // ok
19770                } else {
19771                    throw new SecurityException(
19772                            "Shell cannot change component state for " + packageName + "/"
19773                            + className + " to " + newState);
19774                }
19775            }
19776            if (className == null) {
19777                // We're dealing with an application/package level state change
19778                if (pkgSetting.getEnabled(userId) == newState) {
19779                    // Nothing to do
19780                    return;
19781                }
19782                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19783                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19784                    // Don't care about who enables an app.
19785                    callingPackage = null;
19786                }
19787                pkgSetting.setEnabled(newState, userId, callingPackage);
19788                // pkgSetting.pkg.mSetEnabled = newState;
19789            } else {
19790                // We're dealing with a component level state change
19791                // First, verify that this is a valid class name.
19792                PackageParser.Package pkg = pkgSetting.pkg;
19793                if (pkg == null || !pkg.hasComponentClassName(className)) {
19794                    if (pkg != null &&
19795                            pkg.applicationInfo.targetSdkVersion >=
19796                                    Build.VERSION_CODES.JELLY_BEAN) {
19797                        throw new IllegalArgumentException("Component class " + className
19798                                + " does not exist in " + packageName);
19799                    } else {
19800                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19801                                + className + " does not exist in " + packageName);
19802                    }
19803                }
19804                switch (newState) {
19805                case COMPONENT_ENABLED_STATE_ENABLED:
19806                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19807                        return;
19808                    }
19809                    break;
19810                case COMPONENT_ENABLED_STATE_DISABLED:
19811                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19812                        return;
19813                    }
19814                    break;
19815                case COMPONENT_ENABLED_STATE_DEFAULT:
19816                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19817                        return;
19818                    }
19819                    break;
19820                default:
19821                    Slog.e(TAG, "Invalid new component state: " + newState);
19822                    return;
19823                }
19824            }
19825            scheduleWritePackageRestrictionsLocked(userId);
19826            updateSequenceNumberLP(packageName, new int[] { userId });
19827            final long callingId = Binder.clearCallingIdentity();
19828            try {
19829                updateInstantAppInstallerLocked();
19830            } finally {
19831                Binder.restoreCallingIdentity(callingId);
19832            }
19833            components = mPendingBroadcasts.get(userId, packageName);
19834            final boolean newPackage = components == null;
19835            if (newPackage) {
19836                components = new ArrayList<String>();
19837            }
19838            if (!components.contains(componentName)) {
19839                components.add(componentName);
19840            }
19841            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19842                sendNow = true;
19843                // Purge entry from pending broadcast list if another one exists already
19844                // since we are sending one right away.
19845                mPendingBroadcasts.remove(userId, packageName);
19846            } else {
19847                if (newPackage) {
19848                    mPendingBroadcasts.put(userId, packageName, components);
19849                }
19850                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19851                    // Schedule a message
19852                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19853                }
19854            }
19855        }
19856
19857        long callingId = Binder.clearCallingIdentity();
19858        try {
19859            if (sendNow) {
19860                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19861                sendPackageChangedBroadcast(packageName,
19862                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19863            }
19864        } finally {
19865            Binder.restoreCallingIdentity(callingId);
19866        }
19867    }
19868
19869    @Override
19870    public void flushPackageRestrictionsAsUser(int userId) {
19871        if (!sUserManager.exists(userId)) {
19872            return;
19873        }
19874        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19875                false /* checkShell */, "flushPackageRestrictions");
19876        synchronized (mPackages) {
19877            mSettings.writePackageRestrictionsLPr(userId);
19878            mDirtyUsers.remove(userId);
19879            if (mDirtyUsers.isEmpty()) {
19880                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19881            }
19882        }
19883    }
19884
19885    private void sendPackageChangedBroadcast(String packageName,
19886            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19887        if (DEBUG_INSTALL)
19888            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19889                    + componentNames);
19890        Bundle extras = new Bundle(4);
19891        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19892        String nameList[] = new String[componentNames.size()];
19893        componentNames.toArray(nameList);
19894        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19895        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19896        extras.putInt(Intent.EXTRA_UID, packageUid);
19897        // If this is not reporting a change of the overall package, then only send it
19898        // to registered receivers.  We don't want to launch a swath of apps for every
19899        // little component state change.
19900        final int flags = !componentNames.contains(packageName)
19901                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19902        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19903                new int[] {UserHandle.getUserId(packageUid)});
19904    }
19905
19906    @Override
19907    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19908        if (!sUserManager.exists(userId)) return;
19909        final int uid = Binder.getCallingUid();
19910        final int permission = mContext.checkCallingOrSelfPermission(
19911                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19912        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19913        enforceCrossUserPermission(uid, userId,
19914                true /* requireFullPermission */, true /* checkShell */, "stop package");
19915        // writer
19916        synchronized (mPackages) {
19917            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19918                    allowedByPermission, uid, userId)) {
19919                scheduleWritePackageRestrictionsLocked(userId);
19920            }
19921        }
19922    }
19923
19924    @Override
19925    public String getInstallerPackageName(String packageName) {
19926        // reader
19927        synchronized (mPackages) {
19928            return mSettings.getInstallerPackageNameLPr(packageName);
19929        }
19930    }
19931
19932    public boolean isOrphaned(String packageName) {
19933        // reader
19934        synchronized (mPackages) {
19935            return mSettings.isOrphaned(packageName);
19936        }
19937    }
19938
19939    @Override
19940    public int getApplicationEnabledSetting(String packageName, int userId) {
19941        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19942        int uid = Binder.getCallingUid();
19943        enforceCrossUserPermission(uid, userId,
19944                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19945        // reader
19946        synchronized (mPackages) {
19947            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19948        }
19949    }
19950
19951    @Override
19952    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19953        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19954        int uid = Binder.getCallingUid();
19955        enforceCrossUserPermission(uid, userId,
19956                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19957        // reader
19958        synchronized (mPackages) {
19959            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19960        }
19961    }
19962
19963    @Override
19964    public void enterSafeMode() {
19965        enforceSystemOrRoot("Only the system can request entering safe mode");
19966
19967        if (!mSystemReady) {
19968            mSafeMode = true;
19969        }
19970    }
19971
19972    @Override
19973    public void systemReady() {
19974        mSystemReady = true;
19975
19976        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19977        // disabled after already being started.
19978        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19979                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19980
19981        // Read the compatibilty setting when the system is ready.
19982        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19983                mContext.getContentResolver(),
19984                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19985        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19986        if (DEBUG_SETTINGS) {
19987            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19988        }
19989
19990        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19991
19992        synchronized (mPackages) {
19993            // Verify that all of the preferred activity components actually
19994            // exist.  It is possible for applications to be updated and at
19995            // that point remove a previously declared activity component that
19996            // had been set as a preferred activity.  We try to clean this up
19997            // the next time we encounter that preferred activity, but it is
19998            // possible for the user flow to never be able to return to that
19999            // situation so here we do a sanity check to make sure we haven't
20000            // left any junk around.
20001            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20002            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20003                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20004                removed.clear();
20005                for (PreferredActivity pa : pir.filterSet()) {
20006                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20007                        removed.add(pa);
20008                    }
20009                }
20010                if (removed.size() > 0) {
20011                    for (int r=0; r<removed.size(); r++) {
20012                        PreferredActivity pa = removed.get(r);
20013                        Slog.w(TAG, "Removing dangling preferred activity: "
20014                                + pa.mPref.mComponent);
20015                        pir.removeFilter(pa);
20016                    }
20017                    mSettings.writePackageRestrictionsLPr(
20018                            mSettings.mPreferredActivities.keyAt(i));
20019                }
20020            }
20021
20022            for (int userId : UserManagerService.getInstance().getUserIds()) {
20023                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20024                    grantPermissionsUserIds = ArrayUtils.appendInt(
20025                            grantPermissionsUserIds, userId);
20026                }
20027            }
20028        }
20029        sUserManager.systemReady();
20030
20031        // If we upgraded grant all default permissions before kicking off.
20032        for (int userId : grantPermissionsUserIds) {
20033            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20034        }
20035
20036        // If we did not grant default permissions, we preload from this the
20037        // default permission exceptions lazily to ensure we don't hit the
20038        // disk on a new user creation.
20039        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20040            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20041        }
20042
20043        // Kick off any messages waiting for system ready
20044        if (mPostSystemReadyMessages != null) {
20045            for (Message msg : mPostSystemReadyMessages) {
20046                msg.sendToTarget();
20047            }
20048            mPostSystemReadyMessages = null;
20049        }
20050
20051        // Watch for external volumes that come and go over time
20052        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20053        storage.registerListener(mStorageListener);
20054
20055        mInstallerService.systemReady();
20056        mPackageDexOptimizer.systemReady();
20057
20058        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20059                StorageManagerInternal.class);
20060        StorageManagerInternal.addExternalStoragePolicy(
20061                new StorageManagerInternal.ExternalStorageMountPolicy() {
20062            @Override
20063            public int getMountMode(int uid, String packageName) {
20064                if (Process.isIsolated(uid)) {
20065                    return Zygote.MOUNT_EXTERNAL_NONE;
20066                }
20067                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20068                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20069                }
20070                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20071                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20072                }
20073                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20074                    return Zygote.MOUNT_EXTERNAL_READ;
20075                }
20076                return Zygote.MOUNT_EXTERNAL_WRITE;
20077            }
20078
20079            @Override
20080            public boolean hasExternalStorage(int uid, String packageName) {
20081                return true;
20082            }
20083        });
20084
20085        // Now that we're mostly running, clean up stale users and apps
20086        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20087        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20088
20089        if (mPrivappPermissionsViolations != null) {
20090            Slog.wtf(TAG,"Signature|privileged permissions not in "
20091                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20092            mPrivappPermissionsViolations = null;
20093        }
20094    }
20095
20096    public void waitForAppDataPrepared() {
20097        if (mPrepareAppDataFuture == null) {
20098            return;
20099        }
20100        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20101        mPrepareAppDataFuture = null;
20102    }
20103
20104    @Override
20105    public boolean isSafeMode() {
20106        return mSafeMode;
20107    }
20108
20109    @Override
20110    public boolean hasSystemUidErrors() {
20111        return mHasSystemUidErrors;
20112    }
20113
20114    static String arrayToString(int[] array) {
20115        StringBuffer buf = new StringBuffer(128);
20116        buf.append('[');
20117        if (array != null) {
20118            for (int i=0; i<array.length; i++) {
20119                if (i > 0) buf.append(", ");
20120                buf.append(array[i]);
20121            }
20122        }
20123        buf.append(']');
20124        return buf.toString();
20125    }
20126
20127    static class DumpState {
20128        public static final int DUMP_LIBS = 1 << 0;
20129        public static final int DUMP_FEATURES = 1 << 1;
20130        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20131        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20132        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20133        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20134        public static final int DUMP_PERMISSIONS = 1 << 6;
20135        public static final int DUMP_PACKAGES = 1 << 7;
20136        public static final int DUMP_SHARED_USERS = 1 << 8;
20137        public static final int DUMP_MESSAGES = 1 << 9;
20138        public static final int DUMP_PROVIDERS = 1 << 10;
20139        public static final int DUMP_VERIFIERS = 1 << 11;
20140        public static final int DUMP_PREFERRED = 1 << 12;
20141        public static final int DUMP_PREFERRED_XML = 1 << 13;
20142        public static final int DUMP_KEYSETS = 1 << 14;
20143        public static final int DUMP_VERSION = 1 << 15;
20144        public static final int DUMP_INSTALLS = 1 << 16;
20145        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20146        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20147        public static final int DUMP_FROZEN = 1 << 19;
20148        public static final int DUMP_DEXOPT = 1 << 20;
20149        public static final int DUMP_COMPILER_STATS = 1 << 21;
20150        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20151
20152        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20153
20154        private int mTypes;
20155
20156        private int mOptions;
20157
20158        private boolean mTitlePrinted;
20159
20160        private SharedUserSetting mSharedUser;
20161
20162        public boolean isDumping(int type) {
20163            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20164                return true;
20165            }
20166
20167            return (mTypes & type) != 0;
20168        }
20169
20170        public void setDump(int type) {
20171            mTypes |= type;
20172        }
20173
20174        public boolean isOptionEnabled(int option) {
20175            return (mOptions & option) != 0;
20176        }
20177
20178        public void setOptionEnabled(int option) {
20179            mOptions |= option;
20180        }
20181
20182        public boolean onTitlePrinted() {
20183            final boolean printed = mTitlePrinted;
20184            mTitlePrinted = true;
20185            return printed;
20186        }
20187
20188        public boolean getTitlePrinted() {
20189            return mTitlePrinted;
20190        }
20191
20192        public void setTitlePrinted(boolean enabled) {
20193            mTitlePrinted = enabled;
20194        }
20195
20196        public SharedUserSetting getSharedUser() {
20197            return mSharedUser;
20198        }
20199
20200        public void setSharedUser(SharedUserSetting user) {
20201            mSharedUser = user;
20202        }
20203    }
20204
20205    @Override
20206    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20207            FileDescriptor err, String[] args, ShellCallback callback,
20208            ResultReceiver resultReceiver) {
20209        (new PackageManagerShellCommand(this)).exec(
20210                this, in, out, err, args, callback, resultReceiver);
20211    }
20212
20213    @Override
20214    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20215        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20216                != PackageManager.PERMISSION_GRANTED) {
20217            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20218                    + Binder.getCallingPid()
20219                    + ", uid=" + Binder.getCallingUid()
20220                    + " without permission "
20221                    + android.Manifest.permission.DUMP);
20222            return;
20223        }
20224
20225        DumpState dumpState = new DumpState();
20226        boolean fullPreferred = false;
20227        boolean checkin = false;
20228
20229        String packageName = null;
20230        ArraySet<String> permissionNames = null;
20231
20232        int opti = 0;
20233        while (opti < args.length) {
20234            String opt = args[opti];
20235            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20236                break;
20237            }
20238            opti++;
20239
20240            if ("-a".equals(opt)) {
20241                // Right now we only know how to print all.
20242            } else if ("-h".equals(opt)) {
20243                pw.println("Package manager dump options:");
20244                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20245                pw.println("    --checkin: dump for a checkin");
20246                pw.println("    -f: print details of intent filters");
20247                pw.println("    -h: print this help");
20248                pw.println("  cmd may be one of:");
20249                pw.println("    l[ibraries]: list known shared libraries");
20250                pw.println("    f[eatures]: list device features");
20251                pw.println("    k[eysets]: print known keysets");
20252                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20253                pw.println("    perm[issions]: dump permissions");
20254                pw.println("    permission [name ...]: dump declaration and use of given permission");
20255                pw.println("    pref[erred]: print preferred package settings");
20256                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20257                pw.println("    prov[iders]: dump content providers");
20258                pw.println("    p[ackages]: dump installed packages");
20259                pw.println("    s[hared-users]: dump shared user IDs");
20260                pw.println("    m[essages]: print collected runtime messages");
20261                pw.println("    v[erifiers]: print package verifier info");
20262                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20263                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20264                pw.println("    version: print database version info");
20265                pw.println("    write: write current settings now");
20266                pw.println("    installs: details about install sessions");
20267                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20268                pw.println("    dexopt: dump dexopt state");
20269                pw.println("    compiler-stats: dump compiler statistics");
20270                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20271                pw.println("    <package.name>: info about given package");
20272                return;
20273            } else if ("--checkin".equals(opt)) {
20274                checkin = true;
20275            } else if ("-f".equals(opt)) {
20276                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20277            } else if ("--proto".equals(opt)) {
20278                dumpProto(fd);
20279                return;
20280            } else {
20281                pw.println("Unknown argument: " + opt + "; use -h for help");
20282            }
20283        }
20284
20285        // Is the caller requesting to dump a particular piece of data?
20286        if (opti < args.length) {
20287            String cmd = args[opti];
20288            opti++;
20289            // Is this a package name?
20290            if ("android".equals(cmd) || cmd.contains(".")) {
20291                packageName = cmd;
20292                // When dumping a single package, we always dump all of its
20293                // filter information since the amount of data will be reasonable.
20294                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20295            } else if ("check-permission".equals(cmd)) {
20296                if (opti >= args.length) {
20297                    pw.println("Error: check-permission missing permission argument");
20298                    return;
20299                }
20300                String perm = args[opti];
20301                opti++;
20302                if (opti >= args.length) {
20303                    pw.println("Error: check-permission missing package argument");
20304                    return;
20305                }
20306
20307                String pkg = args[opti];
20308                opti++;
20309                int user = UserHandle.getUserId(Binder.getCallingUid());
20310                if (opti < args.length) {
20311                    try {
20312                        user = Integer.parseInt(args[opti]);
20313                    } catch (NumberFormatException e) {
20314                        pw.println("Error: check-permission user argument is not a number: "
20315                                + args[opti]);
20316                        return;
20317                    }
20318                }
20319
20320                // Normalize package name to handle renamed packages and static libs
20321                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20322
20323                pw.println(checkPermission(perm, pkg, user));
20324                return;
20325            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20326                dumpState.setDump(DumpState.DUMP_LIBS);
20327            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20328                dumpState.setDump(DumpState.DUMP_FEATURES);
20329            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20330                if (opti >= args.length) {
20331                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20332                            | DumpState.DUMP_SERVICE_RESOLVERS
20333                            | DumpState.DUMP_RECEIVER_RESOLVERS
20334                            | DumpState.DUMP_CONTENT_RESOLVERS);
20335                } else {
20336                    while (opti < args.length) {
20337                        String name = args[opti];
20338                        if ("a".equals(name) || "activity".equals(name)) {
20339                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20340                        } else if ("s".equals(name) || "service".equals(name)) {
20341                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20342                        } else if ("r".equals(name) || "receiver".equals(name)) {
20343                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20344                        } else if ("c".equals(name) || "content".equals(name)) {
20345                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20346                        } else {
20347                            pw.println("Error: unknown resolver table type: " + name);
20348                            return;
20349                        }
20350                        opti++;
20351                    }
20352                }
20353            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20354                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20355            } else if ("permission".equals(cmd)) {
20356                if (opti >= args.length) {
20357                    pw.println("Error: permission requires permission name");
20358                    return;
20359                }
20360                permissionNames = new ArraySet<>();
20361                while (opti < args.length) {
20362                    permissionNames.add(args[opti]);
20363                    opti++;
20364                }
20365                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20366                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20367            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20368                dumpState.setDump(DumpState.DUMP_PREFERRED);
20369            } else if ("preferred-xml".equals(cmd)) {
20370                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20371                if (opti < args.length && "--full".equals(args[opti])) {
20372                    fullPreferred = true;
20373                    opti++;
20374                }
20375            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20376                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20377            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20378                dumpState.setDump(DumpState.DUMP_PACKAGES);
20379            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20380                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20381            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20382                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20383            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20384                dumpState.setDump(DumpState.DUMP_MESSAGES);
20385            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20386                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20387            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20388                    || "intent-filter-verifiers".equals(cmd)) {
20389                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20390            } else if ("version".equals(cmd)) {
20391                dumpState.setDump(DumpState.DUMP_VERSION);
20392            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20393                dumpState.setDump(DumpState.DUMP_KEYSETS);
20394            } else if ("installs".equals(cmd)) {
20395                dumpState.setDump(DumpState.DUMP_INSTALLS);
20396            } else if ("frozen".equals(cmd)) {
20397                dumpState.setDump(DumpState.DUMP_FROZEN);
20398            } else if ("dexopt".equals(cmd)) {
20399                dumpState.setDump(DumpState.DUMP_DEXOPT);
20400            } else if ("compiler-stats".equals(cmd)) {
20401                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20402            } else if ("enabled-overlays".equals(cmd)) {
20403                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20404            } else if ("write".equals(cmd)) {
20405                synchronized (mPackages) {
20406                    mSettings.writeLPr();
20407                    pw.println("Settings written.");
20408                    return;
20409                }
20410            }
20411        }
20412
20413        if (checkin) {
20414            pw.println("vers,1");
20415        }
20416
20417        // reader
20418        synchronized (mPackages) {
20419            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20420                if (!checkin) {
20421                    if (dumpState.onTitlePrinted())
20422                        pw.println();
20423                    pw.println("Database versions:");
20424                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20425                }
20426            }
20427
20428            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20429                if (!checkin) {
20430                    if (dumpState.onTitlePrinted())
20431                        pw.println();
20432                    pw.println("Verifiers:");
20433                    pw.print("  Required: ");
20434                    pw.print(mRequiredVerifierPackage);
20435                    pw.print(" (uid=");
20436                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20437                            UserHandle.USER_SYSTEM));
20438                    pw.println(")");
20439                } else if (mRequiredVerifierPackage != null) {
20440                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20441                    pw.print(",");
20442                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20443                            UserHandle.USER_SYSTEM));
20444                }
20445            }
20446
20447            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20448                    packageName == null) {
20449                if (mIntentFilterVerifierComponent != null) {
20450                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20451                    if (!checkin) {
20452                        if (dumpState.onTitlePrinted())
20453                            pw.println();
20454                        pw.println("Intent Filter Verifier:");
20455                        pw.print("  Using: ");
20456                        pw.print(verifierPackageName);
20457                        pw.print(" (uid=");
20458                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20459                                UserHandle.USER_SYSTEM));
20460                        pw.println(")");
20461                    } else if (verifierPackageName != null) {
20462                        pw.print("ifv,"); pw.print(verifierPackageName);
20463                        pw.print(",");
20464                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20465                                UserHandle.USER_SYSTEM));
20466                    }
20467                } else {
20468                    pw.println();
20469                    pw.println("No Intent Filter Verifier available!");
20470                }
20471            }
20472
20473            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20474                boolean printedHeader = false;
20475                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20476                while (it.hasNext()) {
20477                    String libName = it.next();
20478                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20479                    if (versionedLib == null) {
20480                        continue;
20481                    }
20482                    final int versionCount = versionedLib.size();
20483                    for (int i = 0; i < versionCount; i++) {
20484                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20485                        if (!checkin) {
20486                            if (!printedHeader) {
20487                                if (dumpState.onTitlePrinted())
20488                                    pw.println();
20489                                pw.println("Libraries:");
20490                                printedHeader = true;
20491                            }
20492                            pw.print("  ");
20493                        } else {
20494                            pw.print("lib,");
20495                        }
20496                        pw.print(libEntry.info.getName());
20497                        if (libEntry.info.isStatic()) {
20498                            pw.print(" version=" + libEntry.info.getVersion());
20499                        }
20500                        if (!checkin) {
20501                            pw.print(" -> ");
20502                        }
20503                        if (libEntry.path != null) {
20504                            pw.print(" (jar) ");
20505                            pw.print(libEntry.path);
20506                        } else {
20507                            pw.print(" (apk) ");
20508                            pw.print(libEntry.apk);
20509                        }
20510                        pw.println();
20511                    }
20512                }
20513            }
20514
20515            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20516                if (dumpState.onTitlePrinted())
20517                    pw.println();
20518                if (!checkin) {
20519                    pw.println("Features:");
20520                }
20521
20522                synchronized (mAvailableFeatures) {
20523                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20524                        if (checkin) {
20525                            pw.print("feat,");
20526                            pw.print(feat.name);
20527                            pw.print(",");
20528                            pw.println(feat.version);
20529                        } else {
20530                            pw.print("  ");
20531                            pw.print(feat.name);
20532                            if (feat.version > 0) {
20533                                pw.print(" version=");
20534                                pw.print(feat.version);
20535                            }
20536                            pw.println();
20537                        }
20538                    }
20539                }
20540            }
20541
20542            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20543                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20544                        : "Activity Resolver Table:", "  ", packageName,
20545                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20546                    dumpState.setTitlePrinted(true);
20547                }
20548            }
20549            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20550                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20551                        : "Receiver Resolver Table:", "  ", packageName,
20552                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20553                    dumpState.setTitlePrinted(true);
20554                }
20555            }
20556            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20557                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20558                        : "Service Resolver Table:", "  ", packageName,
20559                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20560                    dumpState.setTitlePrinted(true);
20561                }
20562            }
20563            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20564                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20565                        : "Provider Resolver Table:", "  ", packageName,
20566                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20567                    dumpState.setTitlePrinted(true);
20568                }
20569            }
20570
20571            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20572                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20573                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20574                    int user = mSettings.mPreferredActivities.keyAt(i);
20575                    if (pir.dump(pw,
20576                            dumpState.getTitlePrinted()
20577                                ? "\nPreferred Activities User " + user + ":"
20578                                : "Preferred Activities User " + user + ":", "  ",
20579                            packageName, true, false)) {
20580                        dumpState.setTitlePrinted(true);
20581                    }
20582                }
20583            }
20584
20585            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20586                pw.flush();
20587                FileOutputStream fout = new FileOutputStream(fd);
20588                BufferedOutputStream str = new BufferedOutputStream(fout);
20589                XmlSerializer serializer = new FastXmlSerializer();
20590                try {
20591                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20592                    serializer.startDocument(null, true);
20593                    serializer.setFeature(
20594                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20595                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20596                    serializer.endDocument();
20597                    serializer.flush();
20598                } catch (IllegalArgumentException e) {
20599                    pw.println("Failed writing: " + e);
20600                } catch (IllegalStateException e) {
20601                    pw.println("Failed writing: " + e);
20602                } catch (IOException e) {
20603                    pw.println("Failed writing: " + e);
20604                }
20605            }
20606
20607            if (!checkin
20608                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20609                    && packageName == null) {
20610                pw.println();
20611                int count = mSettings.mPackages.size();
20612                if (count == 0) {
20613                    pw.println("No applications!");
20614                    pw.println();
20615                } else {
20616                    final String prefix = "  ";
20617                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20618                    if (allPackageSettings.size() == 0) {
20619                        pw.println("No domain preferred apps!");
20620                        pw.println();
20621                    } else {
20622                        pw.println("App verification status:");
20623                        pw.println();
20624                        count = 0;
20625                        for (PackageSetting ps : allPackageSettings) {
20626                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20627                            if (ivi == null || ivi.getPackageName() == null) continue;
20628                            pw.println(prefix + "Package: " + ivi.getPackageName());
20629                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20630                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20631                            pw.println();
20632                            count++;
20633                        }
20634                        if (count == 0) {
20635                            pw.println(prefix + "No app verification established.");
20636                            pw.println();
20637                        }
20638                        for (int userId : sUserManager.getUserIds()) {
20639                            pw.println("App linkages for user " + userId + ":");
20640                            pw.println();
20641                            count = 0;
20642                            for (PackageSetting ps : allPackageSettings) {
20643                                final long status = ps.getDomainVerificationStatusForUser(userId);
20644                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20645                                        && !DEBUG_DOMAIN_VERIFICATION) {
20646                                    continue;
20647                                }
20648                                pw.println(prefix + "Package: " + ps.name);
20649                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20650                                String statusStr = IntentFilterVerificationInfo.
20651                                        getStatusStringFromValue(status);
20652                                pw.println(prefix + "Status:  " + statusStr);
20653                                pw.println();
20654                                count++;
20655                            }
20656                            if (count == 0) {
20657                                pw.println(prefix + "No configured app linkages.");
20658                                pw.println();
20659                            }
20660                        }
20661                    }
20662                }
20663            }
20664
20665            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20666                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20667                if (packageName == null && permissionNames == null) {
20668                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20669                        if (iperm == 0) {
20670                            if (dumpState.onTitlePrinted())
20671                                pw.println();
20672                            pw.println("AppOp Permissions:");
20673                        }
20674                        pw.print("  AppOp Permission ");
20675                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20676                        pw.println(":");
20677                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20678                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20679                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20680                        }
20681                    }
20682                }
20683            }
20684
20685            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20686                boolean printedSomething = false;
20687                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20688                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20689                        continue;
20690                    }
20691                    if (!printedSomething) {
20692                        if (dumpState.onTitlePrinted())
20693                            pw.println();
20694                        pw.println("Registered ContentProviders:");
20695                        printedSomething = true;
20696                    }
20697                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20698                    pw.print("    "); pw.println(p.toString());
20699                }
20700                printedSomething = false;
20701                for (Map.Entry<String, PackageParser.Provider> entry :
20702                        mProvidersByAuthority.entrySet()) {
20703                    PackageParser.Provider p = entry.getValue();
20704                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20705                        continue;
20706                    }
20707                    if (!printedSomething) {
20708                        if (dumpState.onTitlePrinted())
20709                            pw.println();
20710                        pw.println("ContentProvider Authorities:");
20711                        printedSomething = true;
20712                    }
20713                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20714                    pw.print("    "); pw.println(p.toString());
20715                    if (p.info != null && p.info.applicationInfo != null) {
20716                        final String appInfo = p.info.applicationInfo.toString();
20717                        pw.print("      applicationInfo="); pw.println(appInfo);
20718                    }
20719                }
20720            }
20721
20722            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20723                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20724            }
20725
20726            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20727                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20728            }
20729
20730            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20731                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20732            }
20733
20734            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20735                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20736            }
20737
20738            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20739                // XXX should handle packageName != null by dumping only install data that
20740                // the given package is involved with.
20741                if (dumpState.onTitlePrinted()) pw.println();
20742                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20743            }
20744
20745            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20746                // XXX should handle packageName != null by dumping only install data that
20747                // the given package is involved with.
20748                if (dumpState.onTitlePrinted()) pw.println();
20749
20750                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20751                ipw.println();
20752                ipw.println("Frozen packages:");
20753                ipw.increaseIndent();
20754                if (mFrozenPackages.size() == 0) {
20755                    ipw.println("(none)");
20756                } else {
20757                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20758                        ipw.println(mFrozenPackages.valueAt(i));
20759                    }
20760                }
20761                ipw.decreaseIndent();
20762            }
20763
20764            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20765                if (dumpState.onTitlePrinted()) pw.println();
20766                dumpDexoptStateLPr(pw, packageName);
20767            }
20768
20769            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20770                if (dumpState.onTitlePrinted()) pw.println();
20771                dumpCompilerStatsLPr(pw, packageName);
20772            }
20773
20774            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20775                if (dumpState.onTitlePrinted()) pw.println();
20776                dumpEnabledOverlaysLPr(pw);
20777            }
20778
20779            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20780                if (dumpState.onTitlePrinted()) pw.println();
20781                mSettings.dumpReadMessagesLPr(pw, dumpState);
20782
20783                pw.println();
20784                pw.println("Package warning messages:");
20785                BufferedReader in = null;
20786                String line = null;
20787                try {
20788                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20789                    while ((line = in.readLine()) != null) {
20790                        if (line.contains("ignored: updated version")) continue;
20791                        pw.println(line);
20792                    }
20793                } catch (IOException ignored) {
20794                } finally {
20795                    IoUtils.closeQuietly(in);
20796                }
20797            }
20798
20799            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20800                BufferedReader in = null;
20801                String line = null;
20802                try {
20803                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20804                    while ((line = in.readLine()) != null) {
20805                        if (line.contains("ignored: updated version")) continue;
20806                        pw.print("msg,");
20807                        pw.println(line);
20808                    }
20809                } catch (IOException ignored) {
20810                } finally {
20811                    IoUtils.closeQuietly(in);
20812                }
20813            }
20814        }
20815    }
20816
20817    private void dumpProto(FileDescriptor fd) {
20818        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20819
20820        synchronized (mPackages) {
20821            final long requiredVerifierPackageToken =
20822                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20823            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20824            proto.write(
20825                    PackageServiceDumpProto.PackageShortProto.UID,
20826                    getPackageUid(
20827                            mRequiredVerifierPackage,
20828                            MATCH_DEBUG_TRIAGED_MISSING,
20829                            UserHandle.USER_SYSTEM));
20830            proto.end(requiredVerifierPackageToken);
20831
20832            if (mIntentFilterVerifierComponent != null) {
20833                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20834                final long verifierPackageToken =
20835                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20836                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20837                proto.write(
20838                        PackageServiceDumpProto.PackageShortProto.UID,
20839                        getPackageUid(
20840                                verifierPackageName,
20841                                MATCH_DEBUG_TRIAGED_MISSING,
20842                                UserHandle.USER_SYSTEM));
20843                proto.end(verifierPackageToken);
20844            }
20845
20846            dumpSharedLibrariesProto(proto);
20847            dumpFeaturesProto(proto);
20848            mSettings.dumpPackagesProto(proto);
20849            mSettings.dumpSharedUsersProto(proto);
20850            dumpMessagesProto(proto);
20851        }
20852        proto.flush();
20853    }
20854
20855    private void dumpMessagesProto(ProtoOutputStream proto) {
20856        BufferedReader in = null;
20857        String line = null;
20858        try {
20859            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20860            while ((line = in.readLine()) != null) {
20861                if (line.contains("ignored: updated version")) continue;
20862                proto.write(PackageServiceDumpProto.MESSAGES, line);
20863            }
20864        } catch (IOException ignored) {
20865        } finally {
20866            IoUtils.closeQuietly(in);
20867        }
20868    }
20869
20870    private void dumpFeaturesProto(ProtoOutputStream proto) {
20871        synchronized (mAvailableFeatures) {
20872            final int count = mAvailableFeatures.size();
20873            for (int i = 0; i < count; i++) {
20874                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20875                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20876                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20877                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20878                proto.end(featureToken);
20879            }
20880        }
20881    }
20882
20883    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20884        final int count = mSharedLibraries.size();
20885        for (int i = 0; i < count; i++) {
20886            final String libName = mSharedLibraries.keyAt(i);
20887            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20888            if (versionedLib == null) {
20889                continue;
20890            }
20891            final int versionCount = versionedLib.size();
20892            for (int j = 0; j < versionCount; j++) {
20893                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20894                final long sharedLibraryToken =
20895                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20896                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20897                final boolean isJar = (libEntry.path != null);
20898                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20899                if (isJar) {
20900                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20901                } else {
20902                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20903                }
20904                proto.end(sharedLibraryToken);
20905            }
20906        }
20907    }
20908
20909    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20910        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20911        ipw.println();
20912        ipw.println("Dexopt state:");
20913        ipw.increaseIndent();
20914        Collection<PackageParser.Package> packages = null;
20915        if (packageName != null) {
20916            PackageParser.Package targetPackage = mPackages.get(packageName);
20917            if (targetPackage != null) {
20918                packages = Collections.singletonList(targetPackage);
20919            } else {
20920                ipw.println("Unable to find package: " + packageName);
20921                return;
20922            }
20923        } else {
20924            packages = mPackages.values();
20925        }
20926
20927        for (PackageParser.Package pkg : packages) {
20928            ipw.println("[" + pkg.packageName + "]");
20929            ipw.increaseIndent();
20930            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20931            ipw.decreaseIndent();
20932        }
20933    }
20934
20935    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20936        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20937        ipw.println();
20938        ipw.println("Compiler stats:");
20939        ipw.increaseIndent();
20940        Collection<PackageParser.Package> packages = null;
20941        if (packageName != null) {
20942            PackageParser.Package targetPackage = mPackages.get(packageName);
20943            if (targetPackage != null) {
20944                packages = Collections.singletonList(targetPackage);
20945            } else {
20946                ipw.println("Unable to find package: " + packageName);
20947                return;
20948            }
20949        } else {
20950            packages = mPackages.values();
20951        }
20952
20953        for (PackageParser.Package pkg : packages) {
20954            ipw.println("[" + pkg.packageName + "]");
20955            ipw.increaseIndent();
20956
20957            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20958            if (stats == null) {
20959                ipw.println("(No recorded stats)");
20960            } else {
20961                stats.dump(ipw);
20962            }
20963            ipw.decreaseIndent();
20964        }
20965    }
20966
20967    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20968        pw.println("Enabled overlay paths:");
20969        final int N = mEnabledOverlayPaths.size();
20970        for (int i = 0; i < N; i++) {
20971            final int userId = mEnabledOverlayPaths.keyAt(i);
20972            pw.println(String.format("    User %d:", userId));
20973            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20974                mEnabledOverlayPaths.valueAt(i);
20975            final int M = userSpecificOverlays.size();
20976            for (int j = 0; j < M; j++) {
20977                final String targetPackageName = userSpecificOverlays.keyAt(j);
20978                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
20979                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
20980            }
20981        }
20982    }
20983
20984    private String dumpDomainString(String packageName) {
20985        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20986                .getList();
20987        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20988
20989        ArraySet<String> result = new ArraySet<>();
20990        if (iviList.size() > 0) {
20991            for (IntentFilterVerificationInfo ivi : iviList) {
20992                for (String host : ivi.getDomains()) {
20993                    result.add(host);
20994                }
20995            }
20996        }
20997        if (filters != null && filters.size() > 0) {
20998            for (IntentFilter filter : filters) {
20999                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21000                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21001                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21002                    result.addAll(filter.getHostsList());
21003                }
21004            }
21005        }
21006
21007        StringBuilder sb = new StringBuilder(result.size() * 16);
21008        for (String domain : result) {
21009            if (sb.length() > 0) sb.append(" ");
21010            sb.append(domain);
21011        }
21012        return sb.toString();
21013    }
21014
21015    // ------- apps on sdcard specific code -------
21016    static final boolean DEBUG_SD_INSTALL = false;
21017
21018    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21019
21020    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21021
21022    private boolean mMediaMounted = false;
21023
21024    static String getEncryptKey() {
21025        try {
21026            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21027                    SD_ENCRYPTION_KEYSTORE_NAME);
21028            if (sdEncKey == null) {
21029                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21030                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21031                if (sdEncKey == null) {
21032                    Slog.e(TAG, "Failed to create encryption keys");
21033                    return null;
21034                }
21035            }
21036            return sdEncKey;
21037        } catch (NoSuchAlgorithmException nsae) {
21038            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21039            return null;
21040        } catch (IOException ioe) {
21041            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21042            return null;
21043        }
21044    }
21045
21046    /*
21047     * Update media status on PackageManager.
21048     */
21049    @Override
21050    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21051        int callingUid = Binder.getCallingUid();
21052        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21053            throw new SecurityException("Media status can only be updated by the system");
21054        }
21055        // reader; this apparently protects mMediaMounted, but should probably
21056        // be a different lock in that case.
21057        synchronized (mPackages) {
21058            Log.i(TAG, "Updating external media status from "
21059                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21060                    + (mediaStatus ? "mounted" : "unmounted"));
21061            if (DEBUG_SD_INSTALL)
21062                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21063                        + ", mMediaMounted=" + mMediaMounted);
21064            if (mediaStatus == mMediaMounted) {
21065                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21066                        : 0, -1);
21067                mHandler.sendMessage(msg);
21068                return;
21069            }
21070            mMediaMounted = mediaStatus;
21071        }
21072        // Queue up an async operation since the package installation may take a
21073        // little while.
21074        mHandler.post(new Runnable() {
21075            public void run() {
21076                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21077            }
21078        });
21079    }
21080
21081    /**
21082     * Called by StorageManagerService when the initial ASECs to scan are available.
21083     * Should block until all the ASEC containers are finished being scanned.
21084     */
21085    public void scanAvailableAsecs() {
21086        updateExternalMediaStatusInner(true, false, false);
21087    }
21088
21089    /*
21090     * Collect information of applications on external media, map them against
21091     * existing containers and update information based on current mount status.
21092     * Please note that we always have to report status if reportStatus has been
21093     * set to true especially when unloading packages.
21094     */
21095    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21096            boolean externalStorage) {
21097        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21098        int[] uidArr = EmptyArray.INT;
21099
21100        final String[] list = PackageHelper.getSecureContainerList();
21101        if (ArrayUtils.isEmpty(list)) {
21102            Log.i(TAG, "No secure containers found");
21103        } else {
21104            // Process list of secure containers and categorize them
21105            // as active or stale based on their package internal state.
21106
21107            // reader
21108            synchronized (mPackages) {
21109                for (String cid : list) {
21110                    // Leave stages untouched for now; installer service owns them
21111                    if (PackageInstallerService.isStageName(cid)) continue;
21112
21113                    if (DEBUG_SD_INSTALL)
21114                        Log.i(TAG, "Processing container " + cid);
21115                    String pkgName = getAsecPackageName(cid);
21116                    if (pkgName == null) {
21117                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21118                        continue;
21119                    }
21120                    if (DEBUG_SD_INSTALL)
21121                        Log.i(TAG, "Looking for pkg : " + pkgName);
21122
21123                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21124                    if (ps == null) {
21125                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21126                        continue;
21127                    }
21128
21129                    /*
21130                     * Skip packages that are not external if we're unmounting
21131                     * external storage.
21132                     */
21133                    if (externalStorage && !isMounted && !isExternal(ps)) {
21134                        continue;
21135                    }
21136
21137                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21138                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21139                    // The package status is changed only if the code path
21140                    // matches between settings and the container id.
21141                    if (ps.codePathString != null
21142                            && ps.codePathString.startsWith(args.getCodePath())) {
21143                        if (DEBUG_SD_INSTALL) {
21144                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21145                                    + " at code path: " + ps.codePathString);
21146                        }
21147
21148                        // We do have a valid package installed on sdcard
21149                        processCids.put(args, ps.codePathString);
21150                        final int uid = ps.appId;
21151                        if (uid != -1) {
21152                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21153                        }
21154                    } else {
21155                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21156                                + ps.codePathString);
21157                    }
21158                }
21159            }
21160
21161            Arrays.sort(uidArr);
21162        }
21163
21164        // Process packages with valid entries.
21165        if (isMounted) {
21166            if (DEBUG_SD_INSTALL)
21167                Log.i(TAG, "Loading packages");
21168            loadMediaPackages(processCids, uidArr, externalStorage);
21169            startCleaningPackages();
21170            mInstallerService.onSecureContainersAvailable();
21171        } else {
21172            if (DEBUG_SD_INSTALL)
21173                Log.i(TAG, "Unloading packages");
21174            unloadMediaPackages(processCids, uidArr, reportStatus);
21175        }
21176    }
21177
21178    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21179            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21180        final int size = infos.size();
21181        final String[] packageNames = new String[size];
21182        final int[] packageUids = new int[size];
21183        for (int i = 0; i < size; i++) {
21184            final ApplicationInfo info = infos.get(i);
21185            packageNames[i] = info.packageName;
21186            packageUids[i] = info.uid;
21187        }
21188        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21189                finishedReceiver);
21190    }
21191
21192    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21193            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21194        sendResourcesChangedBroadcast(mediaStatus, replacing,
21195                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21196    }
21197
21198    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21199            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21200        int size = pkgList.length;
21201        if (size > 0) {
21202            // Send broadcasts here
21203            Bundle extras = new Bundle();
21204            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21205            if (uidArr != null) {
21206                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21207            }
21208            if (replacing) {
21209                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21210            }
21211            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21212                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21213            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21214        }
21215    }
21216
21217   /*
21218     * Look at potentially valid container ids from processCids If package
21219     * information doesn't match the one on record or package scanning fails,
21220     * the cid is added to list of removeCids. We currently don't delete stale
21221     * containers.
21222     */
21223    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21224            boolean externalStorage) {
21225        ArrayList<String> pkgList = new ArrayList<String>();
21226        Set<AsecInstallArgs> keys = processCids.keySet();
21227
21228        for (AsecInstallArgs args : keys) {
21229            String codePath = processCids.get(args);
21230            if (DEBUG_SD_INSTALL)
21231                Log.i(TAG, "Loading container : " + args.cid);
21232            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21233            try {
21234                // Make sure there are no container errors first.
21235                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21236                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21237                            + " when installing from sdcard");
21238                    continue;
21239                }
21240                // Check code path here.
21241                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21242                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21243                            + " does not match one in settings " + codePath);
21244                    continue;
21245                }
21246                // Parse package
21247                int parseFlags = mDefParseFlags;
21248                if (args.isExternalAsec()) {
21249                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21250                }
21251                if (args.isFwdLocked()) {
21252                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21253                }
21254
21255                synchronized (mInstallLock) {
21256                    PackageParser.Package pkg = null;
21257                    try {
21258                        // Sadly we don't know the package name yet to freeze it
21259                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21260                                SCAN_IGNORE_FROZEN, 0, null);
21261                    } catch (PackageManagerException e) {
21262                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21263                    }
21264                    // Scan the package
21265                    if (pkg != null) {
21266                        /*
21267                         * TODO why is the lock being held? doPostInstall is
21268                         * called in other places without the lock. This needs
21269                         * to be straightened out.
21270                         */
21271                        // writer
21272                        synchronized (mPackages) {
21273                            retCode = PackageManager.INSTALL_SUCCEEDED;
21274                            pkgList.add(pkg.packageName);
21275                            // Post process args
21276                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21277                                    pkg.applicationInfo.uid);
21278                        }
21279                    } else {
21280                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21281                    }
21282                }
21283
21284            } finally {
21285                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21286                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21287                }
21288            }
21289        }
21290        // writer
21291        synchronized (mPackages) {
21292            // If the platform SDK has changed since the last time we booted,
21293            // we need to re-grant app permission to catch any new ones that
21294            // appear. This is really a hack, and means that apps can in some
21295            // cases get permissions that the user didn't initially explicitly
21296            // allow... it would be nice to have some better way to handle
21297            // this situation.
21298            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21299                    : mSettings.getInternalVersion();
21300            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21301                    : StorageManager.UUID_PRIVATE_INTERNAL;
21302
21303            int updateFlags = UPDATE_PERMISSIONS_ALL;
21304            if (ver.sdkVersion != mSdkVersion) {
21305                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21306                        + mSdkVersion + "; regranting permissions for external");
21307                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21308            }
21309            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21310
21311            // Yay, everything is now upgraded
21312            ver.forceCurrent();
21313
21314            // can downgrade to reader
21315            // Persist settings
21316            mSettings.writeLPr();
21317        }
21318        // Send a broadcast to let everyone know we are done processing
21319        if (pkgList.size() > 0) {
21320            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21321        }
21322    }
21323
21324   /*
21325     * Utility method to unload a list of specified containers
21326     */
21327    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21328        // Just unmount all valid containers.
21329        for (AsecInstallArgs arg : cidArgs) {
21330            synchronized (mInstallLock) {
21331                arg.doPostDeleteLI(false);
21332           }
21333       }
21334   }
21335
21336    /*
21337     * Unload packages mounted on external media. This involves deleting package
21338     * data from internal structures, sending broadcasts about disabled packages,
21339     * gc'ing to free up references, unmounting all secure containers
21340     * corresponding to packages on external media, and posting a
21341     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21342     * that we always have to post this message if status has been requested no
21343     * matter what.
21344     */
21345    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21346            final boolean reportStatus) {
21347        if (DEBUG_SD_INSTALL)
21348            Log.i(TAG, "unloading media packages");
21349        ArrayList<String> pkgList = new ArrayList<String>();
21350        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21351        final Set<AsecInstallArgs> keys = processCids.keySet();
21352        for (AsecInstallArgs args : keys) {
21353            String pkgName = args.getPackageName();
21354            if (DEBUG_SD_INSTALL)
21355                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21356            // Delete package internally
21357            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21358            synchronized (mInstallLock) {
21359                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21360                final boolean res;
21361                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21362                        "unloadMediaPackages")) {
21363                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21364                            null);
21365                }
21366                if (res) {
21367                    pkgList.add(pkgName);
21368                } else {
21369                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21370                    failedList.add(args);
21371                }
21372            }
21373        }
21374
21375        // reader
21376        synchronized (mPackages) {
21377            // We didn't update the settings after removing each package;
21378            // write them now for all packages.
21379            mSettings.writeLPr();
21380        }
21381
21382        // We have to absolutely send UPDATED_MEDIA_STATUS only
21383        // after confirming that all the receivers processed the ordered
21384        // broadcast when packages get disabled, force a gc to clean things up.
21385        // and unload all the containers.
21386        if (pkgList.size() > 0) {
21387            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21388                    new IIntentReceiver.Stub() {
21389                public void performReceive(Intent intent, int resultCode, String data,
21390                        Bundle extras, boolean ordered, boolean sticky,
21391                        int sendingUser) throws RemoteException {
21392                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21393                            reportStatus ? 1 : 0, 1, keys);
21394                    mHandler.sendMessage(msg);
21395                }
21396            });
21397        } else {
21398            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21399                    keys);
21400            mHandler.sendMessage(msg);
21401        }
21402    }
21403
21404    private void loadPrivatePackages(final VolumeInfo vol) {
21405        mHandler.post(new Runnable() {
21406            @Override
21407            public void run() {
21408                loadPrivatePackagesInner(vol);
21409            }
21410        });
21411    }
21412
21413    private void loadPrivatePackagesInner(VolumeInfo vol) {
21414        final String volumeUuid = vol.fsUuid;
21415        if (TextUtils.isEmpty(volumeUuid)) {
21416            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21417            return;
21418        }
21419
21420        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21421        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21422        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21423
21424        final VersionInfo ver;
21425        final List<PackageSetting> packages;
21426        synchronized (mPackages) {
21427            ver = mSettings.findOrCreateVersion(volumeUuid);
21428            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21429        }
21430
21431        for (PackageSetting ps : packages) {
21432            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21433            synchronized (mInstallLock) {
21434                final PackageParser.Package pkg;
21435                try {
21436                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21437                    loaded.add(pkg.applicationInfo);
21438
21439                } catch (PackageManagerException e) {
21440                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21441                }
21442
21443                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21444                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21445                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21446                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21447                }
21448            }
21449        }
21450
21451        // Reconcile app data for all started/unlocked users
21452        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21453        final UserManager um = mContext.getSystemService(UserManager.class);
21454        UserManagerInternal umInternal = getUserManagerInternal();
21455        for (UserInfo user : um.getUsers()) {
21456            final int flags;
21457            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21458                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21459            } else if (umInternal.isUserRunning(user.id)) {
21460                flags = StorageManager.FLAG_STORAGE_DE;
21461            } else {
21462                continue;
21463            }
21464
21465            try {
21466                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21467                synchronized (mInstallLock) {
21468                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21469                }
21470            } catch (IllegalStateException e) {
21471                // Device was probably ejected, and we'll process that event momentarily
21472                Slog.w(TAG, "Failed to prepare storage: " + e);
21473            }
21474        }
21475
21476        synchronized (mPackages) {
21477            int updateFlags = UPDATE_PERMISSIONS_ALL;
21478            if (ver.sdkVersion != mSdkVersion) {
21479                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21480                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21481                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21482            }
21483            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21484
21485            // Yay, everything is now upgraded
21486            ver.forceCurrent();
21487
21488            mSettings.writeLPr();
21489        }
21490
21491        for (PackageFreezer freezer : freezers) {
21492            freezer.close();
21493        }
21494
21495        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21496        sendResourcesChangedBroadcast(true, false, loaded, null);
21497    }
21498
21499    private void unloadPrivatePackages(final VolumeInfo vol) {
21500        mHandler.post(new Runnable() {
21501            @Override
21502            public void run() {
21503                unloadPrivatePackagesInner(vol);
21504            }
21505        });
21506    }
21507
21508    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21509        final String volumeUuid = vol.fsUuid;
21510        if (TextUtils.isEmpty(volumeUuid)) {
21511            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21512            return;
21513        }
21514
21515        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21516        synchronized (mInstallLock) {
21517        synchronized (mPackages) {
21518            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21519            for (PackageSetting ps : packages) {
21520                if (ps.pkg == null) continue;
21521
21522                final ApplicationInfo info = ps.pkg.applicationInfo;
21523                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21524                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21525
21526                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21527                        "unloadPrivatePackagesInner")) {
21528                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21529                            false, null)) {
21530                        unloaded.add(info);
21531                    } else {
21532                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21533                    }
21534                }
21535
21536                // Try very hard to release any references to this package
21537                // so we don't risk the system server being killed due to
21538                // open FDs
21539                AttributeCache.instance().removePackage(ps.name);
21540            }
21541
21542            mSettings.writeLPr();
21543        }
21544        }
21545
21546        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21547        sendResourcesChangedBroadcast(false, false, unloaded, null);
21548
21549        // Try very hard to release any references to this path so we don't risk
21550        // the system server being killed due to open FDs
21551        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21552
21553        for (int i = 0; i < 3; i++) {
21554            System.gc();
21555            System.runFinalization();
21556        }
21557    }
21558
21559    private void assertPackageKnown(String volumeUuid, String packageName)
21560            throws PackageManagerException {
21561        synchronized (mPackages) {
21562            // Normalize package name to handle renamed packages
21563            packageName = normalizePackageNameLPr(packageName);
21564
21565            final PackageSetting ps = mSettings.mPackages.get(packageName);
21566            if (ps == null) {
21567                throw new PackageManagerException("Package " + packageName + " is unknown");
21568            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21569                throw new PackageManagerException(
21570                        "Package " + packageName + " found on unknown volume " + volumeUuid
21571                                + "; expected volume " + ps.volumeUuid);
21572            }
21573        }
21574    }
21575
21576    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21577            throws PackageManagerException {
21578        synchronized (mPackages) {
21579            // Normalize package name to handle renamed packages
21580            packageName = normalizePackageNameLPr(packageName);
21581
21582            final PackageSetting ps = mSettings.mPackages.get(packageName);
21583            if (ps == null) {
21584                throw new PackageManagerException("Package " + packageName + " is unknown");
21585            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21586                throw new PackageManagerException(
21587                        "Package " + packageName + " found on unknown volume " + volumeUuid
21588                                + "; expected volume " + ps.volumeUuid);
21589            } else if (!ps.getInstalled(userId)) {
21590                throw new PackageManagerException(
21591                        "Package " + packageName + " not installed for user " + userId);
21592            }
21593        }
21594    }
21595
21596    private List<String> collectAbsoluteCodePaths() {
21597        synchronized (mPackages) {
21598            List<String> codePaths = new ArrayList<>();
21599            final int packageCount = mSettings.mPackages.size();
21600            for (int i = 0; i < packageCount; i++) {
21601                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21602                codePaths.add(ps.codePath.getAbsolutePath());
21603            }
21604            return codePaths;
21605        }
21606    }
21607
21608    /**
21609     * Examine all apps present on given mounted volume, and destroy apps that
21610     * aren't expected, either due to uninstallation or reinstallation on
21611     * another volume.
21612     */
21613    private void reconcileApps(String volumeUuid) {
21614        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21615        List<File> filesToDelete = null;
21616
21617        final File[] files = FileUtils.listFilesOrEmpty(
21618                Environment.getDataAppDirectory(volumeUuid));
21619        for (File file : files) {
21620            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21621                    && !PackageInstallerService.isStageName(file.getName());
21622            if (!isPackage) {
21623                // Ignore entries which are not packages
21624                continue;
21625            }
21626
21627            String absolutePath = file.getAbsolutePath();
21628
21629            boolean pathValid = false;
21630            final int absoluteCodePathCount = absoluteCodePaths.size();
21631            for (int i = 0; i < absoluteCodePathCount; i++) {
21632                String absoluteCodePath = absoluteCodePaths.get(i);
21633                if (absolutePath.startsWith(absoluteCodePath)) {
21634                    pathValid = true;
21635                    break;
21636                }
21637            }
21638
21639            if (!pathValid) {
21640                if (filesToDelete == null) {
21641                    filesToDelete = new ArrayList<>();
21642                }
21643                filesToDelete.add(file);
21644            }
21645        }
21646
21647        if (filesToDelete != null) {
21648            final int fileToDeleteCount = filesToDelete.size();
21649            for (int i = 0; i < fileToDeleteCount; i++) {
21650                File fileToDelete = filesToDelete.get(i);
21651                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21652                synchronized (mInstallLock) {
21653                    removeCodePathLI(fileToDelete);
21654                }
21655            }
21656        }
21657    }
21658
21659    /**
21660     * Reconcile all app data for the given user.
21661     * <p>
21662     * Verifies that directories exist and that ownership and labeling is
21663     * correct for all installed apps on all mounted volumes.
21664     */
21665    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21666        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21667        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21668            final String volumeUuid = vol.getFsUuid();
21669            synchronized (mInstallLock) {
21670                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21671            }
21672        }
21673    }
21674
21675    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21676            boolean migrateAppData) {
21677        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21678    }
21679
21680    /**
21681     * Reconcile all app data on given mounted volume.
21682     * <p>
21683     * Destroys app data that isn't expected, either due to uninstallation or
21684     * reinstallation on another volume.
21685     * <p>
21686     * Verifies that directories exist and that ownership and labeling is
21687     * correct for all installed apps.
21688     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21689     */
21690    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21691            boolean migrateAppData, boolean onlyCoreApps) {
21692        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21693                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21694        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21695
21696        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21697        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21698
21699        // First look for stale data that doesn't belong, and check if things
21700        // have changed since we did our last restorecon
21701        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21702            if (StorageManager.isFileEncryptedNativeOrEmulated()
21703                    && !StorageManager.isUserKeyUnlocked(userId)) {
21704                throw new RuntimeException(
21705                        "Yikes, someone asked us to reconcile CE storage while " + userId
21706                                + " was still locked; this would have caused massive data loss!");
21707            }
21708
21709            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21710            for (File file : files) {
21711                final String packageName = file.getName();
21712                try {
21713                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21714                } catch (PackageManagerException e) {
21715                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21716                    try {
21717                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21718                                StorageManager.FLAG_STORAGE_CE, 0);
21719                    } catch (InstallerException e2) {
21720                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21721                    }
21722                }
21723            }
21724        }
21725        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21726            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21727            for (File file : files) {
21728                final String packageName = file.getName();
21729                try {
21730                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21731                } catch (PackageManagerException e) {
21732                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21733                    try {
21734                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21735                                StorageManager.FLAG_STORAGE_DE, 0);
21736                    } catch (InstallerException e2) {
21737                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21738                    }
21739                }
21740            }
21741        }
21742
21743        // Ensure that data directories are ready to roll for all packages
21744        // installed for this volume and user
21745        final List<PackageSetting> packages;
21746        synchronized (mPackages) {
21747            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21748        }
21749        int preparedCount = 0;
21750        for (PackageSetting ps : packages) {
21751            final String packageName = ps.name;
21752            if (ps.pkg == null) {
21753                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21754                // TODO: might be due to legacy ASEC apps; we should circle back
21755                // and reconcile again once they're scanned
21756                continue;
21757            }
21758            // Skip non-core apps if requested
21759            if (onlyCoreApps && !ps.pkg.coreApp) {
21760                result.add(packageName);
21761                continue;
21762            }
21763
21764            if (ps.getInstalled(userId)) {
21765                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21766                preparedCount++;
21767            }
21768        }
21769
21770        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21771        return result;
21772    }
21773
21774    /**
21775     * Prepare app data for the given app just after it was installed or
21776     * upgraded. This method carefully only touches users that it's installed
21777     * for, and it forces a restorecon to handle any seinfo changes.
21778     * <p>
21779     * Verifies that directories exist and that ownership and labeling is
21780     * correct for all installed apps. If there is an ownership mismatch, it
21781     * will try recovering system apps by wiping data; third-party app data is
21782     * left intact.
21783     * <p>
21784     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21785     */
21786    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21787        final PackageSetting ps;
21788        synchronized (mPackages) {
21789            ps = mSettings.mPackages.get(pkg.packageName);
21790            mSettings.writeKernelMappingLPr(ps);
21791        }
21792
21793        final UserManager um = mContext.getSystemService(UserManager.class);
21794        UserManagerInternal umInternal = getUserManagerInternal();
21795        for (UserInfo user : um.getUsers()) {
21796            final int flags;
21797            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21798                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21799            } else if (umInternal.isUserRunning(user.id)) {
21800                flags = StorageManager.FLAG_STORAGE_DE;
21801            } else {
21802                continue;
21803            }
21804
21805            if (ps.getInstalled(user.id)) {
21806                // TODO: when user data is locked, mark that we're still dirty
21807                prepareAppDataLIF(pkg, user.id, flags);
21808            }
21809        }
21810    }
21811
21812    /**
21813     * Prepare app data for the given app.
21814     * <p>
21815     * Verifies that directories exist and that ownership and labeling is
21816     * correct for all installed apps. If there is an ownership mismatch, this
21817     * will try recovering system apps by wiping data; third-party app data is
21818     * left intact.
21819     */
21820    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21821        if (pkg == null) {
21822            Slog.wtf(TAG, "Package was null!", new Throwable());
21823            return;
21824        }
21825        prepareAppDataLeafLIF(pkg, userId, flags);
21826        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21827        for (int i = 0; i < childCount; i++) {
21828            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21829        }
21830    }
21831
21832    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21833            boolean maybeMigrateAppData) {
21834        prepareAppDataLIF(pkg, userId, flags);
21835
21836        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21837            // We may have just shuffled around app data directories, so
21838            // prepare them one more time
21839            prepareAppDataLIF(pkg, userId, flags);
21840        }
21841    }
21842
21843    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21844        if (DEBUG_APP_DATA) {
21845            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21846                    + Integer.toHexString(flags));
21847        }
21848
21849        final String volumeUuid = pkg.volumeUuid;
21850        final String packageName = pkg.packageName;
21851        final ApplicationInfo app = pkg.applicationInfo;
21852        final int appId = UserHandle.getAppId(app.uid);
21853
21854        Preconditions.checkNotNull(app.seInfo);
21855
21856        long ceDataInode = -1;
21857        try {
21858            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21859                    appId, app.seInfo, app.targetSdkVersion);
21860        } catch (InstallerException e) {
21861            if (app.isSystemApp()) {
21862                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21863                        + ", but trying to recover: " + e);
21864                destroyAppDataLeafLIF(pkg, userId, flags);
21865                try {
21866                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21867                            appId, app.seInfo, app.targetSdkVersion);
21868                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21869                } catch (InstallerException e2) {
21870                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21871                }
21872            } else {
21873                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21874            }
21875        }
21876
21877        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21878            // TODO: mark this structure as dirty so we persist it!
21879            synchronized (mPackages) {
21880                final PackageSetting ps = mSettings.mPackages.get(packageName);
21881                if (ps != null) {
21882                    ps.setCeDataInode(ceDataInode, userId);
21883                }
21884            }
21885        }
21886
21887        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21888    }
21889
21890    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21891        if (pkg == null) {
21892            Slog.wtf(TAG, "Package was null!", new Throwable());
21893            return;
21894        }
21895        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21896        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21897        for (int i = 0; i < childCount; i++) {
21898            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21899        }
21900    }
21901
21902    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21903        final String volumeUuid = pkg.volumeUuid;
21904        final String packageName = pkg.packageName;
21905        final ApplicationInfo app = pkg.applicationInfo;
21906
21907        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21908            // Create a native library symlink only if we have native libraries
21909            // and if the native libraries are 32 bit libraries. We do not provide
21910            // this symlink for 64 bit libraries.
21911            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21912                final String nativeLibPath = app.nativeLibraryDir;
21913                try {
21914                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21915                            nativeLibPath, userId);
21916                } catch (InstallerException e) {
21917                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21918                }
21919            }
21920        }
21921    }
21922
21923    /**
21924     * For system apps on non-FBE devices, this method migrates any existing
21925     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21926     * requested by the app.
21927     */
21928    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21929        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21930                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21931            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21932                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21933            try {
21934                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21935                        storageTarget);
21936            } catch (InstallerException e) {
21937                logCriticalInfo(Log.WARN,
21938                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21939            }
21940            return true;
21941        } else {
21942            return false;
21943        }
21944    }
21945
21946    public PackageFreezer freezePackage(String packageName, String killReason) {
21947        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21948    }
21949
21950    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21951        return new PackageFreezer(packageName, userId, killReason);
21952    }
21953
21954    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21955            String killReason) {
21956        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21957    }
21958
21959    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21960            String killReason) {
21961        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21962            return new PackageFreezer();
21963        } else {
21964            return freezePackage(packageName, userId, killReason);
21965        }
21966    }
21967
21968    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21969            String killReason) {
21970        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21971    }
21972
21973    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21974            String killReason) {
21975        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21976            return new PackageFreezer();
21977        } else {
21978            return freezePackage(packageName, userId, killReason);
21979        }
21980    }
21981
21982    /**
21983     * Class that freezes and kills the given package upon creation, and
21984     * unfreezes it upon closing. This is typically used when doing surgery on
21985     * app code/data to prevent the app from running while you're working.
21986     */
21987    private class PackageFreezer implements AutoCloseable {
21988        private final String mPackageName;
21989        private final PackageFreezer[] mChildren;
21990
21991        private final boolean mWeFroze;
21992
21993        private final AtomicBoolean mClosed = new AtomicBoolean();
21994        private final CloseGuard mCloseGuard = CloseGuard.get();
21995
21996        /**
21997         * Create and return a stub freezer that doesn't actually do anything,
21998         * typically used when someone requested
21999         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22000         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22001         */
22002        public PackageFreezer() {
22003            mPackageName = null;
22004            mChildren = null;
22005            mWeFroze = false;
22006            mCloseGuard.open("close");
22007        }
22008
22009        public PackageFreezer(String packageName, int userId, String killReason) {
22010            synchronized (mPackages) {
22011                mPackageName = packageName;
22012                mWeFroze = mFrozenPackages.add(mPackageName);
22013
22014                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22015                if (ps != null) {
22016                    killApplication(ps.name, ps.appId, userId, killReason);
22017                }
22018
22019                final PackageParser.Package p = mPackages.get(packageName);
22020                if (p != null && p.childPackages != null) {
22021                    final int N = p.childPackages.size();
22022                    mChildren = new PackageFreezer[N];
22023                    for (int i = 0; i < N; i++) {
22024                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22025                                userId, killReason);
22026                    }
22027                } else {
22028                    mChildren = null;
22029                }
22030            }
22031            mCloseGuard.open("close");
22032        }
22033
22034        @Override
22035        protected void finalize() throws Throwable {
22036            try {
22037                mCloseGuard.warnIfOpen();
22038                close();
22039            } finally {
22040                super.finalize();
22041            }
22042        }
22043
22044        @Override
22045        public void close() {
22046            mCloseGuard.close();
22047            if (mClosed.compareAndSet(false, true)) {
22048                synchronized (mPackages) {
22049                    if (mWeFroze) {
22050                        mFrozenPackages.remove(mPackageName);
22051                    }
22052
22053                    if (mChildren != null) {
22054                        for (PackageFreezer freezer : mChildren) {
22055                            freezer.close();
22056                        }
22057                    }
22058                }
22059            }
22060        }
22061    }
22062
22063    /**
22064     * Verify that given package is currently frozen.
22065     */
22066    private void checkPackageFrozen(String packageName) {
22067        synchronized (mPackages) {
22068            if (!mFrozenPackages.contains(packageName)) {
22069                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22070            }
22071        }
22072    }
22073
22074    @Override
22075    public int movePackage(final String packageName, final String volumeUuid) {
22076        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22077
22078        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22079        final int moveId = mNextMoveId.getAndIncrement();
22080        mHandler.post(new Runnable() {
22081            @Override
22082            public void run() {
22083                try {
22084                    movePackageInternal(packageName, volumeUuid, moveId, user);
22085                } catch (PackageManagerException e) {
22086                    Slog.w(TAG, "Failed to move " + packageName, e);
22087                    mMoveCallbacks.notifyStatusChanged(moveId,
22088                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22089                }
22090            }
22091        });
22092        return moveId;
22093    }
22094
22095    private void movePackageInternal(final String packageName, final String volumeUuid,
22096            final int moveId, UserHandle user) throws PackageManagerException {
22097        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22098        final PackageManager pm = mContext.getPackageManager();
22099
22100        final boolean currentAsec;
22101        final String currentVolumeUuid;
22102        final File codeFile;
22103        final String installerPackageName;
22104        final String packageAbiOverride;
22105        final int appId;
22106        final String seinfo;
22107        final String label;
22108        final int targetSdkVersion;
22109        final PackageFreezer freezer;
22110        final int[] installedUserIds;
22111
22112        // reader
22113        synchronized (mPackages) {
22114            final PackageParser.Package pkg = mPackages.get(packageName);
22115            final PackageSetting ps = mSettings.mPackages.get(packageName);
22116            if (pkg == null || ps == null) {
22117                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22118            }
22119
22120            if (pkg.applicationInfo.isSystemApp()) {
22121                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22122                        "Cannot move system application");
22123            }
22124
22125            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22126            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22127                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22128            if (isInternalStorage && !allow3rdPartyOnInternal) {
22129                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22130                        "3rd party apps are not allowed on internal storage");
22131            }
22132
22133            if (pkg.applicationInfo.isExternalAsec()) {
22134                currentAsec = true;
22135                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22136            } else if (pkg.applicationInfo.isForwardLocked()) {
22137                currentAsec = true;
22138                currentVolumeUuid = "forward_locked";
22139            } else {
22140                currentAsec = false;
22141                currentVolumeUuid = ps.volumeUuid;
22142
22143                final File probe = new File(pkg.codePath);
22144                final File probeOat = new File(probe, "oat");
22145                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22146                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22147                            "Move only supported for modern cluster style installs");
22148                }
22149            }
22150
22151            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22152                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22153                        "Package already moved to " + volumeUuid);
22154            }
22155            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22156                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22157                        "Device admin cannot be moved");
22158            }
22159
22160            if (mFrozenPackages.contains(packageName)) {
22161                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22162                        "Failed to move already frozen package");
22163            }
22164
22165            codeFile = new File(pkg.codePath);
22166            installerPackageName = ps.installerPackageName;
22167            packageAbiOverride = ps.cpuAbiOverrideString;
22168            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22169            seinfo = pkg.applicationInfo.seInfo;
22170            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22171            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22172            freezer = freezePackage(packageName, "movePackageInternal");
22173            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22174        }
22175
22176        final Bundle extras = new Bundle();
22177        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22178        extras.putString(Intent.EXTRA_TITLE, label);
22179        mMoveCallbacks.notifyCreated(moveId, extras);
22180
22181        int installFlags;
22182        final boolean moveCompleteApp;
22183        final File measurePath;
22184
22185        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22186            installFlags = INSTALL_INTERNAL;
22187            moveCompleteApp = !currentAsec;
22188            measurePath = Environment.getDataAppDirectory(volumeUuid);
22189        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22190            installFlags = INSTALL_EXTERNAL;
22191            moveCompleteApp = false;
22192            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22193        } else {
22194            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22195            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22196                    || !volume.isMountedWritable()) {
22197                freezer.close();
22198                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22199                        "Move location not mounted private volume");
22200            }
22201
22202            Preconditions.checkState(!currentAsec);
22203
22204            installFlags = INSTALL_INTERNAL;
22205            moveCompleteApp = true;
22206            measurePath = Environment.getDataAppDirectory(volumeUuid);
22207        }
22208
22209        final PackageStats stats = new PackageStats(null, -1);
22210        synchronized (mInstaller) {
22211            for (int userId : installedUserIds) {
22212                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22213                    freezer.close();
22214                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22215                            "Failed to measure package size");
22216                }
22217            }
22218        }
22219
22220        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22221                + stats.dataSize);
22222
22223        final long startFreeBytes = measurePath.getFreeSpace();
22224        final long sizeBytes;
22225        if (moveCompleteApp) {
22226            sizeBytes = stats.codeSize + stats.dataSize;
22227        } else {
22228            sizeBytes = stats.codeSize;
22229        }
22230
22231        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22232            freezer.close();
22233            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22234                    "Not enough free space to move");
22235        }
22236
22237        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22238
22239        final CountDownLatch installedLatch = new CountDownLatch(1);
22240        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22241            @Override
22242            public void onUserActionRequired(Intent intent) throws RemoteException {
22243                throw new IllegalStateException();
22244            }
22245
22246            @Override
22247            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22248                    Bundle extras) throws RemoteException {
22249                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22250                        + PackageManager.installStatusToString(returnCode, msg));
22251
22252                installedLatch.countDown();
22253                freezer.close();
22254
22255                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22256                switch (status) {
22257                    case PackageInstaller.STATUS_SUCCESS:
22258                        mMoveCallbacks.notifyStatusChanged(moveId,
22259                                PackageManager.MOVE_SUCCEEDED);
22260                        break;
22261                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22262                        mMoveCallbacks.notifyStatusChanged(moveId,
22263                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22264                        break;
22265                    default:
22266                        mMoveCallbacks.notifyStatusChanged(moveId,
22267                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22268                        break;
22269                }
22270            }
22271        };
22272
22273        final MoveInfo move;
22274        if (moveCompleteApp) {
22275            // Kick off a thread to report progress estimates
22276            new Thread() {
22277                @Override
22278                public void run() {
22279                    while (true) {
22280                        try {
22281                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22282                                break;
22283                            }
22284                        } catch (InterruptedException ignored) {
22285                        }
22286
22287                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22288                        final int progress = 10 + (int) MathUtils.constrain(
22289                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22290                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22291                    }
22292                }
22293            }.start();
22294
22295            final String dataAppName = codeFile.getName();
22296            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22297                    dataAppName, appId, seinfo, targetSdkVersion);
22298        } else {
22299            move = null;
22300        }
22301
22302        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22303
22304        final Message msg = mHandler.obtainMessage(INIT_COPY);
22305        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22306        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22307                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22308                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22309                PackageManager.INSTALL_REASON_UNKNOWN);
22310        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22311        msg.obj = params;
22312
22313        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22314                System.identityHashCode(msg.obj));
22315        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22316                System.identityHashCode(msg.obj));
22317
22318        mHandler.sendMessage(msg);
22319    }
22320
22321    @Override
22322    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22323        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22324
22325        final int realMoveId = mNextMoveId.getAndIncrement();
22326        final Bundle extras = new Bundle();
22327        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22328        mMoveCallbacks.notifyCreated(realMoveId, extras);
22329
22330        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22331            @Override
22332            public void onCreated(int moveId, Bundle extras) {
22333                // Ignored
22334            }
22335
22336            @Override
22337            public void onStatusChanged(int moveId, int status, long estMillis) {
22338                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22339            }
22340        };
22341
22342        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22343        storage.setPrimaryStorageUuid(volumeUuid, callback);
22344        return realMoveId;
22345    }
22346
22347    @Override
22348    public int getMoveStatus(int moveId) {
22349        mContext.enforceCallingOrSelfPermission(
22350                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22351        return mMoveCallbacks.mLastStatus.get(moveId);
22352    }
22353
22354    @Override
22355    public void registerMoveCallback(IPackageMoveObserver callback) {
22356        mContext.enforceCallingOrSelfPermission(
22357                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22358        mMoveCallbacks.register(callback);
22359    }
22360
22361    @Override
22362    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22363        mContext.enforceCallingOrSelfPermission(
22364                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22365        mMoveCallbacks.unregister(callback);
22366    }
22367
22368    @Override
22369    public boolean setInstallLocation(int loc) {
22370        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22371                null);
22372        if (getInstallLocation() == loc) {
22373            return true;
22374        }
22375        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22376                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22377            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22378                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22379            return true;
22380        }
22381        return false;
22382   }
22383
22384    @Override
22385    public int getInstallLocation() {
22386        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22387                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22388                PackageHelper.APP_INSTALL_AUTO);
22389    }
22390
22391    /** Called by UserManagerService */
22392    void cleanUpUser(UserManagerService userManager, int userHandle) {
22393        synchronized (mPackages) {
22394            mDirtyUsers.remove(userHandle);
22395            mUserNeedsBadging.delete(userHandle);
22396            mSettings.removeUserLPw(userHandle);
22397            mPendingBroadcasts.remove(userHandle);
22398            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22399            removeUnusedPackagesLPw(userManager, userHandle);
22400        }
22401    }
22402
22403    /**
22404     * We're removing userHandle and would like to remove any downloaded packages
22405     * that are no longer in use by any other user.
22406     * @param userHandle the user being removed
22407     */
22408    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22409        final boolean DEBUG_CLEAN_APKS = false;
22410        int [] users = userManager.getUserIds();
22411        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22412        while (psit.hasNext()) {
22413            PackageSetting ps = psit.next();
22414            if (ps.pkg == null) {
22415                continue;
22416            }
22417            final String packageName = ps.pkg.packageName;
22418            // Skip over if system app
22419            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22420                continue;
22421            }
22422            if (DEBUG_CLEAN_APKS) {
22423                Slog.i(TAG, "Checking package " + packageName);
22424            }
22425            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22426            if (keep) {
22427                if (DEBUG_CLEAN_APKS) {
22428                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22429                }
22430            } else {
22431                for (int i = 0; i < users.length; i++) {
22432                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22433                        keep = true;
22434                        if (DEBUG_CLEAN_APKS) {
22435                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22436                                    + users[i]);
22437                        }
22438                        break;
22439                    }
22440                }
22441            }
22442            if (!keep) {
22443                if (DEBUG_CLEAN_APKS) {
22444                    Slog.i(TAG, "  Removing package " + packageName);
22445                }
22446                mHandler.post(new Runnable() {
22447                    public void run() {
22448                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22449                                userHandle, 0);
22450                    } //end run
22451                });
22452            }
22453        }
22454    }
22455
22456    /** Called by UserManagerService */
22457    void createNewUser(int userId, String[] disallowedPackages) {
22458        synchronized (mInstallLock) {
22459            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22460        }
22461        synchronized (mPackages) {
22462            scheduleWritePackageRestrictionsLocked(userId);
22463            scheduleWritePackageListLocked(userId);
22464            applyFactoryDefaultBrowserLPw(userId);
22465            primeDomainVerificationsLPw(userId);
22466        }
22467    }
22468
22469    void onNewUserCreated(final int userId) {
22470        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22471        // If permission review for legacy apps is required, we represent
22472        // dagerous permissions for such apps as always granted runtime
22473        // permissions to keep per user flag state whether review is needed.
22474        // Hence, if a new user is added we have to propagate dangerous
22475        // permission grants for these legacy apps.
22476        if (mPermissionReviewRequired) {
22477            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22478                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22479        }
22480    }
22481
22482    @Override
22483    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22484        mContext.enforceCallingOrSelfPermission(
22485                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22486                "Only package verification agents can read the verifier device identity");
22487
22488        synchronized (mPackages) {
22489            return mSettings.getVerifierDeviceIdentityLPw();
22490        }
22491    }
22492
22493    @Override
22494    public void setPermissionEnforced(String permission, boolean enforced) {
22495        // TODO: Now that we no longer change GID for storage, this should to away.
22496        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22497                "setPermissionEnforced");
22498        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22499            synchronized (mPackages) {
22500                if (mSettings.mReadExternalStorageEnforced == null
22501                        || mSettings.mReadExternalStorageEnforced != enforced) {
22502                    mSettings.mReadExternalStorageEnforced = enforced;
22503                    mSettings.writeLPr();
22504                }
22505            }
22506            // kill any non-foreground processes so we restart them and
22507            // grant/revoke the GID.
22508            final IActivityManager am = ActivityManager.getService();
22509            if (am != null) {
22510                final long token = Binder.clearCallingIdentity();
22511                try {
22512                    am.killProcessesBelowForeground("setPermissionEnforcement");
22513                } catch (RemoteException e) {
22514                } finally {
22515                    Binder.restoreCallingIdentity(token);
22516                }
22517            }
22518        } else {
22519            throw new IllegalArgumentException("No selective enforcement for " + permission);
22520        }
22521    }
22522
22523    @Override
22524    @Deprecated
22525    public boolean isPermissionEnforced(String permission) {
22526        return true;
22527    }
22528
22529    @Override
22530    public boolean isStorageLow() {
22531        final long token = Binder.clearCallingIdentity();
22532        try {
22533            final DeviceStorageMonitorInternal
22534                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22535            if (dsm != null) {
22536                return dsm.isMemoryLow();
22537            } else {
22538                return false;
22539            }
22540        } finally {
22541            Binder.restoreCallingIdentity(token);
22542        }
22543    }
22544
22545    @Override
22546    public IPackageInstaller getPackageInstaller() {
22547        return mInstallerService;
22548    }
22549
22550    private boolean userNeedsBadging(int userId) {
22551        int index = mUserNeedsBadging.indexOfKey(userId);
22552        if (index < 0) {
22553            final UserInfo userInfo;
22554            final long token = Binder.clearCallingIdentity();
22555            try {
22556                userInfo = sUserManager.getUserInfo(userId);
22557            } finally {
22558                Binder.restoreCallingIdentity(token);
22559            }
22560            final boolean b;
22561            if (userInfo != null && userInfo.isManagedProfile()) {
22562                b = true;
22563            } else {
22564                b = false;
22565            }
22566            mUserNeedsBadging.put(userId, b);
22567            return b;
22568        }
22569        return mUserNeedsBadging.valueAt(index);
22570    }
22571
22572    @Override
22573    public KeySet getKeySetByAlias(String packageName, String alias) {
22574        if (packageName == null || alias == null) {
22575            return null;
22576        }
22577        synchronized(mPackages) {
22578            final PackageParser.Package pkg = mPackages.get(packageName);
22579            if (pkg == null) {
22580                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22581                throw new IllegalArgumentException("Unknown package: " + packageName);
22582            }
22583            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22584            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22585        }
22586    }
22587
22588    @Override
22589    public KeySet getSigningKeySet(String packageName) {
22590        if (packageName == null) {
22591            return null;
22592        }
22593        synchronized(mPackages) {
22594            final PackageParser.Package pkg = mPackages.get(packageName);
22595            if (pkg == null) {
22596                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22597                throw new IllegalArgumentException("Unknown package: " + packageName);
22598            }
22599            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22600                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22601                throw new SecurityException("May not access signing KeySet of other apps.");
22602            }
22603            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22604            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22605        }
22606    }
22607
22608    @Override
22609    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22610        if (packageName == null || ks == null) {
22611            return false;
22612        }
22613        synchronized(mPackages) {
22614            final PackageParser.Package pkg = mPackages.get(packageName);
22615            if (pkg == null) {
22616                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22617                throw new IllegalArgumentException("Unknown package: " + packageName);
22618            }
22619            IBinder ksh = ks.getToken();
22620            if (ksh instanceof KeySetHandle) {
22621                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22622                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22623            }
22624            return false;
22625        }
22626    }
22627
22628    @Override
22629    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22630        if (packageName == null || ks == null) {
22631            return false;
22632        }
22633        synchronized(mPackages) {
22634            final PackageParser.Package pkg = mPackages.get(packageName);
22635            if (pkg == null) {
22636                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22637                throw new IllegalArgumentException("Unknown package: " + packageName);
22638            }
22639            IBinder ksh = ks.getToken();
22640            if (ksh instanceof KeySetHandle) {
22641                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22642                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22643            }
22644            return false;
22645        }
22646    }
22647
22648    private void deletePackageIfUnusedLPr(final String packageName) {
22649        PackageSetting ps = mSettings.mPackages.get(packageName);
22650        if (ps == null) {
22651            return;
22652        }
22653        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22654            // TODO Implement atomic delete if package is unused
22655            // It is currently possible that the package will be deleted even if it is installed
22656            // after this method returns.
22657            mHandler.post(new Runnable() {
22658                public void run() {
22659                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22660                            0, PackageManager.DELETE_ALL_USERS);
22661                }
22662            });
22663        }
22664    }
22665
22666    /**
22667     * Check and throw if the given before/after packages would be considered a
22668     * downgrade.
22669     */
22670    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22671            throws PackageManagerException {
22672        if (after.versionCode < before.mVersionCode) {
22673            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22674                    "Update version code " + after.versionCode + " is older than current "
22675                    + before.mVersionCode);
22676        } else if (after.versionCode == before.mVersionCode) {
22677            if (after.baseRevisionCode < before.baseRevisionCode) {
22678                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22679                        "Update base revision code " + after.baseRevisionCode
22680                        + " is older than current " + before.baseRevisionCode);
22681            }
22682
22683            if (!ArrayUtils.isEmpty(after.splitNames)) {
22684                for (int i = 0; i < after.splitNames.length; i++) {
22685                    final String splitName = after.splitNames[i];
22686                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22687                    if (j != -1) {
22688                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22689                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22690                                    "Update split " + splitName + " revision code "
22691                                    + after.splitRevisionCodes[i] + " is older than current "
22692                                    + before.splitRevisionCodes[j]);
22693                        }
22694                    }
22695                }
22696            }
22697        }
22698    }
22699
22700    private static class MoveCallbacks extends Handler {
22701        private static final int MSG_CREATED = 1;
22702        private static final int MSG_STATUS_CHANGED = 2;
22703
22704        private final RemoteCallbackList<IPackageMoveObserver>
22705                mCallbacks = new RemoteCallbackList<>();
22706
22707        private final SparseIntArray mLastStatus = new SparseIntArray();
22708
22709        public MoveCallbacks(Looper looper) {
22710            super(looper);
22711        }
22712
22713        public void register(IPackageMoveObserver callback) {
22714            mCallbacks.register(callback);
22715        }
22716
22717        public void unregister(IPackageMoveObserver callback) {
22718            mCallbacks.unregister(callback);
22719        }
22720
22721        @Override
22722        public void handleMessage(Message msg) {
22723            final SomeArgs args = (SomeArgs) msg.obj;
22724            final int n = mCallbacks.beginBroadcast();
22725            for (int i = 0; i < n; i++) {
22726                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22727                try {
22728                    invokeCallback(callback, msg.what, args);
22729                } catch (RemoteException ignored) {
22730                }
22731            }
22732            mCallbacks.finishBroadcast();
22733            args.recycle();
22734        }
22735
22736        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22737                throws RemoteException {
22738            switch (what) {
22739                case MSG_CREATED: {
22740                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22741                    break;
22742                }
22743                case MSG_STATUS_CHANGED: {
22744                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22745                    break;
22746                }
22747            }
22748        }
22749
22750        private void notifyCreated(int moveId, Bundle extras) {
22751            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22752
22753            final SomeArgs args = SomeArgs.obtain();
22754            args.argi1 = moveId;
22755            args.arg2 = extras;
22756            obtainMessage(MSG_CREATED, args).sendToTarget();
22757        }
22758
22759        private void notifyStatusChanged(int moveId, int status) {
22760            notifyStatusChanged(moveId, status, -1);
22761        }
22762
22763        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22764            Slog.v(TAG, "Move " + moveId + " status " + status);
22765
22766            final SomeArgs args = SomeArgs.obtain();
22767            args.argi1 = moveId;
22768            args.argi2 = status;
22769            args.arg3 = estMillis;
22770            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22771
22772            synchronized (mLastStatus) {
22773                mLastStatus.put(moveId, status);
22774            }
22775        }
22776    }
22777
22778    private final static class OnPermissionChangeListeners extends Handler {
22779        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22780
22781        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22782                new RemoteCallbackList<>();
22783
22784        public OnPermissionChangeListeners(Looper looper) {
22785            super(looper);
22786        }
22787
22788        @Override
22789        public void handleMessage(Message msg) {
22790            switch (msg.what) {
22791                case MSG_ON_PERMISSIONS_CHANGED: {
22792                    final int uid = msg.arg1;
22793                    handleOnPermissionsChanged(uid);
22794                } break;
22795            }
22796        }
22797
22798        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22799            mPermissionListeners.register(listener);
22800
22801        }
22802
22803        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22804            mPermissionListeners.unregister(listener);
22805        }
22806
22807        public void onPermissionsChanged(int uid) {
22808            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22809                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22810            }
22811        }
22812
22813        private void handleOnPermissionsChanged(int uid) {
22814            final int count = mPermissionListeners.beginBroadcast();
22815            try {
22816                for (int i = 0; i < count; i++) {
22817                    IOnPermissionsChangeListener callback = mPermissionListeners
22818                            .getBroadcastItem(i);
22819                    try {
22820                        callback.onPermissionsChanged(uid);
22821                    } catch (RemoteException e) {
22822                        Log.e(TAG, "Permission listener is dead", e);
22823                    }
22824                }
22825            } finally {
22826                mPermissionListeners.finishBroadcast();
22827            }
22828        }
22829    }
22830
22831    private class PackageManagerInternalImpl extends PackageManagerInternal {
22832        @Override
22833        public void setLocationPackagesProvider(PackagesProvider provider) {
22834            synchronized (mPackages) {
22835                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22836            }
22837        }
22838
22839        @Override
22840        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22841            synchronized (mPackages) {
22842                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22843            }
22844        }
22845
22846        @Override
22847        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22848            synchronized (mPackages) {
22849                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22850            }
22851        }
22852
22853        @Override
22854        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22855            synchronized (mPackages) {
22856                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22857            }
22858        }
22859
22860        @Override
22861        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22862            synchronized (mPackages) {
22863                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22864            }
22865        }
22866
22867        @Override
22868        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22869            synchronized (mPackages) {
22870                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22871            }
22872        }
22873
22874        @Override
22875        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22876            synchronized (mPackages) {
22877                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22878                        packageName, userId);
22879            }
22880        }
22881
22882        @Override
22883        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22884            synchronized (mPackages) {
22885                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22886                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22887                        packageName, userId);
22888            }
22889        }
22890
22891        @Override
22892        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22893            synchronized (mPackages) {
22894                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22895                        packageName, userId);
22896            }
22897        }
22898
22899        @Override
22900        public void setKeepUninstalledPackages(final List<String> packageList) {
22901            Preconditions.checkNotNull(packageList);
22902            List<String> removedFromList = null;
22903            synchronized (mPackages) {
22904                if (mKeepUninstalledPackages != null) {
22905                    final int packagesCount = mKeepUninstalledPackages.size();
22906                    for (int i = 0; i < packagesCount; i++) {
22907                        String oldPackage = mKeepUninstalledPackages.get(i);
22908                        if (packageList != null && packageList.contains(oldPackage)) {
22909                            continue;
22910                        }
22911                        if (removedFromList == null) {
22912                            removedFromList = new ArrayList<>();
22913                        }
22914                        removedFromList.add(oldPackage);
22915                    }
22916                }
22917                mKeepUninstalledPackages = new ArrayList<>(packageList);
22918                if (removedFromList != null) {
22919                    final int removedCount = removedFromList.size();
22920                    for (int i = 0; i < removedCount; i++) {
22921                        deletePackageIfUnusedLPr(removedFromList.get(i));
22922                    }
22923                }
22924            }
22925        }
22926
22927        @Override
22928        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22929            synchronized (mPackages) {
22930                // If we do not support permission review, done.
22931                if (!mPermissionReviewRequired) {
22932                    return false;
22933                }
22934
22935                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22936                if (packageSetting == null) {
22937                    return false;
22938                }
22939
22940                // Permission review applies only to apps not supporting the new permission model.
22941                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22942                    return false;
22943                }
22944
22945                // Legacy apps have the permission and get user consent on launch.
22946                PermissionsState permissionsState = packageSetting.getPermissionsState();
22947                return permissionsState.isPermissionReviewRequired(userId);
22948            }
22949        }
22950
22951        @Override
22952        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22953            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22954        }
22955
22956        @Override
22957        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22958                int userId) {
22959            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22960        }
22961
22962        @Override
22963        public void setDeviceAndProfileOwnerPackages(
22964                int deviceOwnerUserId, String deviceOwnerPackage,
22965                SparseArray<String> profileOwnerPackages) {
22966            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22967                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22968        }
22969
22970        @Override
22971        public boolean isPackageDataProtected(int userId, String packageName) {
22972            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22973        }
22974
22975        @Override
22976        public boolean isPackageEphemeral(int userId, String packageName) {
22977            synchronized (mPackages) {
22978                final PackageSetting ps = mSettings.mPackages.get(packageName);
22979                return ps != null ? ps.getInstantApp(userId) : false;
22980            }
22981        }
22982
22983        @Override
22984        public boolean wasPackageEverLaunched(String packageName, int userId) {
22985            synchronized (mPackages) {
22986                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22987            }
22988        }
22989
22990        @Override
22991        public void grantRuntimePermission(String packageName, String name, int userId,
22992                boolean overridePolicy) {
22993            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22994                    overridePolicy);
22995        }
22996
22997        @Override
22998        public void revokeRuntimePermission(String packageName, String name, int userId,
22999                boolean overridePolicy) {
23000            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23001                    overridePolicy);
23002        }
23003
23004        @Override
23005        public String getNameForUid(int uid) {
23006            return PackageManagerService.this.getNameForUid(uid);
23007        }
23008
23009        @Override
23010        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23011                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23012            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23013                    responseObj, origIntent, resolvedType, callingPackage, userId);
23014        }
23015
23016        @Override
23017        public void grantEphemeralAccess(int userId, Intent intent,
23018                int targetAppId, int ephemeralAppId) {
23019            synchronized (mPackages) {
23020                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23021                        targetAppId, ephemeralAppId);
23022            }
23023        }
23024
23025        @Override
23026        public boolean isInstantAppInstallerComponent(ComponentName component) {
23027            synchronized (mPackages) {
23028                return component != null && component.equals(mInstantAppInstallerComponent);
23029            }
23030        }
23031
23032        @Override
23033        public void pruneInstantApps() {
23034            synchronized (mPackages) {
23035                mInstantAppRegistry.pruneInstantAppsLPw();
23036            }
23037        }
23038
23039        @Override
23040        public String getSetupWizardPackageName() {
23041            return mSetupWizardPackage;
23042        }
23043
23044        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23045            if (policy != null) {
23046                mExternalSourcesPolicy = policy;
23047            }
23048        }
23049
23050        @Override
23051        public boolean isPackagePersistent(String packageName) {
23052            synchronized (mPackages) {
23053                PackageParser.Package pkg = mPackages.get(packageName);
23054                return pkg != null
23055                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23056                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23057                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23058                        : false;
23059            }
23060        }
23061
23062        @Override
23063        public List<PackageInfo> getOverlayPackages(int userId) {
23064            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23065            synchronized (mPackages) {
23066                for (PackageParser.Package p : mPackages.values()) {
23067                    if (p.mOverlayTarget != null) {
23068                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23069                        if (pkg != null) {
23070                            overlayPackages.add(pkg);
23071                        }
23072                    }
23073                }
23074            }
23075            return overlayPackages;
23076        }
23077
23078        @Override
23079        public List<String> getTargetPackageNames(int userId) {
23080            List<String> targetPackages = new ArrayList<>();
23081            synchronized (mPackages) {
23082                for (PackageParser.Package p : mPackages.values()) {
23083                    if (p.mOverlayTarget == null) {
23084                        targetPackages.add(p.packageName);
23085                    }
23086                }
23087            }
23088            return targetPackages;
23089        }
23090
23091        @Override
23092        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23093                @Nullable List<String> overlayPackageNames) {
23094            synchronized (mPackages) {
23095                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23096                    Slog.e(TAG, "failed to find package " + targetPackageName);
23097                    return false;
23098                }
23099
23100                ArrayList<String> paths = null;
23101                if (overlayPackageNames != null) {
23102                    final int N = overlayPackageNames.size();
23103                    paths = new ArrayList<>(N);
23104                    for (int i = 0; i < N; i++) {
23105                        final String packageName = overlayPackageNames.get(i);
23106                        final PackageParser.Package pkg = mPackages.get(packageName);
23107                        if (pkg == null) {
23108                            Slog.e(TAG, "failed to find package " + packageName);
23109                            return false;
23110                        }
23111                        paths.add(pkg.baseCodePath);
23112                    }
23113                }
23114
23115                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23116                    mEnabledOverlayPaths.get(userId);
23117                if (userSpecificOverlays == null) {
23118                    userSpecificOverlays = new ArrayMap<>();
23119                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23120                }
23121
23122                if (paths != null && paths.size() > 0) {
23123                    userSpecificOverlays.put(targetPackageName, paths);
23124                } else {
23125                    userSpecificOverlays.remove(targetPackageName);
23126                }
23127                return true;
23128            }
23129        }
23130
23131        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23132                int flags, int userId) {
23133            return resolveIntentInternal(
23134                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23135        }
23136    }
23137
23138    @Override
23139    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23140        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23141        synchronized (mPackages) {
23142            final long identity = Binder.clearCallingIdentity();
23143            try {
23144                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23145                        packageNames, userId);
23146            } finally {
23147                Binder.restoreCallingIdentity(identity);
23148            }
23149        }
23150    }
23151
23152    @Override
23153    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23154        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23155        synchronized (mPackages) {
23156            final long identity = Binder.clearCallingIdentity();
23157            try {
23158                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23159                        packageNames, userId);
23160            } finally {
23161                Binder.restoreCallingIdentity(identity);
23162            }
23163        }
23164    }
23165
23166    private static void enforceSystemOrPhoneCaller(String tag) {
23167        int callingUid = Binder.getCallingUid();
23168        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23169            throw new SecurityException(
23170                    "Cannot call " + tag + " from UID " + callingUid);
23171        }
23172    }
23173
23174    boolean isHistoricalPackageUsageAvailable() {
23175        return mPackageUsage.isHistoricalPackageUsageAvailable();
23176    }
23177
23178    /**
23179     * Return a <b>copy</b> of the collection of packages known to the package manager.
23180     * @return A copy of the values of mPackages.
23181     */
23182    Collection<PackageParser.Package> getPackages() {
23183        synchronized (mPackages) {
23184            return new ArrayList<>(mPackages.values());
23185        }
23186    }
23187
23188    /**
23189     * Logs process start information (including base APK hash) to the security log.
23190     * @hide
23191     */
23192    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23193            String apkFile, int pid) {
23194        if (!SecurityLog.isLoggingEnabled()) {
23195            return;
23196        }
23197        Bundle data = new Bundle();
23198        data.putLong("startTimestamp", System.currentTimeMillis());
23199        data.putString("processName", processName);
23200        data.putInt("uid", uid);
23201        data.putString("seinfo", seinfo);
23202        data.putString("apkFile", apkFile);
23203        data.putInt("pid", pid);
23204        Message msg = mProcessLoggingHandler.obtainMessage(
23205                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23206        msg.setData(data);
23207        mProcessLoggingHandler.sendMessage(msg);
23208    }
23209
23210    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23211        return mCompilerStats.getPackageStats(pkgName);
23212    }
23213
23214    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23215        return getOrCreateCompilerPackageStats(pkg.packageName);
23216    }
23217
23218    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23219        return mCompilerStats.getOrCreatePackageStats(pkgName);
23220    }
23221
23222    public void deleteCompilerPackageStats(String pkgName) {
23223        mCompilerStats.deletePackageStats(pkgName);
23224    }
23225
23226    @Override
23227    public int getInstallReason(String packageName, int userId) {
23228        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23229                true /* requireFullPermission */, false /* checkShell */,
23230                "get install reason");
23231        synchronized (mPackages) {
23232            final PackageSetting ps = mSettings.mPackages.get(packageName);
23233            if (ps != null) {
23234                return ps.getInstallReason(userId);
23235            }
23236        }
23237        return PackageManager.INSTALL_REASON_UNKNOWN;
23238    }
23239
23240    @Override
23241    public boolean canRequestPackageInstalls(String packageName, int userId) {
23242        int callingUid = Binder.getCallingUid();
23243        int uid = getPackageUid(packageName, 0, userId);
23244        if (callingUid != uid && callingUid != Process.ROOT_UID
23245                && callingUid != Process.SYSTEM_UID) {
23246            throw new SecurityException(
23247                    "Caller uid " + callingUid + " does not own package " + packageName);
23248        }
23249        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23250        if (info == null) {
23251            return false;
23252        }
23253        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23254            throw new UnsupportedOperationException(
23255                    "Operation only supported on apps targeting Android O or higher");
23256        }
23257        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23258        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23259        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23260            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23261        }
23262        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23263            return false;
23264        }
23265        if (mExternalSourcesPolicy != null) {
23266            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23267            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23268                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23269            }
23270        }
23271        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23272    }
23273
23274    @Override
23275    public ComponentName getInstantAppResolverSettingsComponent() {
23276        return mInstantAppResolverSettingsComponent;
23277    }
23278}
23279