PackageManagerService.java revision 50979d14f913b97852c9e39b3b85c555988760f5
138a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin/*
24eb5d79c45383e8538fc8b545f2ea3e5ae980d86Dmitry V. Levin * Copyright (C) 2006 The Android Open Source Project
338a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin *
438a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin * Licensed under the Apache License, Version 2.0 (the "License");
538a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin * you may not use this file except in compliance with the License.
638a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin * You may obtain a copy of the License at
738a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin *
838a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin *      http://www.apache.org/licenses/LICENSE-2.0
938a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin *
1038a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin * Unless required by applicable law or agreed to in writing, software
1138a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin * distributed under the License is distributed on an "AS IS" BASIS,
1238a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1338a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin * See the License for the specific language governing permissions and
1438a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin * limitations under the License.
1538a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin */
1638a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin
1738a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levinpackage com.android.server.pm;
1838a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levin
1938a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levinimport static android.Manifest.permission.DELETE_PACKAGES;
2038a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levinimport static android.Manifest.permission.INSTALL_PACKAGES;
2138a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levinimport static android.Manifest.permission.READ_EXTERNAL_STORAGE;
2238a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levinimport static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
2338a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levinimport static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
2438a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levinimport static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
2538a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levinimport static android.Manifest.permission.WRITE_MEDIA_STORAGE;
2638a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levinimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
2738a34c9349267c99ce1ddbd0b6e985147415d355Dmitry V. Levinimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
284eb5d79c45383e8538fc8b545f2ea3e5ae980d86Dmitry V. Levinimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
2948321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
3048321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
3148321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport static android.content.pm.PackageManager.DELETE_KEEP_DATA;
3248321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3348321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3448321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3548321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
364eb5d79c45383e8538fc8b545f2ea3e5ae980d86Dmitry V. Levinimport static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3748321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
384eb5d79c45383e8538fc8b545f2ea3e5ae980d86Dmitry V. Levinimport static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
3948321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport static android.content.pm.PackageManager.INSTALL_EXTERNAL;
404eb5d79c45383e8538fc8b545f2ea3e5ae980d86Dmitry V. Levinimport static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4148321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
4248321344d7c6f1af5326b31131b3f57da57e4203Dmitry V. Levinimport 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_EPHEMERAL_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.ComponentInfo;
130import android.content.pm.InstantAppInfo;
131import android.content.pm.EphemeralRequest;
132import android.content.pm.EphemeralResolveInfo;
133import android.content.pm.EphemeralResponse;
134import android.content.pm.FallbackCategoryProvider;
135import android.content.pm.FeatureInfo;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.graphics.Bitmap;
175import android.hardware.display.DisplayManager;
176import android.net.Uri;
177import android.os.Binder;
178import android.os.Build;
179import android.os.Bundle;
180import android.os.Debug;
181import android.os.Environment;
182import android.os.Environment.UserEnvironment;
183import android.os.FileUtils;
184import android.os.Handler;
185import android.os.IBinder;
186import android.os.Looper;
187import android.os.Message;
188import android.os.Parcel;
189import android.os.ParcelFileDescriptor;
190import android.os.PatternMatcher;
191import android.os.Process;
192import android.os.RemoteCallbackList;
193import android.os.RemoteException;
194import android.os.ResultReceiver;
195import android.os.SELinux;
196import android.os.ServiceManager;
197import android.os.ShellCallback;
198import android.os.SystemClock;
199import android.os.SystemProperties;
200import android.os.Trace;
201import android.os.UserHandle;
202import android.os.UserManager;
203import android.os.UserManagerInternal;
204import android.os.storage.IStorageManager;
205import android.os.storage.StorageManagerInternal;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.VolumeInfo;
209import android.os.storage.VolumeRecord;
210import android.provider.Settings.Global;
211import android.provider.Settings.Secure;
212import android.security.KeyStore;
213import android.security.SystemKeyStore;
214import android.system.ErrnoException;
215import android.system.Os;
216import android.text.TextUtils;
217import android.text.format.DateUtils;
218import android.util.ArrayMap;
219import android.util.ArraySet;
220import android.util.Base64;
221import android.util.DisplayMetrics;
222import android.util.EventLog;
223import android.util.ExceptionUtils;
224import android.util.Log;
225import android.util.LogPrinter;
226import android.util.MathUtils;
227import android.util.PackageUtils;
228import android.util.Pair;
229import android.util.PrintStreamPrinter;
230import android.util.Slog;
231import android.util.SparseArray;
232import android.util.SparseBooleanArray;
233import android.util.SparseIntArray;
234import android.util.Xml;
235import android.util.jar.StrictJarFile;
236import android.view.Display;
237
238import com.android.internal.R;
239import com.android.internal.annotations.GuardedBy;
240import com.android.internal.app.IMediaContainerService;
241import com.android.internal.app.ResolverActivity;
242import com.android.internal.content.NativeLibraryHelper;
243import com.android.internal.content.PackageHelper;
244import com.android.internal.logging.MetricsLogger;
245import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
246import com.android.internal.os.IParcelFileDescriptorFactory;
247import com.android.internal.os.RoSystemProperties;
248import com.android.internal.os.SomeArgs;
249import com.android.internal.os.Zygote;
250import com.android.internal.telephony.CarrierAppUtils;
251import com.android.internal.util.ArrayUtils;
252import com.android.internal.util.FastPrintWriter;
253import com.android.internal.util.FastXmlSerializer;
254import com.android.internal.util.IndentingPrintWriter;
255import com.android.internal.util.Preconditions;
256import com.android.internal.util.XmlUtils;
257import com.android.server.AttributeCache;
258import com.android.server.BackgroundDexOptJobService;
259import com.android.server.EventLogTags;
260import com.android.server.FgThread;
261import com.android.server.IntentResolver;
262import com.android.server.LocalServices;
263import com.android.server.ServiceThread;
264import com.android.server.SystemConfig;
265import com.android.server.Watchdog;
266import com.android.server.net.NetworkPolicyManagerInternal;
267import com.android.server.pm.Installer.InstallerException;
268import com.android.server.pm.PermissionsState.PermissionState;
269import com.android.server.pm.Settings.DatabaseVersion;
270import com.android.server.pm.Settings.VersionInfo;
271import com.android.server.pm.dex.DexManager;
272import com.android.server.storage.DeviceStorageMonitorInternal;
273
274import dalvik.system.CloseGuard;
275import dalvik.system.DexFile;
276import dalvik.system.VMRuntime;
277
278import libcore.io.IoUtils;
279import libcore.util.EmptyArray;
280
281import org.xmlpull.v1.XmlPullParser;
282import org.xmlpull.v1.XmlPullParserException;
283import org.xmlpull.v1.XmlSerializer;
284
285import java.io.BufferedOutputStream;
286import java.io.BufferedReader;
287import java.io.ByteArrayInputStream;
288import java.io.ByteArrayOutputStream;
289import java.io.File;
290import java.io.FileDescriptor;
291import java.io.FileInputStream;
292import java.io.FileNotFoundException;
293import java.io.FileOutputStream;
294import java.io.FileReader;
295import java.io.FilenameFilter;
296import java.io.IOException;
297import java.io.PrintWriter;
298import java.nio.charset.StandardCharsets;
299import java.security.DigestInputStream;
300import java.security.MessageDigest;
301import java.security.NoSuchAlgorithmException;
302import java.security.PublicKey;
303import java.security.SecureRandom;
304import java.security.cert.Certificate;
305import java.security.cert.CertificateEncodingException;
306import java.security.cert.CertificateException;
307import java.text.SimpleDateFormat;
308import java.util.ArrayList;
309import java.util.Arrays;
310import java.util.Collection;
311import java.util.Collections;
312import java.util.Comparator;
313import java.util.Date;
314import java.util.HashSet;
315import java.util.HashMap;
316import java.util.Iterator;
317import java.util.List;
318import java.util.Map;
319import java.util.Objects;
320import java.util.Set;
321import java.util.concurrent.CountDownLatch;
322import java.util.concurrent.TimeUnit;
323import java.util.concurrent.atomic.AtomicBoolean;
324import java.util.concurrent.atomic.AtomicInteger;
325
326/**
327 * Keep track of all those APKs everywhere.
328 * <p>
329 * Internally there are two important locks:
330 * <ul>
331 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
332 * and other related state. It is a fine-grained lock that should only be held
333 * momentarily, as it's one of the most contended locks in the system.
334 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
335 * operations typically involve heavy lifting of application data on disk. Since
336 * {@code installd} is single-threaded, and it's operations can often be slow,
337 * this lock should never be acquired while already holding {@link #mPackages}.
338 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
339 * holding {@link #mInstallLock}.
340 * </ul>
341 * Many internal methods rely on the caller to hold the appropriate locks, and
342 * this contract is expressed through method name suffixes:
343 * <ul>
344 * <li>fooLI(): the caller must hold {@link #mInstallLock}
345 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
346 * being modified must be frozen
347 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
348 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
349 * </ul>
350 * <p>
351 * Because this class is very central to the platform's security; please run all
352 * CTS and unit tests whenever making modifications:
353 *
354 * <pre>
355 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
356 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
357 * </pre>
358 */
359public class PackageManagerService extends IPackageManager.Stub {
360    static final String TAG = "PackageManager";
361    static final boolean DEBUG_SETTINGS = false;
362    static final boolean DEBUG_PREFERRED = false;
363    static final boolean DEBUG_UPGRADE = false;
364    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
365    private static final boolean DEBUG_BACKUP = false;
366    private static final boolean DEBUG_INSTALL = false;
367    private static final boolean DEBUG_REMOVE = false;
368    private static final boolean DEBUG_BROADCASTS = false;
369    private static final boolean DEBUG_SHOW_INFO = false;
370    private static final boolean DEBUG_PACKAGE_INFO = false;
371    private static final boolean DEBUG_INTENT_MATCHING = false;
372    private static final boolean DEBUG_PACKAGE_SCANNING = false;
373    private static final boolean DEBUG_VERIFY = false;
374    private static final boolean DEBUG_FILTERS = false;
375
376    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
377    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
378    // user, but by default initialize to this.
379    public static final boolean DEBUG_DEXOPT = false;
380
381    private static final boolean DEBUG_ABI_SELECTION = false;
382    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
383    private static final boolean DEBUG_TRIAGED_MISSING = false;
384    private static final boolean DEBUG_APP_DATA = false;
385
386    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
387    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
388
389    private static final boolean DISABLE_EPHEMERAL_APPS = false;
390    private static final boolean HIDE_EPHEMERAL_APIS = false;
391
392    private static final boolean ENABLE_QUOTA =
393            SystemProperties.getBoolean("persist.fw.quota", false);
394
395    private static final int RADIO_UID = Process.PHONE_UID;
396    private static final int LOG_UID = Process.LOG_UID;
397    private static final int NFC_UID = Process.NFC_UID;
398    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
399    private static final int SHELL_UID = Process.SHELL_UID;
400
401    // Cap the size of permission trees that 3rd party apps can define
402    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
403
404    // Suffix used during package installation when copying/moving
405    // package apks to install directory.
406    private static final String INSTALL_PACKAGE_SUFFIX = "-";
407
408    static final int SCAN_NO_DEX = 1<<1;
409    static final int SCAN_FORCE_DEX = 1<<2;
410    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
411    static final int SCAN_NEW_INSTALL = 1<<4;
412    static final int SCAN_UPDATE_TIME = 1<<5;
413    static final int SCAN_BOOTING = 1<<6;
414    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
415    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
416    static final int SCAN_REPLACING = 1<<9;
417    static final int SCAN_REQUIRE_KNOWN = 1<<10;
418    static final int SCAN_MOVE = 1<<11;
419    static final int SCAN_INITIAL = 1<<12;
420    static final int SCAN_CHECK_ONLY = 1<<13;
421    static final int SCAN_DONT_KILL_APP = 1<<14;
422    static final int SCAN_IGNORE_FROZEN = 1<<15;
423    static final int REMOVE_CHATTY = 1<<16;
424    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
425
426    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
427
428    private static final int[] EMPTY_INT_ARRAY = new int[0];
429
430    /**
431     * Timeout (in milliseconds) after which the watchdog should declare that
432     * our handler thread is wedged.  The usual default for such things is one
433     * minute but we sometimes do very lengthy I/O operations on this thread,
434     * such as installing multi-gigabyte applications, so ours needs to be longer.
435     */
436    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
437
438    /**
439     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
440     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
441     * settings entry if available, otherwise we use the hardcoded default.  If it's been
442     * more than this long since the last fstrim, we force one during the boot sequence.
443     *
444     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
445     * one gets run at the next available charging+idle time.  This final mandatory
446     * no-fstrim check kicks in only of the other scheduling criteria is never met.
447     */
448    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
449
450    /**
451     * Whether verification is enabled by default.
452     */
453    private static final boolean DEFAULT_VERIFY_ENABLE = true;
454
455    /**
456     * The default maximum time to wait for the verification agent to return in
457     * milliseconds.
458     */
459    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
460
461    /**
462     * The default response for package verification timeout.
463     *
464     * This can be either PackageManager.VERIFICATION_ALLOW or
465     * PackageManager.VERIFICATION_REJECT.
466     */
467    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
468
469    static final String PLATFORM_PACKAGE_NAME = "android";
470
471    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
472
473    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
474            DEFAULT_CONTAINER_PACKAGE,
475            "com.android.defcontainer.DefaultContainerService");
476
477    private static final String KILL_APP_REASON_GIDS_CHANGED =
478            "permission grant or revoke changed gids";
479
480    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
481            "permissions revoked";
482
483    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
484
485    private static final String PACKAGE_SCHEME = "package";
486
487    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
488    /**
489     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
490     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
491     * VENDOR_OVERLAY_DIR.
492     */
493    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
494    /**
495     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
496     * is in VENDOR_OVERLAY_THEME_PROPERTY.
497     */
498    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
499            = "persist.vendor.overlay.theme";
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_NON_SYSTEM_LIBRARY = 5;
541    public static final int REASON_SHARED_APK = 6;
542    public static final int REASON_FORCED_DEXOPT = 7;
543    public static final int REASON_CORE_APP = 8;
544
545    public static final int REASON_LAST = REASON_CORE_APP;
546
547    /** Special library name that skips shared libraries check during compilation. */
548    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
549
550    /** All dangerous permission names in the same order as the events in MetricsEvent */
551    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
552            Manifest.permission.READ_CALENDAR,
553            Manifest.permission.WRITE_CALENDAR,
554            Manifest.permission.CAMERA,
555            Manifest.permission.READ_CONTACTS,
556            Manifest.permission.WRITE_CONTACTS,
557            Manifest.permission.GET_ACCOUNTS,
558            Manifest.permission.ACCESS_FINE_LOCATION,
559            Manifest.permission.ACCESS_COARSE_LOCATION,
560            Manifest.permission.RECORD_AUDIO,
561            Manifest.permission.READ_PHONE_STATE,
562            Manifest.permission.CALL_PHONE,
563            Manifest.permission.READ_CALL_LOG,
564            Manifest.permission.WRITE_CALL_LOG,
565            Manifest.permission.ADD_VOICEMAIL,
566            Manifest.permission.USE_SIP,
567            Manifest.permission.PROCESS_OUTGOING_CALLS,
568            Manifest.permission.READ_CELL_BROADCASTS,
569            Manifest.permission.BODY_SENSORS,
570            Manifest.permission.SEND_SMS,
571            Manifest.permission.RECEIVE_SMS,
572            Manifest.permission.READ_SMS,
573            Manifest.permission.RECEIVE_WAP_PUSH,
574            Manifest.permission.RECEIVE_MMS,
575            Manifest.permission.READ_EXTERNAL_STORAGE,
576            Manifest.permission.WRITE_EXTERNAL_STORAGE,
577            Manifest.permission.READ_PHONE_NUMBER);
578
579
580    /**
581     * Version number for the package parser cache. Increment this whenever the format or
582     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
583     */
584    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
585
586    /**
587     * Whether the package parser cache is enabled.
588     */
589    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
590
591    final ServiceThread mHandlerThread;
592
593    final PackageHandler mHandler;
594
595    private final ProcessLoggingHandler mProcessLoggingHandler;
596
597    /**
598     * Messages for {@link #mHandler} that need to wait for system ready before
599     * being dispatched.
600     */
601    private ArrayList<Message> mPostSystemReadyMessages;
602
603    final int mSdkVersion = Build.VERSION.SDK_INT;
604
605    final Context mContext;
606    final boolean mFactoryTest;
607    final boolean mOnlyCore;
608    final DisplayMetrics mMetrics;
609    final int mDefParseFlags;
610    final String[] mSeparateProcesses;
611    final boolean mIsUpgrade;
612    final boolean mIsPreNUpgrade;
613    final boolean mIsPreNMR1Upgrade;
614
615    @GuardedBy("mPackages")
616    private boolean mDexOptDialogShown;
617
618    /** The location for ASEC container files on internal storage. */
619    final String mAsecInternalPath;
620
621    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
622    // LOCK HELD.  Can be called with mInstallLock held.
623    @GuardedBy("mInstallLock")
624    final Installer mInstaller;
625
626    /** Directory where installed third-party apps stored */
627    final File mAppInstallDir;
628    final File mEphemeralInstallDir;
629
630    /**
631     * Directory to which applications installed internally have their
632     * 32 bit native libraries copied.
633     */
634    private File mAppLib32InstallDir;
635
636    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
637    // apps.
638    final File mDrmAppPrivateInstallDir;
639
640    // ----------------------------------------------------------------
641
642    // Lock for state used when installing and doing other long running
643    // operations.  Methods that must be called with this lock held have
644    // the suffix "LI".
645    final Object mInstallLock = new Object();
646
647    // ----------------------------------------------------------------
648
649    // Keys are String (package name), values are Package.  This also serves
650    // as the lock for the global state.  Methods that must be called with
651    // this lock held have the prefix "LP".
652    @GuardedBy("mPackages")
653    final ArrayMap<String, PackageParser.Package> mPackages =
654            new ArrayMap<String, PackageParser.Package>();
655
656    final ArrayMap<String, Set<String>> mKnownCodebase =
657            new ArrayMap<String, Set<String>>();
658
659    // Tracks available target package names -> overlay package paths.
660    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
661        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
662
663    /**
664     * Tracks new system packages [received in an OTA] that we expect to
665     * find updated user-installed versions. Keys are package name, values
666     * are package location.
667     */
668    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
669    /**
670     * Tracks high priority intent filters for protected actions. During boot, certain
671     * filter actions are protected and should never be allowed to have a high priority
672     * intent filter for them. However, there is one, and only one exception -- the
673     * setup wizard. It must be able to define a high priority intent filter for these
674     * actions to ensure there are no escapes from the wizard. We need to delay processing
675     * of these during boot as we need to look at all of the system packages in order
676     * to know which component is the setup wizard.
677     */
678    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
679    /**
680     * Whether or not processing protected filters should be deferred.
681     */
682    private boolean mDeferProtectedFilters = true;
683
684    /**
685     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
686     */
687    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
688    /**
689     * Whether or not system app permissions should be promoted from install to runtime.
690     */
691    boolean mPromoteSystemApps;
692
693    @GuardedBy("mPackages")
694    final Settings mSettings;
695
696    /**
697     * Set of package names that are currently "frozen", which means active
698     * surgery is being done on the code/data for that package. The platform
699     * will refuse to launch frozen packages to avoid race conditions.
700     *
701     * @see PackageFreezer
702     */
703    @GuardedBy("mPackages")
704    final ArraySet<String> mFrozenPackages = new ArraySet<>();
705
706    final ProtectedPackages mProtectedPackages;
707
708    boolean mFirstBoot;
709
710    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
711
712    // System configuration read by SystemConfig.
713    final int[] mGlobalGids;
714    final SparseArray<ArraySet<String>> mSystemPermissions;
715    @GuardedBy("mAvailableFeatures")
716    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
717
718    // If mac_permissions.xml was found for seinfo labeling.
719    boolean mFoundPolicyFile;
720
721    private final InstantAppRegistry mInstantAppRegistry;
722
723    public static final class SharedLibraryEntry {
724        public final String path;
725        public final String apk;
726        public final SharedLibraryInfo info;
727
728        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
729                String declaringPackageName, int declaringPackageVersionCode) {
730            path = _path;
731            apk = _apk;
732            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
733                    declaringPackageName, declaringPackageVersionCode), null);
734        }
735    }
736
737    // Currently known shared libraries.
738    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
739    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
740            new ArrayMap<>();
741
742    // All available activities, for your resolving pleasure.
743    final ActivityIntentResolver mActivities =
744            new ActivityIntentResolver();
745
746    // All available receivers, for your resolving pleasure.
747    final ActivityIntentResolver mReceivers =
748            new ActivityIntentResolver();
749
750    // All available services, for your resolving pleasure.
751    final ServiceIntentResolver mServices = new ServiceIntentResolver();
752
753    // All available providers, for your resolving pleasure.
754    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
755
756    // Mapping from provider base names (first directory in content URI codePath)
757    // to the provider information.
758    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
759            new ArrayMap<String, PackageParser.Provider>();
760
761    // Mapping from instrumentation class names to info about them.
762    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
763            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
764
765    // Mapping from permission names to info about them.
766    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
767            new ArrayMap<String, PackageParser.PermissionGroup>();
768
769    // Packages whose data we have transfered into another package, thus
770    // should no longer exist.
771    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
772
773    // Broadcast actions that are only available to the system.
774    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
775
776    /** List of packages waiting for verification. */
777    final SparseArray<PackageVerificationState> mPendingVerification
778            = new SparseArray<PackageVerificationState>();
779
780    /** Set of packages associated with each app op permission. */
781    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
782
783    final PackageInstallerService mInstallerService;
784
785    private final PackageDexOptimizer mPackageDexOptimizer;
786    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
787    // is used by other apps).
788    private final DexManager mDexManager;
789
790    private AtomicInteger mNextMoveId = new AtomicInteger();
791    private final MoveCallbacks mMoveCallbacks;
792
793    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
794
795    // Cache of users who need badging.
796    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
797
798    /** Token for keys in mPendingVerification. */
799    private int mPendingVerificationToken = 0;
800
801    volatile boolean mSystemReady;
802    volatile boolean mSafeMode;
803    volatile boolean mHasSystemUidErrors;
804
805    ApplicationInfo mAndroidApplication;
806    final ActivityInfo mResolveActivity = new ActivityInfo();
807    final ResolveInfo mResolveInfo = new ResolveInfo();
808    ComponentName mResolveComponentName;
809    PackageParser.Package mPlatformPackage;
810    ComponentName mCustomResolverComponentName;
811
812    boolean mResolverReplaced = false;
813
814    private final @Nullable ComponentName mIntentFilterVerifierComponent;
815    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
816
817    private int mIntentFilterVerificationToken = 0;
818
819    /** The service connection to the ephemeral resolver */
820    final EphemeralResolverConnection mEphemeralResolverConnection;
821
822    /** Component used to install ephemeral applications */
823    ComponentName mEphemeralInstallerComponent;
824    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
825    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
826
827    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
828            = new SparseArray<IntentFilterVerificationState>();
829
830    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
831
832    // List of packages names to keep cached, even if they are uninstalled for all users
833    private List<String> mKeepUninstalledPackages;
834
835    private UserManagerInternal mUserManagerInternal;
836
837    private File mCacheDir;
838
839    private static class IFVerificationParams {
840        PackageParser.Package pkg;
841        boolean replacing;
842        int userId;
843        int verifierUid;
844
845        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
846                int _userId, int _verifierUid) {
847            pkg = _pkg;
848            replacing = _replacing;
849            userId = _userId;
850            replacing = _replacing;
851            verifierUid = _verifierUid;
852        }
853    }
854
855    private interface IntentFilterVerifier<T extends IntentFilter> {
856        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
857                                               T filter, String packageName);
858        void startVerifications(int userId);
859        void receiveVerificationResponse(int verificationId);
860    }
861
862    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
863        private Context mContext;
864        private ComponentName mIntentFilterVerifierComponent;
865        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
866
867        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
868            mContext = context;
869            mIntentFilterVerifierComponent = verifierComponent;
870        }
871
872        private String getDefaultScheme() {
873            return IntentFilter.SCHEME_HTTPS;
874        }
875
876        @Override
877        public void startVerifications(int userId) {
878            // Launch verifications requests
879            int count = mCurrentIntentFilterVerifications.size();
880            for (int n=0; n<count; n++) {
881                int verificationId = mCurrentIntentFilterVerifications.get(n);
882                final IntentFilterVerificationState ivs =
883                        mIntentFilterVerificationStates.get(verificationId);
884
885                String packageName = ivs.getPackageName();
886
887                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
888                final int filterCount = filters.size();
889                ArraySet<String> domainsSet = new ArraySet<>();
890                for (int m=0; m<filterCount; m++) {
891                    PackageParser.ActivityIntentInfo filter = filters.get(m);
892                    domainsSet.addAll(filter.getHostsList());
893                }
894                synchronized (mPackages) {
895                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
896                            packageName, domainsSet) != null) {
897                        scheduleWriteSettingsLocked();
898                    }
899                }
900                sendVerificationRequest(userId, verificationId, ivs);
901            }
902            mCurrentIntentFilterVerifications.clear();
903        }
904
905        private void sendVerificationRequest(int userId, int verificationId,
906                IntentFilterVerificationState ivs) {
907
908            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
909            verificationIntent.putExtra(
910                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
911                    verificationId);
912            verificationIntent.putExtra(
913                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
914                    getDefaultScheme());
915            verificationIntent.putExtra(
916                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
917                    ivs.getHostsString());
918            verificationIntent.putExtra(
919                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
920                    ivs.getPackageName());
921            verificationIntent.setComponent(mIntentFilterVerifierComponent);
922            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
923
924            UserHandle user = new UserHandle(userId);
925            mContext.sendBroadcastAsUser(verificationIntent, user);
926            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
927                    "Sending IntentFilter verification broadcast");
928        }
929
930        public void receiveVerificationResponse(int verificationId) {
931            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
932
933            final boolean verified = ivs.isVerified();
934
935            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
936            final int count = filters.size();
937            if (DEBUG_DOMAIN_VERIFICATION) {
938                Slog.i(TAG, "Received verification response " + verificationId
939                        + " for " + count + " filters, verified=" + verified);
940            }
941            for (int n=0; n<count; n++) {
942                PackageParser.ActivityIntentInfo filter = filters.get(n);
943                filter.setVerified(verified);
944
945                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
946                        + " verified with result:" + verified + " and hosts:"
947                        + ivs.getHostsString());
948            }
949
950            mIntentFilterVerificationStates.remove(verificationId);
951
952            final String packageName = ivs.getPackageName();
953            IntentFilterVerificationInfo ivi = null;
954
955            synchronized (mPackages) {
956                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
957            }
958            if (ivi == null) {
959                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
960                        + verificationId + " packageName:" + packageName);
961                return;
962            }
963            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
964                    "Updating IntentFilterVerificationInfo for package " + packageName
965                            +" verificationId:" + verificationId);
966
967            synchronized (mPackages) {
968                if (verified) {
969                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
970                } else {
971                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
972                }
973                scheduleWriteSettingsLocked();
974
975                final int userId = ivs.getUserId();
976                if (userId != UserHandle.USER_ALL) {
977                    final int userStatus =
978                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
979
980                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
981                    boolean needUpdate = false;
982
983                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
984                    // already been set by the User thru the Disambiguation dialog
985                    switch (userStatus) {
986                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
987                            if (verified) {
988                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
989                            } else {
990                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
991                            }
992                            needUpdate = true;
993                            break;
994
995                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
996                            if (verified) {
997                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
998                                needUpdate = true;
999                            }
1000                            break;
1001
1002                        default:
1003                            // Nothing to do
1004                    }
1005
1006                    if (needUpdate) {
1007                        mSettings.updateIntentFilterVerificationStatusLPw(
1008                                packageName, updatedStatus, userId);
1009                        scheduleWritePackageRestrictionsLocked(userId);
1010                    }
1011                }
1012            }
1013        }
1014
1015        @Override
1016        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1017                    ActivityIntentInfo filter, String packageName) {
1018            if (!hasValidDomains(filter)) {
1019                return false;
1020            }
1021            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1022            if (ivs == null) {
1023                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1024                        packageName);
1025            }
1026            if (DEBUG_DOMAIN_VERIFICATION) {
1027                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1028            }
1029            ivs.addFilter(filter);
1030            return true;
1031        }
1032
1033        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1034                int userId, int verificationId, String packageName) {
1035            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1036                    verifierUid, userId, packageName);
1037            ivs.setPendingState();
1038            synchronized (mPackages) {
1039                mIntentFilterVerificationStates.append(verificationId, ivs);
1040                mCurrentIntentFilterVerifications.add(verificationId);
1041            }
1042            return ivs;
1043        }
1044    }
1045
1046    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1047        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1048                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1049                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1050    }
1051
1052    // Set of pending broadcasts for aggregating enable/disable of components.
1053    static class PendingPackageBroadcasts {
1054        // for each user id, a map of <package name -> components within that package>
1055        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1056
1057        public PendingPackageBroadcasts() {
1058            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1059        }
1060
1061        public ArrayList<String> get(int userId, String packageName) {
1062            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1063            return packages.get(packageName);
1064        }
1065
1066        public void put(int userId, String packageName, ArrayList<String> components) {
1067            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1068            packages.put(packageName, components);
1069        }
1070
1071        public void remove(int userId, String packageName) {
1072            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1073            if (packages != null) {
1074                packages.remove(packageName);
1075            }
1076        }
1077
1078        public void remove(int userId) {
1079            mUidMap.remove(userId);
1080        }
1081
1082        public int userIdCount() {
1083            return mUidMap.size();
1084        }
1085
1086        public int userIdAt(int n) {
1087            return mUidMap.keyAt(n);
1088        }
1089
1090        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1091            return mUidMap.get(userId);
1092        }
1093
1094        public int size() {
1095            // total number of pending broadcast entries across all userIds
1096            int num = 0;
1097            for (int i = 0; i< mUidMap.size(); i++) {
1098                num += mUidMap.valueAt(i).size();
1099            }
1100            return num;
1101        }
1102
1103        public void clear() {
1104            mUidMap.clear();
1105        }
1106
1107        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1108            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1109            if (map == null) {
1110                map = new ArrayMap<String, ArrayList<String>>();
1111                mUidMap.put(userId, map);
1112            }
1113            return map;
1114        }
1115    }
1116    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1117
1118    // Service Connection to remote media container service to copy
1119    // package uri's from external media onto secure containers
1120    // or internal storage.
1121    private IMediaContainerService mContainerService = null;
1122
1123    static final int SEND_PENDING_BROADCAST = 1;
1124    static final int MCS_BOUND = 3;
1125    static final int END_COPY = 4;
1126    static final int INIT_COPY = 5;
1127    static final int MCS_UNBIND = 6;
1128    static final int START_CLEANING_PACKAGE = 7;
1129    static final int FIND_INSTALL_LOC = 8;
1130    static final int POST_INSTALL = 9;
1131    static final int MCS_RECONNECT = 10;
1132    static final int MCS_GIVE_UP = 11;
1133    static final int UPDATED_MEDIA_STATUS = 12;
1134    static final int WRITE_SETTINGS = 13;
1135    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1136    static final int PACKAGE_VERIFIED = 15;
1137    static final int CHECK_PENDING_VERIFICATION = 16;
1138    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1139    static final int INTENT_FILTER_VERIFIED = 18;
1140    static final int WRITE_PACKAGE_LIST = 19;
1141    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1142
1143    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1144
1145    // Delay time in millisecs
1146    static final int BROADCAST_DELAY = 10 * 1000;
1147
1148    static UserManagerService sUserManager;
1149
1150    // Stores a list of users whose package restrictions file needs to be updated
1151    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1152
1153    final private DefaultContainerConnection mDefContainerConn =
1154            new DefaultContainerConnection();
1155    class DefaultContainerConnection implements ServiceConnection {
1156        public void onServiceConnected(ComponentName name, IBinder service) {
1157            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1158            final IMediaContainerService imcs = IMediaContainerService.Stub
1159                    .asInterface(Binder.allowBlocking(service));
1160            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1161        }
1162
1163        public void onServiceDisconnected(ComponentName name) {
1164            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1165        }
1166    }
1167
1168    // Recordkeeping of restore-after-install operations that are currently in flight
1169    // between the Package Manager and the Backup Manager
1170    static class PostInstallData {
1171        public InstallArgs args;
1172        public PackageInstalledInfo res;
1173
1174        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1175            args = _a;
1176            res = _r;
1177        }
1178    }
1179
1180    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1181    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1182
1183    // XML tags for backup/restore of various bits of state
1184    private static final String TAG_PREFERRED_BACKUP = "pa";
1185    private static final String TAG_DEFAULT_APPS = "da";
1186    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1187
1188    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1189    private static final String TAG_ALL_GRANTS = "rt-grants";
1190    private static final String TAG_GRANT = "grant";
1191    private static final String ATTR_PACKAGE_NAME = "pkg";
1192
1193    private static final String TAG_PERMISSION = "perm";
1194    private static final String ATTR_PERMISSION_NAME = "name";
1195    private static final String ATTR_IS_GRANTED = "g";
1196    private static final String ATTR_USER_SET = "set";
1197    private static final String ATTR_USER_FIXED = "fixed";
1198    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1199
1200    // System/policy permission grants are not backed up
1201    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1202            FLAG_PERMISSION_POLICY_FIXED
1203            | FLAG_PERMISSION_SYSTEM_FIXED
1204            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1205
1206    // And we back up these user-adjusted states
1207    private static final int USER_RUNTIME_GRANT_MASK =
1208            FLAG_PERMISSION_USER_SET
1209            | FLAG_PERMISSION_USER_FIXED
1210            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1211
1212    final @Nullable String mRequiredVerifierPackage;
1213    final @NonNull String mRequiredInstallerPackage;
1214    final @NonNull String mRequiredUninstallerPackage;
1215    final @Nullable String mSetupWizardPackage;
1216    final @Nullable String mStorageManagerPackage;
1217    final @NonNull String mServicesSystemSharedLibraryPackageName;
1218    final @NonNull String mSharedSystemSharedLibraryPackageName;
1219
1220    final boolean mPermissionReviewRequired;
1221
1222    private final PackageUsage mPackageUsage = new PackageUsage();
1223    private final CompilerStats mCompilerStats = new CompilerStats();
1224
1225    class PackageHandler extends Handler {
1226        private boolean mBound = false;
1227        final ArrayList<HandlerParams> mPendingInstalls =
1228            new ArrayList<HandlerParams>();
1229
1230        private boolean connectToService() {
1231            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1232                    " DefaultContainerService");
1233            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1234            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1235            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1236                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1237                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1238                mBound = true;
1239                return true;
1240            }
1241            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1242            return false;
1243        }
1244
1245        private void disconnectService() {
1246            mContainerService = null;
1247            mBound = false;
1248            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1249            mContext.unbindService(mDefContainerConn);
1250            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1251        }
1252
1253        PackageHandler(Looper looper) {
1254            super(looper);
1255        }
1256
1257        public void handleMessage(Message msg) {
1258            try {
1259                doHandleMessage(msg);
1260            } finally {
1261                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1262            }
1263        }
1264
1265        void doHandleMessage(Message msg) {
1266            switch (msg.what) {
1267                case INIT_COPY: {
1268                    HandlerParams params = (HandlerParams) msg.obj;
1269                    int idx = mPendingInstalls.size();
1270                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1271                    // If a bind was already initiated we dont really
1272                    // need to do anything. The pending install
1273                    // will be processed later on.
1274                    if (!mBound) {
1275                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1276                                System.identityHashCode(mHandler));
1277                        // If this is the only one pending we might
1278                        // have to bind to the service again.
1279                        if (!connectToService()) {
1280                            Slog.e(TAG, "Failed to bind to media container service");
1281                            params.serviceError();
1282                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1283                                    System.identityHashCode(mHandler));
1284                            if (params.traceMethod != null) {
1285                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1286                                        params.traceCookie);
1287                            }
1288                            return;
1289                        } else {
1290                            // Once we bind to the service, the first
1291                            // pending request will be processed.
1292                            mPendingInstalls.add(idx, params);
1293                        }
1294                    } else {
1295                        mPendingInstalls.add(idx, params);
1296                        // Already bound to the service. Just make
1297                        // sure we trigger off processing the first request.
1298                        if (idx == 0) {
1299                            mHandler.sendEmptyMessage(MCS_BOUND);
1300                        }
1301                    }
1302                    break;
1303                }
1304                case MCS_BOUND: {
1305                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1306                    if (msg.obj != null) {
1307                        mContainerService = (IMediaContainerService) msg.obj;
1308                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1309                                System.identityHashCode(mHandler));
1310                    }
1311                    if (mContainerService == null) {
1312                        if (!mBound) {
1313                            // Something seriously wrong since we are not bound and we are not
1314                            // waiting for connection. Bail out.
1315                            Slog.e(TAG, "Cannot bind to media container service");
1316                            for (HandlerParams params : mPendingInstalls) {
1317                                // Indicate service bind error
1318                                params.serviceError();
1319                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1320                                        System.identityHashCode(params));
1321                                if (params.traceMethod != null) {
1322                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1323                                            params.traceMethod, params.traceCookie);
1324                                }
1325                                return;
1326                            }
1327                            mPendingInstalls.clear();
1328                        } else {
1329                            Slog.w(TAG, "Waiting to connect to media container service");
1330                        }
1331                    } else if (mPendingInstalls.size() > 0) {
1332                        HandlerParams params = mPendingInstalls.get(0);
1333                        if (params != null) {
1334                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1335                                    System.identityHashCode(params));
1336                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1337                            if (params.startCopy()) {
1338                                // We are done...  look for more work or to
1339                                // go idle.
1340                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1341                                        "Checking for more work or unbind...");
1342                                // Delete pending install
1343                                if (mPendingInstalls.size() > 0) {
1344                                    mPendingInstalls.remove(0);
1345                                }
1346                                if (mPendingInstalls.size() == 0) {
1347                                    if (mBound) {
1348                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1349                                                "Posting delayed MCS_UNBIND");
1350                                        removeMessages(MCS_UNBIND);
1351                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1352                                        // Unbind after a little delay, to avoid
1353                                        // continual thrashing.
1354                                        sendMessageDelayed(ubmsg, 10000);
1355                                    }
1356                                } else {
1357                                    // There are more pending requests in queue.
1358                                    // Just post MCS_BOUND message to trigger processing
1359                                    // of next pending install.
1360                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1361                                            "Posting MCS_BOUND for next work");
1362                                    mHandler.sendEmptyMessage(MCS_BOUND);
1363                                }
1364                            }
1365                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1366                        }
1367                    } else {
1368                        // Should never happen ideally.
1369                        Slog.w(TAG, "Empty queue");
1370                    }
1371                    break;
1372                }
1373                case MCS_RECONNECT: {
1374                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1375                    if (mPendingInstalls.size() > 0) {
1376                        if (mBound) {
1377                            disconnectService();
1378                        }
1379                        if (!connectToService()) {
1380                            Slog.e(TAG, "Failed to bind to media container service");
1381                            for (HandlerParams params : mPendingInstalls) {
1382                                // Indicate service bind error
1383                                params.serviceError();
1384                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1385                                        System.identityHashCode(params));
1386                            }
1387                            mPendingInstalls.clear();
1388                        }
1389                    }
1390                    break;
1391                }
1392                case MCS_UNBIND: {
1393                    // If there is no actual work left, then time to unbind.
1394                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1395
1396                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1397                        if (mBound) {
1398                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1399
1400                            disconnectService();
1401                        }
1402                    } else if (mPendingInstalls.size() > 0) {
1403                        // There are more pending requests in queue.
1404                        // Just post MCS_BOUND message to trigger processing
1405                        // of next pending install.
1406                        mHandler.sendEmptyMessage(MCS_BOUND);
1407                    }
1408
1409                    break;
1410                }
1411                case MCS_GIVE_UP: {
1412                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1413                    HandlerParams params = mPendingInstalls.remove(0);
1414                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1415                            System.identityHashCode(params));
1416                    break;
1417                }
1418                case SEND_PENDING_BROADCAST: {
1419                    String packages[];
1420                    ArrayList<String> components[];
1421                    int size = 0;
1422                    int uids[];
1423                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424                    synchronized (mPackages) {
1425                        if (mPendingBroadcasts == null) {
1426                            return;
1427                        }
1428                        size = mPendingBroadcasts.size();
1429                        if (size <= 0) {
1430                            // Nothing to be done. Just return
1431                            return;
1432                        }
1433                        packages = new String[size];
1434                        components = new ArrayList[size];
1435                        uids = new int[size];
1436                        int i = 0;  // filling out the above arrays
1437
1438                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1439                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1440                            Iterator<Map.Entry<String, ArrayList<String>>> it
1441                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1442                                            .entrySet().iterator();
1443                            while (it.hasNext() && i < size) {
1444                                Map.Entry<String, ArrayList<String>> ent = it.next();
1445                                packages[i] = ent.getKey();
1446                                components[i] = ent.getValue();
1447                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1448                                uids[i] = (ps != null)
1449                                        ? UserHandle.getUid(packageUserId, ps.appId)
1450                                        : -1;
1451                                i++;
1452                            }
1453                        }
1454                        size = i;
1455                        mPendingBroadcasts.clear();
1456                    }
1457                    // Send broadcasts
1458                    for (int i = 0; i < size; i++) {
1459                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1460                    }
1461                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1462                    break;
1463                }
1464                case START_CLEANING_PACKAGE: {
1465                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1466                    final String packageName = (String)msg.obj;
1467                    final int userId = msg.arg1;
1468                    final boolean andCode = msg.arg2 != 0;
1469                    synchronized (mPackages) {
1470                        if (userId == UserHandle.USER_ALL) {
1471                            int[] users = sUserManager.getUserIds();
1472                            for (int user : users) {
1473                                mSettings.addPackageToCleanLPw(
1474                                        new PackageCleanItem(user, packageName, andCode));
1475                            }
1476                        } else {
1477                            mSettings.addPackageToCleanLPw(
1478                                    new PackageCleanItem(userId, packageName, andCode));
1479                        }
1480                    }
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1482                    startCleaningPackages();
1483                } break;
1484                case POST_INSTALL: {
1485                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1486
1487                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1488                    final boolean didRestore = (msg.arg2 != 0);
1489                    mRunningInstalls.delete(msg.arg1);
1490
1491                    if (data != null) {
1492                        InstallArgs args = data.args;
1493                        PackageInstalledInfo parentRes = data.res;
1494
1495                        final boolean grantPermissions = (args.installFlags
1496                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1497                        final boolean killApp = (args.installFlags
1498                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1499                        final String[] grantedPermissions = args.installGrantPermissions;
1500
1501                        // Handle the parent package
1502                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1503                                grantedPermissions, didRestore, args.installerPackageName,
1504                                args.observer);
1505
1506                        // Handle the child packages
1507                        final int childCount = (parentRes.addedChildPackages != null)
1508                                ? parentRes.addedChildPackages.size() : 0;
1509                        for (int i = 0; i < childCount; i++) {
1510                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1511                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1512                                    grantedPermissions, false, args.installerPackageName,
1513                                    args.observer);
1514                        }
1515
1516                        // Log tracing if needed
1517                        if (args.traceMethod != null) {
1518                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1519                                    args.traceCookie);
1520                        }
1521                    } else {
1522                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1523                    }
1524
1525                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1526                } break;
1527                case UPDATED_MEDIA_STATUS: {
1528                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1529                    boolean reportStatus = msg.arg1 == 1;
1530                    boolean doGc = msg.arg2 == 1;
1531                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1532                    if (doGc) {
1533                        // Force a gc to clear up stale containers.
1534                        Runtime.getRuntime().gc();
1535                    }
1536                    if (msg.obj != null) {
1537                        @SuppressWarnings("unchecked")
1538                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1539                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1540                        // Unload containers
1541                        unloadAllContainers(args);
1542                    }
1543                    if (reportStatus) {
1544                        try {
1545                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1546                                    "Invoking StorageManagerService call back");
1547                            PackageHelper.getStorageManager().finishMediaUpdate();
1548                        } catch (RemoteException e) {
1549                            Log.e(TAG, "StorageManagerService not running?");
1550                        }
1551                    }
1552                } break;
1553                case WRITE_SETTINGS: {
1554                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1555                    synchronized (mPackages) {
1556                        removeMessages(WRITE_SETTINGS);
1557                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1558                        mSettings.writeLPr();
1559                        mDirtyUsers.clear();
1560                    }
1561                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1562                } break;
1563                case WRITE_PACKAGE_RESTRICTIONS: {
1564                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1565                    synchronized (mPackages) {
1566                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1567                        for (int userId : mDirtyUsers) {
1568                            mSettings.writePackageRestrictionsLPr(userId);
1569                        }
1570                        mDirtyUsers.clear();
1571                    }
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1573                } break;
1574                case WRITE_PACKAGE_LIST: {
1575                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1576                    synchronized (mPackages) {
1577                        removeMessages(WRITE_PACKAGE_LIST);
1578                        mSettings.writePackageListLPr(msg.arg1);
1579                    }
1580                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1581                } break;
1582                case CHECK_PENDING_VERIFICATION: {
1583                    final int verificationId = msg.arg1;
1584                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1585
1586                    if ((state != null) && !state.timeoutExtended()) {
1587                        final InstallArgs args = state.getInstallArgs();
1588                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1589
1590                        Slog.i(TAG, "Verification timed out for " + originUri);
1591                        mPendingVerification.remove(verificationId);
1592
1593                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1594
1595                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1596                            Slog.i(TAG, "Continuing with installation of " + originUri);
1597                            state.setVerifierResponse(Binder.getCallingUid(),
1598                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1599                            broadcastPackageVerified(verificationId, originUri,
1600                                    PackageManager.VERIFICATION_ALLOW,
1601                                    state.getInstallArgs().getUser());
1602                            try {
1603                                ret = args.copyApk(mContainerService, true);
1604                            } catch (RemoteException e) {
1605                                Slog.e(TAG, "Could not contact the ContainerService");
1606                            }
1607                        } else {
1608                            broadcastPackageVerified(verificationId, originUri,
1609                                    PackageManager.VERIFICATION_REJECT,
1610                                    state.getInstallArgs().getUser());
1611                        }
1612
1613                        Trace.asyncTraceEnd(
1614                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1615
1616                        processPendingInstall(args, ret);
1617                        mHandler.sendEmptyMessage(MCS_UNBIND);
1618                    }
1619                    break;
1620                }
1621                case PACKAGE_VERIFIED: {
1622                    final int verificationId = msg.arg1;
1623
1624                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1625                    if (state == null) {
1626                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1627                        break;
1628                    }
1629
1630                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1631
1632                    state.setVerifierResponse(response.callerUid, response.code);
1633
1634                    if (state.isVerificationComplete()) {
1635                        mPendingVerification.remove(verificationId);
1636
1637                        final InstallArgs args = state.getInstallArgs();
1638                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1639
1640                        int ret;
1641                        if (state.isInstallAllowed()) {
1642                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1643                            broadcastPackageVerified(verificationId, originUri,
1644                                    response.code, state.getInstallArgs().getUser());
1645                            try {
1646                                ret = args.copyApk(mContainerService, true);
1647                            } catch (RemoteException e) {
1648                                Slog.e(TAG, "Could not contact the ContainerService");
1649                            }
1650                        } else {
1651                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1652                        }
1653
1654                        Trace.asyncTraceEnd(
1655                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1656
1657                        processPendingInstall(args, ret);
1658                        mHandler.sendEmptyMessage(MCS_UNBIND);
1659                    }
1660
1661                    break;
1662                }
1663                case START_INTENT_FILTER_VERIFICATIONS: {
1664                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1665                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1666                            params.replacing, params.pkg);
1667                    break;
1668                }
1669                case INTENT_FILTER_VERIFIED: {
1670                    final int verificationId = msg.arg1;
1671
1672                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1673                            verificationId);
1674                    if (state == null) {
1675                        Slog.w(TAG, "Invalid IntentFilter verification token "
1676                                + verificationId + " received");
1677                        break;
1678                    }
1679
1680                    final int userId = state.getUserId();
1681
1682                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1683                            "Processing IntentFilter verification with token:"
1684                            + verificationId + " and userId:" + userId);
1685
1686                    final IntentFilterVerificationResponse response =
1687                            (IntentFilterVerificationResponse) msg.obj;
1688
1689                    state.setVerifierResponse(response.callerUid, response.code);
1690
1691                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1692                            "IntentFilter verification with token:" + verificationId
1693                            + " and userId:" + userId
1694                            + " is settings verifier response with response code:"
1695                            + response.code);
1696
1697                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1698                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1699                                + response.getFailedDomainsString());
1700                    }
1701
1702                    if (state.isVerificationComplete()) {
1703                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1704                    } else {
1705                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1706                                "IntentFilter verification with token:" + verificationId
1707                                + " was not said to be complete");
1708                    }
1709
1710                    break;
1711                }
1712                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1713                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1714                            mEphemeralResolverConnection,
1715                            (EphemeralRequest) msg.obj,
1716                            mEphemeralInstallerActivity,
1717                            mHandler);
1718                }
1719            }
1720        }
1721    }
1722
1723    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1724            boolean killApp, String[] grantedPermissions,
1725            boolean launchedForRestore, String installerPackage,
1726            IPackageInstallObserver2 installObserver) {
1727        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1728            // Send the removed broadcasts
1729            if (res.removedInfo != null) {
1730                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1731            }
1732
1733            // Now that we successfully installed the package, grant runtime
1734            // permissions if requested before broadcasting the install. Also
1735            // for legacy apps in permission review mode we clear the permission
1736            // review flag which is used to emulate runtime permissions for
1737            // legacy apps.
1738            if (grantPermissions) {
1739                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1740            }
1741
1742            final boolean update = res.removedInfo != null
1743                    && res.removedInfo.removedPackage != null;
1744
1745            // If this is the first time we have child packages for a disabled privileged
1746            // app that had no children, we grant requested runtime permissions to the new
1747            // children if the parent on the system image had them already granted.
1748            if (res.pkg.parentPackage != null) {
1749                synchronized (mPackages) {
1750                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1751                }
1752            }
1753
1754            synchronized (mPackages) {
1755                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1756            }
1757
1758            final String packageName = res.pkg.applicationInfo.packageName;
1759
1760            // Determine the set of users who are adding this package for
1761            // the first time vs. those who are seeing an update.
1762            int[] firstUsers = EMPTY_INT_ARRAY;
1763            int[] updateUsers = EMPTY_INT_ARRAY;
1764            if (res.origUsers == null || res.origUsers.length == 0) {
1765                firstUsers = res.newUsers;
1766            } else {
1767                for (int newUser : res.newUsers) {
1768                    boolean isNew = true;
1769                    for (int origUser : res.origUsers) {
1770                        if (origUser == newUser) {
1771                            isNew = false;
1772                            break;
1773                        }
1774                    }
1775                    if (isNew) {
1776                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1777                    } else {
1778                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1779                    }
1780                }
1781            }
1782
1783            // Send installed broadcasts if the install/update is not ephemeral
1784            // and the package is not a static shared lib.
1785            if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) {
1786                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1787
1788                // Send added for users that see the package for the first time
1789                // sendPackageAddedForNewUsers also deals with system apps
1790                int appId = UserHandle.getAppId(res.uid);
1791                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1792                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1793
1794                // Send added for users that don't see the package for the first time
1795                Bundle extras = new Bundle(1);
1796                extras.putInt(Intent.EXTRA_UID, res.uid);
1797                if (update) {
1798                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1799                }
1800                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1801                        extras, 0 /*flags*/, null /*targetPackage*/,
1802                        null /*finishedReceiver*/, updateUsers);
1803
1804                // Send replaced for users that don't see the package for the first time
1805                if (update) {
1806                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1807                            packageName, extras, 0 /*flags*/,
1808                            null /*targetPackage*/, null /*finishedReceiver*/,
1809                            updateUsers);
1810                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1811                            null /*package*/, null /*extras*/, 0 /*flags*/,
1812                            packageName /*targetPackage*/,
1813                            null /*finishedReceiver*/, updateUsers);
1814                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1815                    // First-install and we did a restore, so we're responsible for the
1816                    // first-launch broadcast.
1817                    if (DEBUG_BACKUP) {
1818                        Slog.i(TAG, "Post-restore of " + packageName
1819                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1820                    }
1821                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1822                }
1823
1824                // Send broadcast package appeared if forward locked/external for all users
1825                // treat asec-hosted packages like removable media on upgrade
1826                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1827                    if (DEBUG_INSTALL) {
1828                        Slog.i(TAG, "upgrading pkg " + res.pkg
1829                                + " is ASEC-hosted -> AVAILABLE");
1830                    }
1831                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1832                    ArrayList<String> pkgList = new ArrayList<>(1);
1833                    pkgList.add(packageName);
1834                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1835                }
1836            }
1837
1838            // Work that needs to happen on first install within each user
1839            if (firstUsers != null && firstUsers.length > 0) {
1840                synchronized (mPackages) {
1841                    for (int userId : firstUsers) {
1842                        // If this app is a browser and it's newly-installed for some
1843                        // users, clear any default-browser state in those users. The
1844                        // app's nature doesn't depend on the user, so we can just check
1845                        // its browser nature in any user and generalize.
1846                        if (packageIsBrowser(packageName, userId)) {
1847                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1848                        }
1849
1850                        // We may also need to apply pending (restored) runtime
1851                        // permission grants within these users.
1852                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1853                    }
1854                }
1855            }
1856
1857            // Log current value of "unknown sources" setting
1858            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1859                    getUnknownSourcesSettings());
1860
1861            // Force a gc to clear up things
1862            Runtime.getRuntime().gc();
1863
1864            // Remove the replaced package's older resources safely now
1865            // We delete after a gc for applications  on sdcard.
1866            if (res.removedInfo != null && res.removedInfo.args != null) {
1867                synchronized (mInstallLock) {
1868                    res.removedInfo.args.doPostDeleteLI(true);
1869                }
1870            }
1871
1872            if (!isEphemeral(res.pkg)) {
1873                // Notify DexManager that the package was installed for new users.
1874                // The updated users should already be indexed and the package code paths
1875                // should not change.
1876                // Don't notify the manager for ephemeral apps as they are not expected to
1877                // survive long enough to benefit of background optimizations.
1878                for (int userId : firstUsers) {
1879                    PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1880                    mDexManager.notifyPackageInstalled(info, userId);
1881                }
1882            }
1883        }
1884
1885        // If someone is watching installs - notify them
1886        if (installObserver != null) {
1887            try {
1888                Bundle extras = extrasForInstallResult(res);
1889                installObserver.onPackageInstalled(res.name, res.returnCode,
1890                        res.returnMsg, extras);
1891            } catch (RemoteException e) {
1892                Slog.i(TAG, "Observer no longer exists.");
1893            }
1894        }
1895    }
1896
1897    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1898            PackageParser.Package pkg) {
1899        if (pkg.parentPackage == null) {
1900            return;
1901        }
1902        if (pkg.requestedPermissions == null) {
1903            return;
1904        }
1905        final PackageSetting disabledSysParentPs = mSettings
1906                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1907        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1908                || !disabledSysParentPs.isPrivileged()
1909                || (disabledSysParentPs.childPackageNames != null
1910                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1911            return;
1912        }
1913        final int[] allUserIds = sUserManager.getUserIds();
1914        final int permCount = pkg.requestedPermissions.size();
1915        for (int i = 0; i < permCount; i++) {
1916            String permission = pkg.requestedPermissions.get(i);
1917            BasePermission bp = mSettings.mPermissions.get(permission);
1918            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1919                continue;
1920            }
1921            for (int userId : allUserIds) {
1922                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1923                        permission, userId)) {
1924                    grantRuntimePermission(pkg.packageName, permission, userId);
1925                }
1926            }
1927        }
1928    }
1929
1930    private StorageEventListener mStorageListener = new StorageEventListener() {
1931        @Override
1932        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1933            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1934                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1935                    final String volumeUuid = vol.getFsUuid();
1936
1937                    // Clean up any users or apps that were removed or recreated
1938                    // while this volume was missing
1939                    sUserManager.reconcileUsers(volumeUuid);
1940                    reconcileApps(volumeUuid);
1941
1942                    // Clean up any install sessions that expired or were
1943                    // cancelled while this volume was missing
1944                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1945
1946                    loadPrivatePackages(vol);
1947
1948                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1949                    unloadPrivatePackages(vol);
1950                }
1951            }
1952
1953            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1954                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1955                    updateExternalMediaStatus(true, false);
1956                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1957                    updateExternalMediaStatus(false, false);
1958                }
1959            }
1960        }
1961
1962        @Override
1963        public void onVolumeForgotten(String fsUuid) {
1964            if (TextUtils.isEmpty(fsUuid)) {
1965                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1966                return;
1967            }
1968
1969            // Remove any apps installed on the forgotten volume
1970            synchronized (mPackages) {
1971                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1972                for (PackageSetting ps : packages) {
1973                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1974                    deletePackageVersioned(new VersionedPackage(ps.name,
1975                            PackageManager.VERSION_CODE_HIGHEST),
1976                            new LegacyPackageDeleteObserver(null).getBinder(),
1977                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1978                    // Try very hard to release any references to this package
1979                    // so we don't risk the system server being killed due to
1980                    // open FDs
1981                    AttributeCache.instance().removePackage(ps.name);
1982                }
1983
1984                mSettings.onVolumeForgotten(fsUuid);
1985                mSettings.writeLPr();
1986            }
1987        }
1988    };
1989
1990    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1991            String[] grantedPermissions) {
1992        for (int userId : userIds) {
1993            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1994        }
1995    }
1996
1997    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1998            String[] grantedPermissions) {
1999        SettingBase sb = (SettingBase) pkg.mExtras;
2000        if (sb == null) {
2001            return;
2002        }
2003
2004        PermissionsState permissionsState = sb.getPermissionsState();
2005
2006        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2007                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2008
2009        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2010                >= Build.VERSION_CODES.M;
2011
2012        for (String permission : pkg.requestedPermissions) {
2013            final BasePermission bp;
2014            synchronized (mPackages) {
2015                bp = mSettings.mPermissions.get(permission);
2016            }
2017            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2018                    && (grantedPermissions == null
2019                           || ArrayUtils.contains(grantedPermissions, permission))) {
2020                final int flags = permissionsState.getPermissionFlags(permission, userId);
2021                if (supportsRuntimePermissions) {
2022                    // Installer cannot change immutable permissions.
2023                    if ((flags & immutableFlags) == 0) {
2024                        grantRuntimePermission(pkg.packageName, permission, userId);
2025                    }
2026                } else if (mPermissionReviewRequired) {
2027                    // In permission review mode we clear the review flag when we
2028                    // are asked to install the app with all permissions granted.
2029                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2030                        updatePermissionFlags(permission, pkg.packageName,
2031                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2032                    }
2033                }
2034            }
2035        }
2036    }
2037
2038    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2039        Bundle extras = null;
2040        switch (res.returnCode) {
2041            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2042                extras = new Bundle();
2043                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2044                        res.origPermission);
2045                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2046                        res.origPackage);
2047                break;
2048            }
2049            case PackageManager.INSTALL_SUCCEEDED: {
2050                extras = new Bundle();
2051                extras.putBoolean(Intent.EXTRA_REPLACING,
2052                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2053                break;
2054            }
2055        }
2056        return extras;
2057    }
2058
2059    void scheduleWriteSettingsLocked() {
2060        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2061            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2062        }
2063    }
2064
2065    void scheduleWritePackageListLocked(int userId) {
2066        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2067            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2068            msg.arg1 = userId;
2069            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2070        }
2071    }
2072
2073    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2074        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2075        scheduleWritePackageRestrictionsLocked(userId);
2076    }
2077
2078    void scheduleWritePackageRestrictionsLocked(int userId) {
2079        final int[] userIds = (userId == UserHandle.USER_ALL)
2080                ? sUserManager.getUserIds() : new int[]{userId};
2081        for (int nextUserId : userIds) {
2082            if (!sUserManager.exists(nextUserId)) return;
2083            mDirtyUsers.add(nextUserId);
2084            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2085                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2086            }
2087        }
2088    }
2089
2090    public static PackageManagerService main(Context context, Installer installer,
2091            boolean factoryTest, boolean onlyCore) {
2092        // Self-check for initial settings.
2093        PackageManagerServiceCompilerMapping.checkProperties();
2094
2095        PackageManagerService m = new PackageManagerService(context, installer,
2096                factoryTest, onlyCore);
2097        m.enableSystemUserPackages();
2098        ServiceManager.addService("package", m);
2099        return m;
2100    }
2101
2102    private void enableSystemUserPackages() {
2103        if (!UserManager.isSplitSystemUser()) {
2104            return;
2105        }
2106        // For system user, enable apps based on the following conditions:
2107        // - app is whitelisted or belong to one of these groups:
2108        //   -- system app which has no launcher icons
2109        //   -- system app which has INTERACT_ACROSS_USERS permission
2110        //   -- system IME app
2111        // - app is not in the blacklist
2112        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2113        Set<String> enableApps = new ArraySet<>();
2114        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2115                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2116                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2117        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2118        enableApps.addAll(wlApps);
2119        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2120                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2121        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2122        enableApps.removeAll(blApps);
2123        Log.i(TAG, "Applications installed for system user: " + enableApps);
2124        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2125                UserHandle.SYSTEM);
2126        final int allAppsSize = allAps.size();
2127        synchronized (mPackages) {
2128            for (int i = 0; i < allAppsSize; i++) {
2129                String pName = allAps.get(i);
2130                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2131                // Should not happen, but we shouldn't be failing if it does
2132                if (pkgSetting == null) {
2133                    continue;
2134                }
2135                boolean install = enableApps.contains(pName);
2136                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2137                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2138                            + " for system user");
2139                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2140                }
2141            }
2142        }
2143    }
2144
2145    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2146        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2147                Context.DISPLAY_SERVICE);
2148        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2149    }
2150
2151    /**
2152     * Requests that files preopted on a secondary system partition be copied to the data partition
2153     * if possible.  Note that the actual copying of the files is accomplished by init for security
2154     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2155     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2156     */
2157    private static void requestCopyPreoptedFiles() {
2158        final int WAIT_TIME_MS = 100;
2159        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2160        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2161            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2162            // We will wait for up to 100 seconds.
2163            final long timeStart = SystemClock.uptimeMillis();
2164            final long timeEnd = timeStart + 100 * 1000;
2165            long timeNow = timeStart;
2166            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2167                try {
2168                    Thread.sleep(WAIT_TIME_MS);
2169                } catch (InterruptedException e) {
2170                    // Do nothing
2171                }
2172                timeNow = SystemClock.uptimeMillis();
2173                if (timeNow > timeEnd) {
2174                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2175                    Slog.wtf(TAG, "cppreopt did not finish!");
2176                    break;
2177                }
2178            }
2179
2180            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2181        }
2182    }
2183
2184    public PackageManagerService(Context context, Installer installer,
2185            boolean factoryTest, boolean onlyCore) {
2186        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2187        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2188                SystemClock.uptimeMillis());
2189
2190        if (mSdkVersion <= 0) {
2191            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2192        }
2193
2194        mContext = context;
2195
2196        mPermissionReviewRequired = context.getResources().getBoolean(
2197                R.bool.config_permissionReviewRequired);
2198
2199        mFactoryTest = factoryTest;
2200        mOnlyCore = onlyCore;
2201        mMetrics = new DisplayMetrics();
2202        mSettings = new Settings(mPackages);
2203        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2204                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2205        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2206                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2207        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2208                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2209        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2210                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2211        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2212                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2213        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2214                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2215
2216        String separateProcesses = SystemProperties.get("debug.separate_processes");
2217        if (separateProcesses != null && separateProcesses.length() > 0) {
2218            if ("*".equals(separateProcesses)) {
2219                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2220                mSeparateProcesses = null;
2221                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2222            } else {
2223                mDefParseFlags = 0;
2224                mSeparateProcesses = separateProcesses.split(",");
2225                Slog.w(TAG, "Running with debug.separate_processes: "
2226                        + separateProcesses);
2227            }
2228        } else {
2229            mDefParseFlags = 0;
2230            mSeparateProcesses = null;
2231        }
2232
2233        mInstaller = installer;
2234        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2235                "*dexopt*");
2236        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2237        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2238
2239        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2240                FgThread.get().getLooper());
2241
2242        getDefaultDisplayMetrics(context, mMetrics);
2243
2244        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2245        SystemConfig systemConfig = SystemConfig.getInstance();
2246        mGlobalGids = systemConfig.getGlobalGids();
2247        mSystemPermissions = systemConfig.getSystemPermissions();
2248        mAvailableFeatures = systemConfig.getAvailableFeatures();
2249        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2250
2251        mProtectedPackages = new ProtectedPackages(mContext);
2252
2253        synchronized (mInstallLock) {
2254        // writer
2255        synchronized (mPackages) {
2256            mHandlerThread = new ServiceThread(TAG,
2257                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2258            mHandlerThread.start();
2259            mHandler = new PackageHandler(mHandlerThread.getLooper());
2260            mProcessLoggingHandler = new ProcessLoggingHandler();
2261            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2262
2263            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2264            mInstantAppRegistry = new InstantAppRegistry(this);
2265
2266            File dataDir = Environment.getDataDirectory();
2267            mAppInstallDir = new File(dataDir, "app");
2268            mAppLib32InstallDir = new File(dataDir, "app-lib");
2269            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2270            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2271            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2272            sUserManager = new UserManagerService(context, this,
2273                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2274
2275            // Propagate permission configuration in to package manager.
2276            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2277                    = systemConfig.getPermissions();
2278            for (int i=0; i<permConfig.size(); i++) {
2279                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2280                BasePermission bp = mSettings.mPermissions.get(perm.name);
2281                if (bp == null) {
2282                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2283                    mSettings.mPermissions.put(perm.name, bp);
2284                }
2285                if (perm.gids != null) {
2286                    bp.setGids(perm.gids, perm.perUser);
2287                }
2288            }
2289
2290            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2291            final int builtInLibCount = libConfig.size();
2292            for (int i = 0; i < builtInLibCount; i++) {
2293                String name = libConfig.keyAt(i);
2294                String path = libConfig.valueAt(i);
2295                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2296                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2297            }
2298
2299            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2300
2301            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2302            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2303            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2304
2305            // Clean up orphaned packages for which the code path doesn't exist
2306            // and they are an update to a system app - caused by bug/32321269
2307            final int packageSettingCount = mSettings.mPackages.size();
2308            for (int i = packageSettingCount - 1; i >= 0; i--) {
2309                PackageSetting ps = mSettings.mPackages.valueAt(i);
2310                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2311                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2312                    mSettings.mPackages.removeAt(i);
2313                    mSettings.enableSystemPackageLPw(ps.name);
2314                }
2315            }
2316
2317            if (mFirstBoot) {
2318                requestCopyPreoptedFiles();
2319            }
2320
2321            String customResolverActivity = Resources.getSystem().getString(
2322                    R.string.config_customResolverActivity);
2323            if (TextUtils.isEmpty(customResolverActivity)) {
2324                customResolverActivity = null;
2325            } else {
2326                mCustomResolverComponentName = ComponentName.unflattenFromString(
2327                        customResolverActivity);
2328            }
2329
2330            long startTime = SystemClock.uptimeMillis();
2331
2332            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2333                    startTime);
2334
2335            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2336            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2337
2338            if (bootClassPath == null) {
2339                Slog.w(TAG, "No BOOTCLASSPATH found!");
2340            }
2341
2342            if (systemServerClassPath == null) {
2343                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2344            }
2345
2346            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2347            final String[] dexCodeInstructionSets =
2348                    getDexCodeInstructionSets(
2349                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2350
2351            /**
2352             * Ensure all external libraries have had dexopt run on them.
2353             */
2354            if (mSharedLibraries.size() > 0) {
2355                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2356                // NOTE: For now, we're compiling these system "shared libraries"
2357                // (and framework jars) into all available architectures. It's possible
2358                // to compile them only when we come across an app that uses them (there's
2359                // already logic for that in scanPackageLI) but that adds some complexity.
2360                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2361                    final int libCount = mSharedLibraries.size();
2362                    for (int i = 0; i < libCount; i++) {
2363                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2364                        final int versionCount = versionedLib.size();
2365                        for (int j = 0; j < versionCount; j++) {
2366                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2367                            final String libPath = libEntry.path != null
2368                                    ? libEntry.path : libEntry.apk;
2369                            if (libPath == null) {
2370                                continue;
2371                            }
2372                            try {
2373                                // Shared libraries do not have profiles so we perform a full
2374                                // AOT compilation (if needed).
2375                                int dexoptNeeded = DexFile.getDexOptNeeded(
2376                                        libPath, dexCodeInstructionSet,
2377                                        getCompilerFilterForReason(REASON_SHARED_APK),
2378                                        false /* newProfile */);
2379                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2380                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2381                                            dexCodeInstructionSet, dexoptNeeded, null,
2382                                            DEXOPT_PUBLIC,
2383                                            getCompilerFilterForReason(REASON_SHARED_APK),
2384                                            StorageManager.UUID_PRIVATE_INTERNAL,
2385                                            SKIP_SHARED_LIBRARY_CHECK);
2386                                }
2387                            } catch (FileNotFoundException e) {
2388                                Slog.w(TAG, "Library not found: " + libPath);
2389                            } catch (IOException | InstallerException e) {
2390                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2391                                        + e.getMessage());
2392                            }
2393                        }
2394                    }
2395                }
2396                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2397            }
2398
2399            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2400
2401            final VersionInfo ver = mSettings.getInternalVersion();
2402            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2403
2404            // when upgrading from pre-M, promote system app permissions from install to runtime
2405            mPromoteSystemApps =
2406                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2407
2408            // When upgrading from pre-N, we need to handle package extraction like first boot,
2409            // as there is no profiling data available.
2410            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2411
2412            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2413
2414            // save off the names of pre-existing system packages prior to scanning; we don't
2415            // want to automatically grant runtime permissions for new system apps
2416            if (mPromoteSystemApps) {
2417                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2418                while (pkgSettingIter.hasNext()) {
2419                    PackageSetting ps = pkgSettingIter.next();
2420                    if (isSystemApp(ps)) {
2421                        mExistingSystemPackages.add(ps.name);
2422                    }
2423                }
2424            }
2425
2426            mCacheDir = preparePackageParserCache(mIsUpgrade);
2427
2428            // Set flag to monitor and not change apk file paths when
2429            // scanning install directories.
2430            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2431
2432            if (mIsUpgrade || mFirstBoot) {
2433                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2434            }
2435
2436            // Collect vendor overlay packages. (Do this before scanning any apps.)
2437            // For security and version matching reason, only consider
2438            // overlay packages if they reside in the right directory.
2439            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2440            if (overlayThemeDir.isEmpty()) {
2441                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2442            }
2443            if (!overlayThemeDir.isEmpty()) {
2444                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2445                        | PackageParser.PARSE_IS_SYSTEM
2446                        | PackageParser.PARSE_IS_SYSTEM_DIR
2447                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2448            }
2449            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2450                    | PackageParser.PARSE_IS_SYSTEM
2451                    | PackageParser.PARSE_IS_SYSTEM_DIR
2452                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2453
2454            // Find base frameworks (resource packages without code).
2455            scanDirTracedLI(frameworkDir, mDefParseFlags
2456                    | PackageParser.PARSE_IS_SYSTEM
2457                    | PackageParser.PARSE_IS_SYSTEM_DIR
2458                    | PackageParser.PARSE_IS_PRIVILEGED,
2459                    scanFlags | SCAN_NO_DEX, 0);
2460
2461            // Collected privileged system packages.
2462            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2463            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2464                    | PackageParser.PARSE_IS_SYSTEM
2465                    | PackageParser.PARSE_IS_SYSTEM_DIR
2466                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2467
2468            // Collect ordinary system packages.
2469            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2470            scanDirTracedLI(systemAppDir, mDefParseFlags
2471                    | PackageParser.PARSE_IS_SYSTEM
2472                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2473
2474            // Collect all vendor packages.
2475            File vendorAppDir = new File("/vendor/app");
2476            try {
2477                vendorAppDir = vendorAppDir.getCanonicalFile();
2478            } catch (IOException e) {
2479                // failed to look up canonical path, continue with original one
2480            }
2481            scanDirTracedLI(vendorAppDir, mDefParseFlags
2482                    | PackageParser.PARSE_IS_SYSTEM
2483                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2484
2485            // Collect all OEM packages.
2486            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2487            scanDirTracedLI(oemAppDir, mDefParseFlags
2488                    | PackageParser.PARSE_IS_SYSTEM
2489                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2490
2491            // Prune any system packages that no longer exist.
2492            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2493            if (!mOnlyCore) {
2494                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2495                while (psit.hasNext()) {
2496                    PackageSetting ps = psit.next();
2497
2498                    /*
2499                     * If this is not a system app, it can't be a
2500                     * disable system app.
2501                     */
2502                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2503                        continue;
2504                    }
2505
2506                    /*
2507                     * If the package is scanned, it's not erased.
2508                     */
2509                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2510                    if (scannedPkg != null) {
2511                        /*
2512                         * If the system app is both scanned and in the
2513                         * disabled packages list, then it must have been
2514                         * added via OTA. Remove it from the currently
2515                         * scanned package so the previously user-installed
2516                         * application can be scanned.
2517                         */
2518                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2519                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2520                                    + ps.name + "; removing system app.  Last known codePath="
2521                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2522                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2523                                    + scannedPkg.mVersionCode);
2524                            removePackageLI(scannedPkg, true);
2525                            mExpectingBetter.put(ps.name, ps.codePath);
2526                        }
2527
2528                        continue;
2529                    }
2530
2531                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2532                        psit.remove();
2533                        logCriticalInfo(Log.WARN, "System package " + ps.name
2534                                + " no longer exists; it's data will be wiped");
2535                        // Actual deletion of code and data will be handled by later
2536                        // reconciliation step
2537                    } else {
2538                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2539                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2540                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2541                        }
2542                    }
2543                }
2544            }
2545
2546            //look for any incomplete package installations
2547            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2548            for (int i = 0; i < deletePkgsList.size(); i++) {
2549                // Actual deletion of code and data will be handled by later
2550                // reconciliation step
2551                final String packageName = deletePkgsList.get(i).name;
2552                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2553                synchronized (mPackages) {
2554                    mSettings.removePackageLPw(packageName);
2555                }
2556            }
2557
2558            //delete tmp files
2559            deleteTempPackageFiles();
2560
2561            // Remove any shared userIDs that have no associated packages
2562            mSettings.pruneSharedUsersLPw();
2563
2564            if (!mOnlyCore) {
2565                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2566                        SystemClock.uptimeMillis());
2567                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2568
2569                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2570                        | PackageParser.PARSE_FORWARD_LOCK,
2571                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2572
2573                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2574                        | PackageParser.PARSE_IS_EPHEMERAL,
2575                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2576
2577                /**
2578                 * Remove disable package settings for any updated system
2579                 * apps that were removed via an OTA. If they're not a
2580                 * previously-updated app, remove them completely.
2581                 * Otherwise, just revoke their system-level permissions.
2582                 */
2583                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2584                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2585                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2586
2587                    String msg;
2588                    if (deletedPkg == null) {
2589                        msg = "Updated system package " + deletedAppName
2590                                + " no longer exists; it's data will be wiped";
2591                        // Actual deletion of code and data will be handled by later
2592                        // reconciliation step
2593                    } else {
2594                        msg = "Updated system app + " + deletedAppName
2595                                + " no longer present; removing system privileges for "
2596                                + deletedAppName;
2597
2598                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2599
2600                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2601                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2602                    }
2603                    logCriticalInfo(Log.WARN, msg);
2604                }
2605
2606                /**
2607                 * Make sure all system apps that we expected to appear on
2608                 * the userdata partition actually showed up. If they never
2609                 * appeared, crawl back and revive the system version.
2610                 */
2611                for (int i = 0; i < mExpectingBetter.size(); i++) {
2612                    final String packageName = mExpectingBetter.keyAt(i);
2613                    if (!mPackages.containsKey(packageName)) {
2614                        final File scanFile = mExpectingBetter.valueAt(i);
2615
2616                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2617                                + " but never showed up; reverting to system");
2618
2619                        int reparseFlags = mDefParseFlags;
2620                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2621                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2622                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2623                                    | PackageParser.PARSE_IS_PRIVILEGED;
2624                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2625                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2626                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2627                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2628                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2629                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2630                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2631                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2632                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2633                        } else {
2634                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2635                            continue;
2636                        }
2637
2638                        mSettings.enableSystemPackageLPw(packageName);
2639
2640                        try {
2641                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2642                        } catch (PackageManagerException e) {
2643                            Slog.e(TAG, "Failed to parse original system package: "
2644                                    + e.getMessage());
2645                        }
2646                    }
2647                }
2648            }
2649            mExpectingBetter.clear();
2650
2651            // Resolve the storage manager.
2652            mStorageManagerPackage = getStorageManagerPackageName();
2653
2654            // Resolve protected action filters. Only the setup wizard is allowed to
2655            // have a high priority filter for these actions.
2656            mSetupWizardPackage = getSetupWizardPackageName();
2657            if (mProtectedFilters.size() > 0) {
2658                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2659                    Slog.i(TAG, "No setup wizard;"
2660                        + " All protected intents capped to priority 0");
2661                }
2662                for (ActivityIntentInfo filter : mProtectedFilters) {
2663                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2664                        if (DEBUG_FILTERS) {
2665                            Slog.i(TAG, "Found setup wizard;"
2666                                + " allow priority " + filter.getPriority() + ";"
2667                                + " package: " + filter.activity.info.packageName
2668                                + " activity: " + filter.activity.className
2669                                + " priority: " + filter.getPriority());
2670                        }
2671                        // skip setup wizard; allow it to keep the high priority filter
2672                        continue;
2673                    }
2674                    Slog.w(TAG, "Protected action; cap priority to 0;"
2675                            + " package: " + filter.activity.info.packageName
2676                            + " activity: " + filter.activity.className
2677                            + " origPrio: " + filter.getPriority());
2678                    filter.setPriority(0);
2679                }
2680            }
2681            mDeferProtectedFilters = false;
2682            mProtectedFilters.clear();
2683
2684            // Now that we know all of the shared libraries, update all clients to have
2685            // the correct library paths.
2686            updateAllSharedLibrariesLPw(null);
2687
2688            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2689                // NOTE: We ignore potential failures here during a system scan (like
2690                // the rest of the commands above) because there's precious little we
2691                // can do about it. A settings error is reported, though.
2692                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2693            }
2694
2695            // Now that we know all the packages we are keeping,
2696            // read and update their last usage times.
2697            mPackageUsage.read(mPackages);
2698            mCompilerStats.read();
2699
2700            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2701                    SystemClock.uptimeMillis());
2702            Slog.i(TAG, "Time to scan packages: "
2703                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2704                    + " seconds");
2705
2706            // If the platform SDK has changed since the last time we booted,
2707            // we need to re-grant app permission to catch any new ones that
2708            // appear.  This is really a hack, and means that apps can in some
2709            // cases get permissions that the user didn't initially explicitly
2710            // allow...  it would be nice to have some better way to handle
2711            // this situation.
2712            int updateFlags = UPDATE_PERMISSIONS_ALL;
2713            if (ver.sdkVersion != mSdkVersion) {
2714                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2715                        + mSdkVersion + "; regranting permissions for internal storage");
2716                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2717            }
2718            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2719            ver.sdkVersion = mSdkVersion;
2720
2721            // If this is the first boot or an update from pre-M, and it is a normal
2722            // boot, then we need to initialize the default preferred apps across
2723            // all defined users.
2724            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2725                for (UserInfo user : sUserManager.getUsers(true)) {
2726                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2727                    applyFactoryDefaultBrowserLPw(user.id);
2728                    primeDomainVerificationsLPw(user.id);
2729                }
2730            }
2731
2732            // Prepare storage for system user really early during boot,
2733            // since core system apps like SettingsProvider and SystemUI
2734            // can't wait for user to start
2735            final int storageFlags;
2736            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2737                storageFlags = StorageManager.FLAG_STORAGE_DE;
2738            } else {
2739                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2740            }
2741            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2742                    storageFlags, true /* migrateAppData */);
2743
2744            // If this is first boot after an OTA, and a normal boot, then
2745            // we need to clear code cache directories.
2746            // Note that we do *not* clear the application profiles. These remain valid
2747            // across OTAs and are used to drive profile verification (post OTA) and
2748            // profile compilation (without waiting to collect a fresh set of profiles).
2749            if (mIsUpgrade && !onlyCore) {
2750                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2751                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2752                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2753                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2754                        // No apps are running this early, so no need to freeze
2755                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2756                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2757                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2758                    }
2759                }
2760                ver.fingerprint = Build.FINGERPRINT;
2761            }
2762
2763            checkDefaultBrowser();
2764
2765            // clear only after permissions and other defaults have been updated
2766            mExistingSystemPackages.clear();
2767            mPromoteSystemApps = false;
2768
2769            // All the changes are done during package scanning.
2770            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2771
2772            // can downgrade to reader
2773            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2774            mSettings.writeLPr();
2775            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2776
2777            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2778            // early on (before the package manager declares itself as early) because other
2779            // components in the system server might ask for package contexts for these apps.
2780            //
2781            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2782            // (i.e, that the data partition is unavailable).
2783            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2784                long start = System.nanoTime();
2785                List<PackageParser.Package> coreApps = new ArrayList<>();
2786                for (PackageParser.Package pkg : mPackages.values()) {
2787                    if (pkg.coreApp) {
2788                        coreApps.add(pkg);
2789                    }
2790                }
2791
2792                int[] stats = performDexOptUpgrade(coreApps, false,
2793                        getCompilerFilterForReason(REASON_CORE_APP));
2794
2795                final int elapsedTimeSeconds =
2796                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2797                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2798
2799                if (DEBUG_DEXOPT) {
2800                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2801                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2802                }
2803
2804
2805                // TODO: Should we log these stats to tron too ?
2806                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2807                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2808                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2809                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2810            }
2811
2812            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2813                    SystemClock.uptimeMillis());
2814
2815            if (!mOnlyCore) {
2816                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2817                mRequiredInstallerPackage = getRequiredInstallerLPr();
2818                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2819                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2820                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2821                        mIntentFilterVerifierComponent);
2822                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2823                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2824                        SharedLibraryInfo.VERSION_UNDEFINED);
2825                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2826                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2827                        SharedLibraryInfo.VERSION_UNDEFINED);
2828            } else {
2829                mRequiredVerifierPackage = null;
2830                mRequiredInstallerPackage = null;
2831                mRequiredUninstallerPackage = null;
2832                mIntentFilterVerifierComponent = null;
2833                mIntentFilterVerifier = null;
2834                mServicesSystemSharedLibraryPackageName = null;
2835                mSharedSystemSharedLibraryPackageName = null;
2836            }
2837
2838            mInstallerService = new PackageInstallerService(context, this);
2839
2840            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2841            if (ephemeralResolverComponent != null) {
2842                if (DEBUG_EPHEMERAL) {
2843                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2844                }
2845                mEphemeralResolverConnection =
2846                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2847            } else {
2848                mEphemeralResolverConnection = null;
2849            }
2850            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2851            if (mEphemeralInstallerComponent != null) {
2852                if (DEBUG_EPHEMERAL) {
2853                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2854                }
2855                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2856            }
2857
2858            // Read and update the usage of dex files.
2859            // Do this at the end of PM init so that all the packages have their
2860            // data directory reconciled.
2861            // At this point we know the code paths of the packages, so we can validate
2862            // the disk file and build the internal cache.
2863            // The usage file is expected to be small so loading and verifying it
2864            // should take a fairly small time compare to the other activities (e.g. package
2865            // scanning).
2866            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2867            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2868            for (int userId : currentUserIds) {
2869                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2870            }
2871            mDexManager.load(userPackages);
2872        } // synchronized (mPackages)
2873        } // synchronized (mInstallLock)
2874
2875        // Now after opening every single application zip, make sure they
2876        // are all flushed.  Not really needed, but keeps things nice and
2877        // tidy.
2878        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2879        Runtime.getRuntime().gc();
2880        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2881
2882        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2883        FallbackCategoryProvider.loadFallbacks();
2884        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2885
2886        // The initial scanning above does many calls into installd while
2887        // holding the mPackages lock, but we're mostly interested in yelling
2888        // once we have a booted system.
2889        mInstaller.setWarnIfHeld(mPackages);
2890
2891        // Expose private service for system components to use.
2892        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2893        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2894    }
2895
2896    private static File preparePackageParserCache(boolean isUpgrade) {
2897        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2898            return null;
2899        }
2900
2901        // Disable package parsing on eng builds to allow for faster incremental development.
2902        if ("eng".equals(Build.TYPE)) {
2903            return null;
2904        }
2905
2906        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2907            Slog.i(TAG, "Disabling package parser cache due to system property.");
2908            return null;
2909        }
2910
2911        // The base directory for the package parser cache lives under /data/system/.
2912        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2913                "package_cache");
2914        if (cacheBaseDir == null) {
2915            return null;
2916        }
2917
2918        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2919        // This also serves to "GC" unused entries when the package cache version changes (which
2920        // can only happen during upgrades).
2921        if (isUpgrade) {
2922            FileUtils.deleteContents(cacheBaseDir);
2923        }
2924
2925
2926        // Return the versioned package cache directory. This is something like
2927        // "/data/system/package_cache/1"
2928        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2929
2930        // The following is a workaround to aid development on non-numbered userdebug
2931        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2932        // the system partition is newer.
2933        //
2934        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2935        // that starts with "eng." to signify that this is an engineering build and not
2936        // destined for release.
2937        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2938            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2939
2940            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2941            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2942            // in general and should not be used for production changes. In this specific case,
2943            // we know that they will work.
2944            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2945            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2946                FileUtils.deleteContents(cacheBaseDir);
2947                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2948            }
2949        }
2950
2951        return cacheDir;
2952    }
2953
2954    @Override
2955    public boolean isFirstBoot() {
2956        return mFirstBoot;
2957    }
2958
2959    @Override
2960    public boolean isOnlyCoreApps() {
2961        return mOnlyCore;
2962    }
2963
2964    @Override
2965    public boolean isUpgrade() {
2966        return mIsUpgrade;
2967    }
2968
2969    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2970        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2971
2972        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2973                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2974                UserHandle.USER_SYSTEM);
2975        if (matches.size() == 1) {
2976            return matches.get(0).getComponentInfo().packageName;
2977        } else if (matches.size() == 0) {
2978            Log.e(TAG, "There should probably be a verifier, but, none were found");
2979            return null;
2980        }
2981        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2982    }
2983
2984    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2985        synchronized (mPackages) {
2986            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2987            if (libraryEntry == null) {
2988                throw new IllegalStateException("Missing required shared library:" + name);
2989            }
2990            return libraryEntry.apk;
2991        }
2992    }
2993
2994    private @NonNull String getRequiredInstallerLPr() {
2995        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2996        intent.addCategory(Intent.CATEGORY_DEFAULT);
2997        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2998
2999        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3000                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3001                UserHandle.USER_SYSTEM);
3002        if (matches.size() == 1) {
3003            ResolveInfo resolveInfo = matches.get(0);
3004            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3005                throw new RuntimeException("The installer must be a privileged app");
3006            }
3007            return matches.get(0).getComponentInfo().packageName;
3008        } else {
3009            throw new RuntimeException("There must be exactly one installer; found " + matches);
3010        }
3011    }
3012
3013    private @NonNull String getRequiredUninstallerLPr() {
3014        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3015        intent.addCategory(Intent.CATEGORY_DEFAULT);
3016        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3017
3018        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3019                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3020                UserHandle.USER_SYSTEM);
3021        if (resolveInfo == null ||
3022                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3023            throw new RuntimeException("There must be exactly one uninstaller; found "
3024                    + resolveInfo);
3025        }
3026        return resolveInfo.getComponentInfo().packageName;
3027    }
3028
3029    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3030        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3031
3032        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3033                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3034                UserHandle.USER_SYSTEM);
3035        ResolveInfo best = null;
3036        final int N = matches.size();
3037        for (int i = 0; i < N; i++) {
3038            final ResolveInfo cur = matches.get(i);
3039            final String packageName = cur.getComponentInfo().packageName;
3040            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3041                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3042                continue;
3043            }
3044
3045            if (best == null || cur.priority > best.priority) {
3046                best = cur;
3047            }
3048        }
3049
3050        if (best != null) {
3051            return best.getComponentInfo().getComponentName();
3052        } else {
3053            throw new RuntimeException("There must be at least one intent filter verifier");
3054        }
3055    }
3056
3057    private @Nullable ComponentName getEphemeralResolverLPr() {
3058        final String[] packageArray =
3059                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3060        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3061            if (DEBUG_EPHEMERAL) {
3062                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3063            }
3064            return null;
3065        }
3066
3067        final int resolveFlags =
3068                MATCH_DIRECT_BOOT_AWARE
3069                | MATCH_DIRECT_BOOT_UNAWARE
3070                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3071        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3072        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3073                resolveFlags, UserHandle.USER_SYSTEM);
3074
3075        final int N = resolvers.size();
3076        if (N == 0) {
3077            if (DEBUG_EPHEMERAL) {
3078                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3079            }
3080            return null;
3081        }
3082
3083        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3084        for (int i = 0; i < N; i++) {
3085            final ResolveInfo info = resolvers.get(i);
3086
3087            if (info.serviceInfo == null) {
3088                continue;
3089            }
3090
3091            final String packageName = info.serviceInfo.packageName;
3092            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3093                if (DEBUG_EPHEMERAL) {
3094                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3095                            + " pkg: " + packageName + ", info:" + info);
3096                }
3097                continue;
3098            }
3099
3100            if (DEBUG_EPHEMERAL) {
3101                Slog.v(TAG, "Ephemeral resolver found;"
3102                        + " pkg: " + packageName + ", info:" + info);
3103            }
3104            return new ComponentName(packageName, info.serviceInfo.name);
3105        }
3106        if (DEBUG_EPHEMERAL) {
3107            Slog.v(TAG, "Ephemeral resolver NOT found");
3108        }
3109        return null;
3110    }
3111
3112    private @Nullable ComponentName getEphemeralInstallerLPr() {
3113        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3114        intent.addCategory(Intent.CATEGORY_DEFAULT);
3115        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3116
3117        final int resolveFlags =
3118                MATCH_DIRECT_BOOT_AWARE
3119                | MATCH_DIRECT_BOOT_UNAWARE
3120                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3121        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3122                resolveFlags, UserHandle.USER_SYSTEM);
3123        Iterator<ResolveInfo> iter = matches.iterator();
3124        while (iter.hasNext()) {
3125            final ResolveInfo rInfo = iter.next();
3126            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3127            if (ps != null) {
3128                final PermissionsState permissionsState = ps.getPermissionsState();
3129                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3130                    continue;
3131                }
3132            }
3133            iter.remove();
3134        }
3135        if (matches.size() == 0) {
3136            return null;
3137        } else if (matches.size() == 1) {
3138            return matches.get(0).getComponentInfo().getComponentName();
3139        } else {
3140            throw new RuntimeException(
3141                    "There must be at most one ephemeral installer; found " + matches);
3142        }
3143    }
3144
3145    private void primeDomainVerificationsLPw(int userId) {
3146        if (DEBUG_DOMAIN_VERIFICATION) {
3147            Slog.d(TAG, "Priming domain verifications in user " + userId);
3148        }
3149
3150        SystemConfig systemConfig = SystemConfig.getInstance();
3151        ArraySet<String> packages = systemConfig.getLinkedApps();
3152
3153        for (String packageName : packages) {
3154            PackageParser.Package pkg = mPackages.get(packageName);
3155            if (pkg != null) {
3156                if (!pkg.isSystemApp()) {
3157                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3158                    continue;
3159                }
3160
3161                ArraySet<String> domains = null;
3162                for (PackageParser.Activity a : pkg.activities) {
3163                    for (ActivityIntentInfo filter : a.intents) {
3164                        if (hasValidDomains(filter)) {
3165                            if (domains == null) {
3166                                domains = new ArraySet<String>();
3167                            }
3168                            domains.addAll(filter.getHostsList());
3169                        }
3170                    }
3171                }
3172
3173                if (domains != null && domains.size() > 0) {
3174                    if (DEBUG_DOMAIN_VERIFICATION) {
3175                        Slog.v(TAG, "      + " + packageName);
3176                    }
3177                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3178                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3179                    // and then 'always' in the per-user state actually used for intent resolution.
3180                    final IntentFilterVerificationInfo ivi;
3181                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3182                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3183                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3184                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3185                } else {
3186                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3187                            + "' does not handle web links");
3188                }
3189            } else {
3190                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3191            }
3192        }
3193
3194        scheduleWritePackageRestrictionsLocked(userId);
3195        scheduleWriteSettingsLocked();
3196    }
3197
3198    private void applyFactoryDefaultBrowserLPw(int userId) {
3199        // The default browser app's package name is stored in a string resource,
3200        // with a product-specific overlay used for vendor customization.
3201        String browserPkg = mContext.getResources().getString(
3202                com.android.internal.R.string.default_browser);
3203        if (!TextUtils.isEmpty(browserPkg)) {
3204            // non-empty string => required to be a known package
3205            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3206            if (ps == null) {
3207                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3208                browserPkg = null;
3209            } else {
3210                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3211            }
3212        }
3213
3214        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3215        // default.  If there's more than one, just leave everything alone.
3216        if (browserPkg == null) {
3217            calculateDefaultBrowserLPw(userId);
3218        }
3219    }
3220
3221    private void calculateDefaultBrowserLPw(int userId) {
3222        List<String> allBrowsers = resolveAllBrowserApps(userId);
3223        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3224        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3225    }
3226
3227    private List<String> resolveAllBrowserApps(int userId) {
3228        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3229        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3230                PackageManager.MATCH_ALL, userId);
3231
3232        final int count = list.size();
3233        List<String> result = new ArrayList<String>(count);
3234        for (int i=0; i<count; i++) {
3235            ResolveInfo info = list.get(i);
3236            if (info.activityInfo == null
3237                    || !info.handleAllWebDataURI
3238                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3239                    || result.contains(info.activityInfo.packageName)) {
3240                continue;
3241            }
3242            result.add(info.activityInfo.packageName);
3243        }
3244
3245        return result;
3246    }
3247
3248    private boolean packageIsBrowser(String packageName, int userId) {
3249        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3250                PackageManager.MATCH_ALL, userId);
3251        final int N = list.size();
3252        for (int i = 0; i < N; i++) {
3253            ResolveInfo info = list.get(i);
3254            if (packageName.equals(info.activityInfo.packageName)) {
3255                return true;
3256            }
3257        }
3258        return false;
3259    }
3260
3261    private void checkDefaultBrowser() {
3262        final int myUserId = UserHandle.myUserId();
3263        final String packageName = getDefaultBrowserPackageName(myUserId);
3264        if (packageName != null) {
3265            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3266            if (info == null) {
3267                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3268                synchronized (mPackages) {
3269                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3270                }
3271            }
3272        }
3273    }
3274
3275    @Override
3276    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3277            throws RemoteException {
3278        try {
3279            return super.onTransact(code, data, reply, flags);
3280        } catch (RuntimeException e) {
3281            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3282                Slog.wtf(TAG, "Package Manager Crash", e);
3283            }
3284            throw e;
3285        }
3286    }
3287
3288    static int[] appendInts(int[] cur, int[] add) {
3289        if (add == null) return cur;
3290        if (cur == null) return add;
3291        final int N = add.length;
3292        for (int i=0; i<N; i++) {
3293            cur = appendInt(cur, add[i]);
3294        }
3295        return cur;
3296    }
3297
3298    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3299        if (!sUserManager.exists(userId)) return null;
3300        if (ps == null) {
3301            return null;
3302        }
3303        final PackageParser.Package p = ps.pkg;
3304        if (p == null) {
3305            return null;
3306        }
3307        // Filter out ephemeral app metadata:
3308        //   * The system/shell/root can see metadata for any app
3309        //   * An installed app can see metadata for 1) other installed apps
3310        //     and 2) ephemeral apps that have explicitly interacted with it
3311        //   * Ephemeral apps can only see their own metadata
3312        //   * Holding a signature permission allows seeing instant apps
3313        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3314        if (callingAppId != Process.SYSTEM_UID
3315                && callingAppId != Process.SHELL_UID
3316                && callingAppId != Process.ROOT_UID
3317                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3318                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3319            final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid());
3320            if (ephemeralPackageName != null) {
3321                // ephemeral apps can only get information on themselves
3322                if (!ephemeralPackageName.equals(p.packageName)) {
3323                    return null;
3324                }
3325            } else {
3326                if (p.applicationInfo.isInstantApp()) {
3327                    // only get access to the ephemeral app if we've been granted access
3328                    if (!mInstantAppRegistry.isInstantAccessGranted(
3329                            userId, callingAppId, ps.appId)) {
3330                        return null;
3331                    }
3332                }
3333            }
3334        }
3335
3336        final PermissionsState permissionsState = ps.getPermissionsState();
3337
3338        // Compute GIDs only if requested
3339        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3340                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3341        // Compute granted permissions only if package has requested permissions
3342        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3343                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3344        final PackageUserState state = ps.readUserState(userId);
3345
3346        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3347                && ps.isSystem()) {
3348            flags |= MATCH_ANY_USER;
3349        }
3350
3351        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3352                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3353
3354        if (packageInfo == null) {
3355            return null;
3356        }
3357
3358        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3359                resolveExternalPackageNameLPr(p);
3360
3361        return packageInfo;
3362    }
3363
3364    @Override
3365    public void checkPackageStartable(String packageName, int userId) {
3366        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3367
3368        synchronized (mPackages) {
3369            final PackageSetting ps = mSettings.mPackages.get(packageName);
3370            if (ps == null) {
3371                throw new SecurityException("Package " + packageName + " was not found!");
3372            }
3373
3374            if (!ps.getInstalled(userId)) {
3375                throw new SecurityException(
3376                        "Package " + packageName + " was not installed for user " + userId + "!");
3377            }
3378
3379            if (mSafeMode && !ps.isSystem()) {
3380                throw new SecurityException("Package " + packageName + " not a system app!");
3381            }
3382
3383            if (mFrozenPackages.contains(packageName)) {
3384                throw new SecurityException("Package " + packageName + " is currently frozen!");
3385            }
3386
3387            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3388                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3389                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3390            }
3391        }
3392    }
3393
3394    @Override
3395    public boolean isPackageAvailable(String packageName, int userId) {
3396        if (!sUserManager.exists(userId)) return false;
3397        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3398                false /* requireFullPermission */, false /* checkShell */, "is package available");
3399        synchronized (mPackages) {
3400            PackageParser.Package p = mPackages.get(packageName);
3401            if (p != null) {
3402                final PackageSetting ps = (PackageSetting) p.mExtras;
3403                if (ps != null) {
3404                    final PackageUserState state = ps.readUserState(userId);
3405                    if (state != null) {
3406                        return PackageParser.isAvailable(state);
3407                    }
3408                }
3409            }
3410        }
3411        return false;
3412    }
3413
3414    @Override
3415    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3416        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3417                flags, userId);
3418    }
3419
3420    @Override
3421    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3422            int flags, int userId) {
3423        return getPackageInfoInternal(versionedPackage.getPackageName(),
3424                // TODO: We will change version code to long, so in the new API it is long
3425                (int) versionedPackage.getVersionCode(), flags, userId);
3426    }
3427
3428    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3429            int flags, int userId) {
3430        if (!sUserManager.exists(userId)) return null;
3431        flags = updateFlagsForPackage(flags, userId, packageName);
3432        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3433                false /* requireFullPermission */, false /* checkShell */, "get package info");
3434
3435        // reader
3436        synchronized (mPackages) {
3437            // Normalize package name to handle renamed packages and static libs
3438            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3439
3440            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3441            if (matchFactoryOnly) {
3442                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3443                if (ps != null) {
3444                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3445                        return null;
3446                    }
3447                    return generatePackageInfo(ps, flags, userId);
3448                }
3449            }
3450
3451            PackageParser.Package p = mPackages.get(packageName);
3452            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3453                return null;
3454            }
3455            if (DEBUG_PACKAGE_INFO)
3456                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3457            if (p != null) {
3458                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3459                        Binder.getCallingUid(), userId)) {
3460                    return null;
3461                }
3462                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3463            }
3464            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3465                final PackageSetting ps = mSettings.mPackages.get(packageName);
3466                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3467                    return null;
3468                }
3469                return generatePackageInfo(ps, flags, userId);
3470            }
3471        }
3472        return null;
3473    }
3474
3475
3476    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3477        // System/shell/root get to see all static libs
3478        final int appId = UserHandle.getAppId(uid);
3479        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3480                || appId == Process.ROOT_UID) {
3481            return false;
3482        }
3483
3484        // No package means no static lib as it is always on internal storage
3485        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3486            return false;
3487        }
3488
3489        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3490                ps.pkg.staticSharedLibVersion);
3491        if (libEntry == null) {
3492            return false;
3493        }
3494
3495        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3496        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3497        if (uidPackageNames == null) {
3498            return true;
3499        }
3500
3501        for (String uidPackageName : uidPackageNames) {
3502            if (ps.name.equals(uidPackageName)) {
3503                return false;
3504            }
3505            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3506            if (uidPs != null) {
3507                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3508                        libEntry.info.getName());
3509                if (index < 0) {
3510                    continue;
3511                }
3512                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3513                    return false;
3514                }
3515            }
3516        }
3517        return true;
3518    }
3519
3520    @Override
3521    public String[] currentToCanonicalPackageNames(String[] names) {
3522        String[] out = new String[names.length];
3523        // reader
3524        synchronized (mPackages) {
3525            for (int i=names.length-1; i>=0; i--) {
3526                PackageSetting ps = mSettings.mPackages.get(names[i]);
3527                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3528            }
3529        }
3530        return out;
3531    }
3532
3533    @Override
3534    public String[] canonicalToCurrentPackageNames(String[] names) {
3535        String[] out = new String[names.length];
3536        // reader
3537        synchronized (mPackages) {
3538            for (int i=names.length-1; i>=0; i--) {
3539                String cur = mSettings.getRenamedPackageLPr(names[i]);
3540                out[i] = cur != null ? cur : names[i];
3541            }
3542        }
3543        return out;
3544    }
3545
3546    @Override
3547    public int getPackageUid(String packageName, int flags, int userId) {
3548        if (!sUserManager.exists(userId)) return -1;
3549        flags = updateFlagsForPackage(flags, userId, packageName);
3550        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3551                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3552
3553        // reader
3554        synchronized (mPackages) {
3555            final PackageParser.Package p = mPackages.get(packageName);
3556            if (p != null && p.isMatch(flags)) {
3557                return UserHandle.getUid(userId, p.applicationInfo.uid);
3558            }
3559            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3560                final PackageSetting ps = mSettings.mPackages.get(packageName);
3561                if (ps != null && ps.isMatch(flags)) {
3562                    return UserHandle.getUid(userId, ps.appId);
3563                }
3564            }
3565        }
3566
3567        return -1;
3568    }
3569
3570    @Override
3571    public int[] getPackageGids(String packageName, int flags, int userId) {
3572        if (!sUserManager.exists(userId)) return null;
3573        flags = updateFlagsForPackage(flags, userId, packageName);
3574        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3575                false /* requireFullPermission */, false /* checkShell */,
3576                "getPackageGids");
3577
3578        // reader
3579        synchronized (mPackages) {
3580            final PackageParser.Package p = mPackages.get(packageName);
3581            if (p != null && p.isMatch(flags)) {
3582                PackageSetting ps = (PackageSetting) p.mExtras;
3583                // TODO: Shouldn't this be checking for package installed state for userId and
3584                // return null?
3585                return ps.getPermissionsState().computeGids(userId);
3586            }
3587            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3588                final PackageSetting ps = mSettings.mPackages.get(packageName);
3589                if (ps != null && ps.isMatch(flags)) {
3590                    return ps.getPermissionsState().computeGids(userId);
3591                }
3592            }
3593        }
3594
3595        return null;
3596    }
3597
3598    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3599        if (bp.perm != null) {
3600            return PackageParser.generatePermissionInfo(bp.perm, flags);
3601        }
3602        PermissionInfo pi = new PermissionInfo();
3603        pi.name = bp.name;
3604        pi.packageName = bp.sourcePackage;
3605        pi.nonLocalizedLabel = bp.name;
3606        pi.protectionLevel = bp.protectionLevel;
3607        return pi;
3608    }
3609
3610    @Override
3611    public PermissionInfo getPermissionInfo(String name, int flags) {
3612        // reader
3613        synchronized (mPackages) {
3614            final BasePermission p = mSettings.mPermissions.get(name);
3615            if (p != null) {
3616                return generatePermissionInfo(p, flags);
3617            }
3618            return null;
3619        }
3620    }
3621
3622    @Override
3623    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3624            int flags) {
3625        // reader
3626        synchronized (mPackages) {
3627            if (group != null && !mPermissionGroups.containsKey(group)) {
3628                // This is thrown as NameNotFoundException
3629                return null;
3630            }
3631
3632            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3633            for (BasePermission p : mSettings.mPermissions.values()) {
3634                if (group == null) {
3635                    if (p.perm == null || p.perm.info.group == null) {
3636                        out.add(generatePermissionInfo(p, flags));
3637                    }
3638                } else {
3639                    if (p.perm != null && group.equals(p.perm.info.group)) {
3640                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3641                    }
3642                }
3643            }
3644            return new ParceledListSlice<>(out);
3645        }
3646    }
3647
3648    @Override
3649    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3650        // reader
3651        synchronized (mPackages) {
3652            return PackageParser.generatePermissionGroupInfo(
3653                    mPermissionGroups.get(name), flags);
3654        }
3655    }
3656
3657    @Override
3658    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3659        // reader
3660        synchronized (mPackages) {
3661            final int N = mPermissionGroups.size();
3662            ArrayList<PermissionGroupInfo> out
3663                    = new ArrayList<PermissionGroupInfo>(N);
3664            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3665                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3666            }
3667            return new ParceledListSlice<>(out);
3668        }
3669    }
3670
3671    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3672            int uid, int userId) {
3673        if (!sUserManager.exists(userId)) return null;
3674        PackageSetting ps = mSettings.mPackages.get(packageName);
3675        if (ps != null) {
3676            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3677                return null;
3678            }
3679            if (ps.pkg == null) {
3680                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3681                if (pInfo != null) {
3682                    return pInfo.applicationInfo;
3683                }
3684                return null;
3685            }
3686            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3687                    ps.readUserState(userId), userId);
3688            if (ai != null) {
3689                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3690            }
3691            return ai;
3692        }
3693        return null;
3694    }
3695
3696    @Override
3697    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3698        if (!sUserManager.exists(userId)) return null;
3699        flags = updateFlagsForApplication(flags, userId, packageName);
3700        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3701                false /* requireFullPermission */, false /* checkShell */, "get application info");
3702
3703        // writer
3704        synchronized (mPackages) {
3705            // Normalize package name to handle renamed packages and static libs
3706            packageName = resolveInternalPackageNameLPr(packageName,
3707                    PackageManager.VERSION_CODE_HIGHEST);
3708
3709            PackageParser.Package p = mPackages.get(packageName);
3710            if (DEBUG_PACKAGE_INFO) Log.v(
3711                    TAG, "getApplicationInfo " + packageName
3712                    + ": " + p);
3713            if (p != null) {
3714                PackageSetting ps = mSettings.mPackages.get(packageName);
3715                if (ps == null) return null;
3716                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3717                    return null;
3718                }
3719                // Note: isEnabledLP() does not apply here - always return info
3720                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3721                        p, flags, ps.readUserState(userId), userId);
3722                if (ai != null) {
3723                    ai.packageName = resolveExternalPackageNameLPr(p);
3724                }
3725                return ai;
3726            }
3727            if ("android".equals(packageName)||"system".equals(packageName)) {
3728                return mAndroidApplication;
3729            }
3730            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3731                // Already generates the external package name
3732                return generateApplicationInfoFromSettingsLPw(packageName,
3733                        Binder.getCallingUid(), flags, userId);
3734            }
3735        }
3736        return null;
3737    }
3738
3739    private String normalizePackageNameLPr(String packageName) {
3740        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3741        return normalizedPackageName != null ? normalizedPackageName : packageName;
3742    }
3743
3744    @Override
3745    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3746            final IPackageDataObserver observer) {
3747        mContext.enforceCallingOrSelfPermission(
3748                android.Manifest.permission.CLEAR_APP_CACHE, null);
3749        // Queue up an async operation since clearing cache may take a little while.
3750        mHandler.post(new Runnable() {
3751            public void run() {
3752                mHandler.removeCallbacks(this);
3753                boolean success = true;
3754                synchronized (mInstallLock) {
3755                    try {
3756                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3757                    } catch (InstallerException e) {
3758                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3759                        success = false;
3760                    }
3761                }
3762                if (observer != null) {
3763                    try {
3764                        observer.onRemoveCompleted(null, success);
3765                    } catch (RemoteException e) {
3766                        Slog.w(TAG, "RemoveException when invoking call back");
3767                    }
3768                }
3769            }
3770        });
3771    }
3772
3773    @Override
3774    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3775            final IntentSender pi) {
3776        mContext.enforceCallingOrSelfPermission(
3777                android.Manifest.permission.CLEAR_APP_CACHE, null);
3778        // Queue up an async operation since clearing cache may take a little while.
3779        mHandler.post(new Runnable() {
3780            public void run() {
3781                mHandler.removeCallbacks(this);
3782                boolean success = true;
3783                synchronized (mInstallLock) {
3784                    try {
3785                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3786                    } catch (InstallerException e) {
3787                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3788                        success = false;
3789                    }
3790                }
3791                if(pi != null) {
3792                    try {
3793                        // Callback via pending intent
3794                        int code = success ? 1 : 0;
3795                        pi.sendIntent(null, code, null,
3796                                null, null);
3797                    } catch (SendIntentException e1) {
3798                        Slog.i(TAG, "Failed to send pending intent");
3799                    }
3800                }
3801            }
3802        });
3803    }
3804
3805    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3806        synchronized (mInstallLock) {
3807            try {
3808                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3809            } catch (InstallerException e) {
3810                throw new IOException("Failed to free enough space", e);
3811            }
3812        }
3813    }
3814
3815    /**
3816     * Update given flags based on encryption status of current user.
3817     */
3818    private int updateFlags(int flags, int userId) {
3819        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3820                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3821            // Caller expressed an explicit opinion about what encryption
3822            // aware/unaware components they want to see, so fall through and
3823            // give them what they want
3824        } else {
3825            // Caller expressed no opinion, so match based on user state
3826            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3827                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3828            } else {
3829                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3830            }
3831        }
3832        return flags;
3833    }
3834
3835    private UserManagerInternal getUserManagerInternal() {
3836        if (mUserManagerInternal == null) {
3837            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3838        }
3839        return mUserManagerInternal;
3840    }
3841
3842    /**
3843     * Update given flags when being used to request {@link PackageInfo}.
3844     */
3845    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3846        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3847        boolean triaged = true;
3848        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3849                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3850            // Caller is asking for component details, so they'd better be
3851            // asking for specific encryption matching behavior, or be triaged
3852            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3853                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3854                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3855                triaged = false;
3856            }
3857        }
3858        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3859                | PackageManager.MATCH_SYSTEM_ONLY
3860                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3861            triaged = false;
3862        }
3863        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3864            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3865                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3866                    + Debug.getCallers(5));
3867        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3868                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3869            // If the caller wants all packages and has a restricted profile associated with it,
3870            // then match all users. This is to make sure that launchers that need to access work
3871            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3872            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3873            flags |= PackageManager.MATCH_ANY_USER;
3874        }
3875        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3876            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3877                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3878        }
3879        return updateFlags(flags, userId);
3880    }
3881
3882    /**
3883     * Update given flags when being used to request {@link ApplicationInfo}.
3884     */
3885    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3886        return updateFlagsForPackage(flags, userId, cookie);
3887    }
3888
3889    /**
3890     * Update given flags when being used to request {@link ComponentInfo}.
3891     */
3892    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3893        if (cookie instanceof Intent) {
3894            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3895                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3896            }
3897        }
3898
3899        boolean triaged = true;
3900        // Caller is asking for component details, so they'd better be
3901        // asking for specific encryption matching behavior, or be triaged
3902        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3903                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3904                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3905            triaged = false;
3906        }
3907        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3908            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3909                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3910        }
3911
3912        return updateFlags(flags, userId);
3913    }
3914
3915    /**
3916     * Update given intent when being used to request {@link ResolveInfo}.
3917     */
3918    private Intent updateIntentForResolve(Intent intent) {
3919        if (intent.getSelector() != null) {
3920            intent = intent.getSelector();
3921        }
3922        if (DEBUG_PREFERRED) {
3923            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3924        }
3925        return intent;
3926    }
3927
3928    /**
3929     * Update given flags when being used to request {@link ResolveInfo}.
3930     */
3931    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3932        // Safe mode means we shouldn't match any third-party components
3933        if (mSafeMode) {
3934            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3935        }
3936        final int callingUid = Binder.getCallingUid();
3937        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3938            // The system sees all components
3939            flags |= PackageManager.MATCH_EPHEMERAL;
3940        } else if (getEphemeralPackageName(callingUid) != null) {
3941            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3942            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3943            flags |= PackageManager.MATCH_EPHEMERAL;
3944        } else {
3945            // Otherwise, prevent leaking ephemeral components
3946            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3947            flags &= ~PackageManager.MATCH_EPHEMERAL;
3948        }
3949        return updateFlagsForComponent(flags, userId, cookie);
3950    }
3951
3952    @Override
3953    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3954        if (!sUserManager.exists(userId)) return null;
3955        flags = updateFlagsForComponent(flags, userId, component);
3956        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3957                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3958        synchronized (mPackages) {
3959            PackageParser.Activity a = mActivities.mActivities.get(component);
3960
3961            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3962            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3963                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3964                if (ps == null) return null;
3965                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3966                        userId);
3967            }
3968            if (mResolveComponentName.equals(component)) {
3969                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3970                        new PackageUserState(), userId);
3971            }
3972        }
3973        return null;
3974    }
3975
3976    @Override
3977    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3978            String resolvedType) {
3979        synchronized (mPackages) {
3980            if (component.equals(mResolveComponentName)) {
3981                // The resolver supports EVERYTHING!
3982                return true;
3983            }
3984            PackageParser.Activity a = mActivities.mActivities.get(component);
3985            if (a == null) {
3986                return false;
3987            }
3988            for (int i=0; i<a.intents.size(); i++) {
3989                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3990                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3991                    return true;
3992                }
3993            }
3994            return false;
3995        }
3996    }
3997
3998    @Override
3999    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4000        if (!sUserManager.exists(userId)) return null;
4001        flags = updateFlagsForComponent(flags, userId, component);
4002        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4003                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4004        synchronized (mPackages) {
4005            PackageParser.Activity a = mReceivers.mActivities.get(component);
4006            if (DEBUG_PACKAGE_INFO) Log.v(
4007                TAG, "getReceiverInfo " + component + ": " + a);
4008            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4009                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4010                if (ps == null) return null;
4011                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4012                        userId);
4013            }
4014        }
4015        return null;
4016    }
4017
4018    @Override
4019    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4020        if (!sUserManager.exists(userId)) return null;
4021        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4022
4023        flags = updateFlagsForPackage(flags, userId, null);
4024
4025        final boolean canSeeStaticLibraries =
4026                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4027                        == PERMISSION_GRANTED
4028                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4029                        == PERMISSION_GRANTED
4030                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4031                        == PERMISSION_GRANTED
4032                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4033                        == PERMISSION_GRANTED;
4034
4035        synchronized (mPackages) {
4036            List<SharedLibraryInfo> result = null;
4037
4038            final int libCount = mSharedLibraries.size();
4039            for (int i = 0; i < libCount; i++) {
4040                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4041                if (versionedLib == null) {
4042                    continue;
4043                }
4044
4045                final int versionCount = versionedLib.size();
4046                for (int j = 0; j < versionCount; j++) {
4047                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4048                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4049                        break;
4050                    }
4051                    final long identity = Binder.clearCallingIdentity();
4052                    try {
4053                        // TODO: We will change version code to long, so in the new API it is long
4054                        PackageInfo packageInfo = getPackageInfoVersioned(
4055                                libInfo.getDeclaringPackage(), flags, userId);
4056                        if (packageInfo == null) {
4057                            continue;
4058                        }
4059                    } finally {
4060                        Binder.restoreCallingIdentity(identity);
4061                    }
4062
4063                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4064                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4065                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4066
4067                    if (result == null) {
4068                        result = new ArrayList<>();
4069                    }
4070                    result.add(resLibInfo);
4071                }
4072            }
4073
4074            return result != null ? new ParceledListSlice<>(result) : null;
4075        }
4076    }
4077
4078    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4079            SharedLibraryInfo libInfo, int flags, int userId) {
4080        List<VersionedPackage> versionedPackages = null;
4081        final int packageCount = mSettings.mPackages.size();
4082        for (int i = 0; i < packageCount; i++) {
4083            PackageSetting ps = mSettings.mPackages.valueAt(i);
4084
4085            if (ps == null) {
4086                continue;
4087            }
4088
4089            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4090                continue;
4091            }
4092
4093            final String libName = libInfo.getName();
4094            if (libInfo.isStatic()) {
4095                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4096                if (libIdx < 0) {
4097                    continue;
4098                }
4099                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4100                    continue;
4101                }
4102                if (versionedPackages == null) {
4103                    versionedPackages = new ArrayList<>();
4104                }
4105                // If the dependent is a static shared lib, use the public package name
4106                String dependentPackageName = ps.name;
4107                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4108                    dependentPackageName = ps.pkg.manifestPackageName;
4109                }
4110                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4111            } else if (ps.pkg != null) {
4112                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4113                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4114                    if (versionedPackages == null) {
4115                        versionedPackages = new ArrayList<>();
4116                    }
4117                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4118                }
4119            }
4120        }
4121
4122        return versionedPackages;
4123    }
4124
4125    @Override
4126    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4127        if (!sUserManager.exists(userId)) return null;
4128        flags = updateFlagsForComponent(flags, userId, component);
4129        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4130                false /* requireFullPermission */, false /* checkShell */, "get service info");
4131        synchronized (mPackages) {
4132            PackageParser.Service s = mServices.mServices.get(component);
4133            if (DEBUG_PACKAGE_INFO) Log.v(
4134                TAG, "getServiceInfo " + component + ": " + s);
4135            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4136                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4137                if (ps == null) return null;
4138                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4139                        userId);
4140            }
4141        }
4142        return null;
4143    }
4144
4145    @Override
4146    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4147        if (!sUserManager.exists(userId)) return null;
4148        flags = updateFlagsForComponent(flags, userId, component);
4149        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4150                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4151        synchronized (mPackages) {
4152            PackageParser.Provider p = mProviders.mProviders.get(component);
4153            if (DEBUG_PACKAGE_INFO) Log.v(
4154                TAG, "getProviderInfo " + component + ": " + p);
4155            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4156                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4157                if (ps == null) return null;
4158                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4159                        userId);
4160            }
4161        }
4162        return null;
4163    }
4164
4165    @Override
4166    public String[] getSystemSharedLibraryNames() {
4167        synchronized (mPackages) {
4168            Set<String> libs = null;
4169            final int libCount = mSharedLibraries.size();
4170            for (int i = 0; i < libCount; i++) {
4171                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4172                if (versionedLib == null) {
4173                    continue;
4174                }
4175                final int versionCount = versionedLib.size();
4176                for (int j = 0; j < versionCount; j++) {
4177                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4178                    if (!libEntry.info.isStatic()) {
4179                        if (libs == null) {
4180                            libs = new ArraySet<>();
4181                        }
4182                        libs.add(libEntry.info.getName());
4183                        break;
4184                    }
4185                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4186                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4187                            UserHandle.getUserId(Binder.getCallingUid()))) {
4188                        if (libs == null) {
4189                            libs = new ArraySet<>();
4190                        }
4191                        libs.add(libEntry.info.getName());
4192                        break;
4193                    }
4194                }
4195            }
4196
4197            if (libs != null) {
4198                String[] libsArray = new String[libs.size()];
4199                libs.toArray(libsArray);
4200                return libsArray;
4201            }
4202
4203            return null;
4204        }
4205    }
4206
4207    @Override
4208    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4209        synchronized (mPackages) {
4210            return mServicesSystemSharedLibraryPackageName;
4211        }
4212    }
4213
4214    @Override
4215    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4216        synchronized (mPackages) {
4217            return mSharedSystemSharedLibraryPackageName;
4218        }
4219    }
4220
4221    @Override
4222    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4223        ArrayList<FeatureInfo> res;
4224        synchronized (mAvailableFeatures) {
4225            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4226            res.addAll(mAvailableFeatures.values());
4227        }
4228        final FeatureInfo fi = new FeatureInfo();
4229        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4230                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4231        res.add(fi);
4232
4233        return new ParceledListSlice<>(res);
4234    }
4235
4236    @Override
4237    public boolean hasSystemFeature(String name, int version) {
4238        synchronized (mAvailableFeatures) {
4239            final FeatureInfo feat = mAvailableFeatures.get(name);
4240            if (feat == null) {
4241                return false;
4242            } else {
4243                return feat.version >= version;
4244            }
4245        }
4246    }
4247
4248    @Override
4249    public int checkPermission(String permName, String pkgName, int userId) {
4250        if (!sUserManager.exists(userId)) {
4251            return PackageManager.PERMISSION_DENIED;
4252        }
4253
4254        synchronized (mPackages) {
4255            final PackageParser.Package p = mPackages.get(pkgName);
4256            if (p != null && p.mExtras != null) {
4257                final PackageSetting ps = (PackageSetting) p.mExtras;
4258                final PermissionsState permissionsState = ps.getPermissionsState();
4259                if (permissionsState.hasPermission(permName, userId)) {
4260                    return PackageManager.PERMISSION_GRANTED;
4261                }
4262                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4263                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4264                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4265                    return PackageManager.PERMISSION_GRANTED;
4266                }
4267            }
4268        }
4269
4270        return PackageManager.PERMISSION_DENIED;
4271    }
4272
4273    @Override
4274    public int checkUidPermission(String permName, int uid) {
4275        final int userId = UserHandle.getUserId(uid);
4276
4277        if (!sUserManager.exists(userId)) {
4278            return PackageManager.PERMISSION_DENIED;
4279        }
4280
4281        synchronized (mPackages) {
4282            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4283            if (obj != null) {
4284                final SettingBase ps = (SettingBase) obj;
4285                final PermissionsState permissionsState = ps.getPermissionsState();
4286                if (permissionsState.hasPermission(permName, userId)) {
4287                    return PackageManager.PERMISSION_GRANTED;
4288                }
4289                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4290                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4291                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4292                    return PackageManager.PERMISSION_GRANTED;
4293                }
4294            } else {
4295                ArraySet<String> perms = mSystemPermissions.get(uid);
4296                if (perms != null) {
4297                    if (perms.contains(permName)) {
4298                        return PackageManager.PERMISSION_GRANTED;
4299                    }
4300                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4301                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4302                        return PackageManager.PERMISSION_GRANTED;
4303                    }
4304                }
4305            }
4306        }
4307
4308        return PackageManager.PERMISSION_DENIED;
4309    }
4310
4311    @Override
4312    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4313        if (UserHandle.getCallingUserId() != userId) {
4314            mContext.enforceCallingPermission(
4315                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4316                    "isPermissionRevokedByPolicy for user " + userId);
4317        }
4318
4319        if (checkPermission(permission, packageName, userId)
4320                == PackageManager.PERMISSION_GRANTED) {
4321            return false;
4322        }
4323
4324        final long identity = Binder.clearCallingIdentity();
4325        try {
4326            final int flags = getPermissionFlags(permission, packageName, userId);
4327            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4328        } finally {
4329            Binder.restoreCallingIdentity(identity);
4330        }
4331    }
4332
4333    @Override
4334    public String getPermissionControllerPackageName() {
4335        synchronized (mPackages) {
4336            return mRequiredInstallerPackage;
4337        }
4338    }
4339
4340    /**
4341     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4342     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4343     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4344     * @param message the message to log on security exception
4345     */
4346    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4347            boolean checkShell, String message) {
4348        if (userId < 0) {
4349            throw new IllegalArgumentException("Invalid userId " + userId);
4350        }
4351        if (checkShell) {
4352            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4353        }
4354        if (userId == UserHandle.getUserId(callingUid)) return;
4355        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4356            if (requireFullPermission) {
4357                mContext.enforceCallingOrSelfPermission(
4358                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4359            } else {
4360                try {
4361                    mContext.enforceCallingOrSelfPermission(
4362                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4363                } catch (SecurityException se) {
4364                    mContext.enforceCallingOrSelfPermission(
4365                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4366                }
4367            }
4368        }
4369    }
4370
4371    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4372        if (callingUid == Process.SHELL_UID) {
4373            if (userHandle >= 0
4374                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4375                throw new SecurityException("Shell does not have permission to access user "
4376                        + userHandle);
4377            } else if (userHandle < 0) {
4378                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4379                        + Debug.getCallers(3));
4380            }
4381        }
4382    }
4383
4384    private BasePermission findPermissionTreeLP(String permName) {
4385        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4386            if (permName.startsWith(bp.name) &&
4387                    permName.length() > bp.name.length() &&
4388                    permName.charAt(bp.name.length()) == '.') {
4389                return bp;
4390            }
4391        }
4392        return null;
4393    }
4394
4395    private BasePermission checkPermissionTreeLP(String permName) {
4396        if (permName != null) {
4397            BasePermission bp = findPermissionTreeLP(permName);
4398            if (bp != null) {
4399                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4400                    return bp;
4401                }
4402                throw new SecurityException("Calling uid "
4403                        + Binder.getCallingUid()
4404                        + " is not allowed to add to permission tree "
4405                        + bp.name + " owned by uid " + bp.uid);
4406            }
4407        }
4408        throw new SecurityException("No permission tree found for " + permName);
4409    }
4410
4411    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4412        if (s1 == null) {
4413            return s2 == null;
4414        }
4415        if (s2 == null) {
4416            return false;
4417        }
4418        if (s1.getClass() != s2.getClass()) {
4419            return false;
4420        }
4421        return s1.equals(s2);
4422    }
4423
4424    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4425        if (pi1.icon != pi2.icon) return false;
4426        if (pi1.logo != pi2.logo) return false;
4427        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4428        if (!compareStrings(pi1.name, pi2.name)) return false;
4429        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4430        // We'll take care of setting this one.
4431        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4432        // These are not currently stored in settings.
4433        //if (!compareStrings(pi1.group, pi2.group)) return false;
4434        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4435        //if (pi1.labelRes != pi2.labelRes) return false;
4436        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4437        return true;
4438    }
4439
4440    int permissionInfoFootprint(PermissionInfo info) {
4441        int size = info.name.length();
4442        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4443        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4444        return size;
4445    }
4446
4447    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4448        int size = 0;
4449        for (BasePermission perm : mSettings.mPermissions.values()) {
4450            if (perm.uid == tree.uid) {
4451                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4452            }
4453        }
4454        return size;
4455    }
4456
4457    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4458        // We calculate the max size of permissions defined by this uid and throw
4459        // if that plus the size of 'info' would exceed our stated maximum.
4460        if (tree.uid != Process.SYSTEM_UID) {
4461            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4462            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4463                throw new SecurityException("Permission tree size cap exceeded");
4464            }
4465        }
4466    }
4467
4468    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4469        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4470            throw new SecurityException("Label must be specified in permission");
4471        }
4472        BasePermission tree = checkPermissionTreeLP(info.name);
4473        BasePermission bp = mSettings.mPermissions.get(info.name);
4474        boolean added = bp == null;
4475        boolean changed = true;
4476        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4477        if (added) {
4478            enforcePermissionCapLocked(info, tree);
4479            bp = new BasePermission(info.name, tree.sourcePackage,
4480                    BasePermission.TYPE_DYNAMIC);
4481        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4482            throw new SecurityException(
4483                    "Not allowed to modify non-dynamic permission "
4484                    + info.name);
4485        } else {
4486            if (bp.protectionLevel == fixedLevel
4487                    && bp.perm.owner.equals(tree.perm.owner)
4488                    && bp.uid == tree.uid
4489                    && comparePermissionInfos(bp.perm.info, info)) {
4490                changed = false;
4491            }
4492        }
4493        bp.protectionLevel = fixedLevel;
4494        info = new PermissionInfo(info);
4495        info.protectionLevel = fixedLevel;
4496        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4497        bp.perm.info.packageName = tree.perm.info.packageName;
4498        bp.uid = tree.uid;
4499        if (added) {
4500            mSettings.mPermissions.put(info.name, bp);
4501        }
4502        if (changed) {
4503            if (!async) {
4504                mSettings.writeLPr();
4505            } else {
4506                scheduleWriteSettingsLocked();
4507            }
4508        }
4509        return added;
4510    }
4511
4512    @Override
4513    public boolean addPermission(PermissionInfo info) {
4514        synchronized (mPackages) {
4515            return addPermissionLocked(info, false);
4516        }
4517    }
4518
4519    @Override
4520    public boolean addPermissionAsync(PermissionInfo info) {
4521        synchronized (mPackages) {
4522            return addPermissionLocked(info, true);
4523        }
4524    }
4525
4526    @Override
4527    public void removePermission(String name) {
4528        synchronized (mPackages) {
4529            checkPermissionTreeLP(name);
4530            BasePermission bp = mSettings.mPermissions.get(name);
4531            if (bp != null) {
4532                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4533                    throw new SecurityException(
4534                            "Not allowed to modify non-dynamic permission "
4535                            + name);
4536                }
4537                mSettings.mPermissions.remove(name);
4538                mSettings.writeLPr();
4539            }
4540        }
4541    }
4542
4543    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4544            BasePermission bp) {
4545        int index = pkg.requestedPermissions.indexOf(bp.name);
4546        if (index == -1) {
4547            throw new SecurityException("Package " + pkg.packageName
4548                    + " has not requested permission " + bp.name);
4549        }
4550        if (!bp.isRuntime() && !bp.isDevelopment()) {
4551            throw new SecurityException("Permission " + bp.name
4552                    + " is not a changeable permission type");
4553        }
4554    }
4555
4556    @Override
4557    public void grantRuntimePermission(String packageName, String name, final int userId) {
4558        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4559    }
4560
4561    private void grantRuntimePermission(String packageName, String name, final int userId,
4562            boolean overridePolicy) {
4563        if (!sUserManager.exists(userId)) {
4564            Log.e(TAG, "No such user:" + userId);
4565            return;
4566        }
4567
4568        mContext.enforceCallingOrSelfPermission(
4569                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4570                "grantRuntimePermission");
4571
4572        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4573                true /* requireFullPermission */, true /* checkShell */,
4574                "grantRuntimePermission");
4575
4576        final int uid;
4577        final SettingBase sb;
4578
4579        synchronized (mPackages) {
4580            final PackageParser.Package pkg = mPackages.get(packageName);
4581            if (pkg == null) {
4582                throw new IllegalArgumentException("Unknown package: " + packageName);
4583            }
4584
4585            final BasePermission bp = mSettings.mPermissions.get(name);
4586            if (bp == null) {
4587                throw new IllegalArgumentException("Unknown permission: " + name);
4588            }
4589
4590            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4591
4592            // If a permission review is required for legacy apps we represent
4593            // their permissions as always granted runtime ones since we need
4594            // to keep the review required permission flag per user while an
4595            // install permission's state is shared across all users.
4596            if (mPermissionReviewRequired
4597                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4598                    && bp.isRuntime()) {
4599                return;
4600            }
4601
4602            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4603            sb = (SettingBase) pkg.mExtras;
4604            if (sb == null) {
4605                throw new IllegalArgumentException("Unknown package: " + packageName);
4606            }
4607
4608            final PermissionsState permissionsState = sb.getPermissionsState();
4609
4610            final int flags = permissionsState.getPermissionFlags(name, userId);
4611            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4612                throw new SecurityException("Cannot grant system fixed permission "
4613                        + name + " for package " + packageName);
4614            }
4615            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4616                throw new SecurityException("Cannot grant policy fixed permission "
4617                        + name + " for package " + packageName);
4618            }
4619
4620            if (bp.isDevelopment()) {
4621                // Development permissions must be handled specially, since they are not
4622                // normal runtime permissions.  For now they apply to all users.
4623                if (permissionsState.grantInstallPermission(bp) !=
4624                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4625                    scheduleWriteSettingsLocked();
4626                }
4627                return;
4628            }
4629
4630            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
4631                throw new SecurityException("Cannot grant non-ephemeral permission"
4632                        + name + " for package " + packageName);
4633            }
4634
4635            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4636                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4637                return;
4638            }
4639
4640            final int result = permissionsState.grantRuntimePermission(bp, userId);
4641            switch (result) {
4642                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4643                    return;
4644                }
4645
4646                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4647                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4648                    mHandler.post(new Runnable() {
4649                        @Override
4650                        public void run() {
4651                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4652                        }
4653                    });
4654                }
4655                break;
4656            }
4657
4658            if (bp.isRuntime()) {
4659                logPermissionGranted(mContext, name, packageName);
4660            }
4661
4662            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4663
4664            // Not critical if that is lost - app has to request again.
4665            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4666        }
4667
4668        // Only need to do this if user is initialized. Otherwise it's a new user
4669        // and there are no processes running as the user yet and there's no need
4670        // to make an expensive call to remount processes for the changed permissions.
4671        if (READ_EXTERNAL_STORAGE.equals(name)
4672                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4673            final long token = Binder.clearCallingIdentity();
4674            try {
4675                if (sUserManager.isInitialized(userId)) {
4676                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4677                            StorageManagerInternal.class);
4678                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4679                }
4680            } finally {
4681                Binder.restoreCallingIdentity(token);
4682            }
4683        }
4684    }
4685
4686    @Override
4687    public void revokeRuntimePermission(String packageName, String name, int userId) {
4688        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4689    }
4690
4691    private void revokeRuntimePermission(String packageName, String name, int userId,
4692            boolean overridePolicy) {
4693        if (!sUserManager.exists(userId)) {
4694            Log.e(TAG, "No such user:" + userId);
4695            return;
4696        }
4697
4698        mContext.enforceCallingOrSelfPermission(
4699                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4700                "revokeRuntimePermission");
4701
4702        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4703                true /* requireFullPermission */, true /* checkShell */,
4704                "revokeRuntimePermission");
4705
4706        final int appId;
4707
4708        synchronized (mPackages) {
4709            final PackageParser.Package pkg = mPackages.get(packageName);
4710            if (pkg == null) {
4711                throw new IllegalArgumentException("Unknown package: " + packageName);
4712            }
4713
4714            final BasePermission bp = mSettings.mPermissions.get(name);
4715            if (bp == null) {
4716                throw new IllegalArgumentException("Unknown permission: " + name);
4717            }
4718
4719            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4720
4721            // If a permission review is required for legacy apps we represent
4722            // their permissions as always granted runtime ones since we need
4723            // to keep the review required permission flag per user while an
4724            // install permission's state is shared across all users.
4725            if (mPermissionReviewRequired
4726                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4727                    && bp.isRuntime()) {
4728                return;
4729            }
4730
4731            SettingBase sb = (SettingBase) pkg.mExtras;
4732            if (sb == null) {
4733                throw new IllegalArgumentException("Unknown package: " + packageName);
4734            }
4735
4736            final PermissionsState permissionsState = sb.getPermissionsState();
4737
4738            final int flags = permissionsState.getPermissionFlags(name, userId);
4739            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4740                throw new SecurityException("Cannot revoke system fixed permission "
4741                        + name + " for package " + packageName);
4742            }
4743            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4744                throw new SecurityException("Cannot revoke policy fixed permission "
4745                        + name + " for package " + packageName);
4746            }
4747
4748            if (bp.isDevelopment()) {
4749                // Development permissions must be handled specially, since they are not
4750                // normal runtime permissions.  For now they apply to all users.
4751                if (permissionsState.revokeInstallPermission(bp) !=
4752                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4753                    scheduleWriteSettingsLocked();
4754                }
4755                return;
4756            }
4757
4758            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4759                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4760                return;
4761            }
4762
4763            if (bp.isRuntime()) {
4764                logPermissionRevoked(mContext, name, packageName);
4765            }
4766
4767            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4768
4769            // Critical, after this call app should never have the permission.
4770            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4771
4772            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4773        }
4774
4775        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4776    }
4777
4778    /**
4779     * Get the first event id for the permission.
4780     *
4781     * <p>There are four events for each permission: <ul>
4782     *     <li>Request permission: first id + 0</li>
4783     *     <li>Grant permission: first id + 1</li>
4784     *     <li>Request for permission denied: first id + 2</li>
4785     *     <li>Revoke permission: first id + 3</li>
4786     * </ul></p>
4787     *
4788     * @param name name of the permission
4789     *
4790     * @return The first event id for the permission
4791     */
4792    private static int getBaseEventId(@NonNull String name) {
4793        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4794
4795        if (eventIdIndex == -1) {
4796            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4797                    || "user".equals(Build.TYPE)) {
4798                Log.i(TAG, "Unknown permission " + name);
4799
4800                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4801            } else {
4802                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4803                //
4804                // Also update
4805                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4806                // - metrics_constants.proto
4807                throw new IllegalStateException("Unknown permission " + name);
4808            }
4809        }
4810
4811        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4812    }
4813
4814    /**
4815     * Log that a permission was revoked.
4816     *
4817     * @param context Context of the caller
4818     * @param name name of the permission
4819     * @param packageName package permission if for
4820     */
4821    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4822            @NonNull String packageName) {
4823        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4824    }
4825
4826    /**
4827     * Log that a permission request was granted.
4828     *
4829     * @param context Context of the caller
4830     * @param name name of the permission
4831     * @param packageName package permission if for
4832     */
4833    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4834            @NonNull String packageName) {
4835        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4836    }
4837
4838    @Override
4839    public void resetRuntimePermissions() {
4840        mContext.enforceCallingOrSelfPermission(
4841                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4842                "revokeRuntimePermission");
4843
4844        int callingUid = Binder.getCallingUid();
4845        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4846            mContext.enforceCallingOrSelfPermission(
4847                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4848                    "resetRuntimePermissions");
4849        }
4850
4851        synchronized (mPackages) {
4852            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4853            for (int userId : UserManagerService.getInstance().getUserIds()) {
4854                final int packageCount = mPackages.size();
4855                for (int i = 0; i < packageCount; i++) {
4856                    PackageParser.Package pkg = mPackages.valueAt(i);
4857                    if (!(pkg.mExtras instanceof PackageSetting)) {
4858                        continue;
4859                    }
4860                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4861                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4862                }
4863            }
4864        }
4865    }
4866
4867    @Override
4868    public int getPermissionFlags(String name, String packageName, int userId) {
4869        if (!sUserManager.exists(userId)) {
4870            return 0;
4871        }
4872
4873        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4874
4875        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4876                true /* requireFullPermission */, false /* checkShell */,
4877                "getPermissionFlags");
4878
4879        synchronized (mPackages) {
4880            final PackageParser.Package pkg = mPackages.get(packageName);
4881            if (pkg == null) {
4882                return 0;
4883            }
4884
4885            final BasePermission bp = mSettings.mPermissions.get(name);
4886            if (bp == null) {
4887                return 0;
4888            }
4889
4890            SettingBase sb = (SettingBase) pkg.mExtras;
4891            if (sb == null) {
4892                return 0;
4893            }
4894
4895            PermissionsState permissionsState = sb.getPermissionsState();
4896            return permissionsState.getPermissionFlags(name, userId);
4897        }
4898    }
4899
4900    @Override
4901    public void updatePermissionFlags(String name, String packageName, int flagMask,
4902            int flagValues, int userId) {
4903        if (!sUserManager.exists(userId)) {
4904            return;
4905        }
4906
4907        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4908
4909        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4910                true /* requireFullPermission */, true /* checkShell */,
4911                "updatePermissionFlags");
4912
4913        // Only the system can change these flags and nothing else.
4914        if (getCallingUid() != Process.SYSTEM_UID) {
4915            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4916            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4917            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4918            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4919            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4920        }
4921
4922        synchronized (mPackages) {
4923            final PackageParser.Package pkg = mPackages.get(packageName);
4924            if (pkg == null) {
4925                throw new IllegalArgumentException("Unknown package: " + packageName);
4926            }
4927
4928            final BasePermission bp = mSettings.mPermissions.get(name);
4929            if (bp == null) {
4930                throw new IllegalArgumentException("Unknown permission: " + name);
4931            }
4932
4933            SettingBase sb = (SettingBase) pkg.mExtras;
4934            if (sb == null) {
4935                throw new IllegalArgumentException("Unknown package: " + packageName);
4936            }
4937
4938            PermissionsState permissionsState = sb.getPermissionsState();
4939
4940            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4941
4942            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4943                // Install and runtime permissions are stored in different places,
4944                // so figure out what permission changed and persist the change.
4945                if (permissionsState.getInstallPermissionState(name) != null) {
4946                    scheduleWriteSettingsLocked();
4947                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4948                        || hadState) {
4949                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4950                }
4951            }
4952        }
4953    }
4954
4955    /**
4956     * Update the permission flags for all packages and runtime permissions of a user in order
4957     * to allow device or profile owner to remove POLICY_FIXED.
4958     */
4959    @Override
4960    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4961        if (!sUserManager.exists(userId)) {
4962            return;
4963        }
4964
4965        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4966
4967        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4968                true /* requireFullPermission */, true /* checkShell */,
4969                "updatePermissionFlagsForAllApps");
4970
4971        // Only the system can change system fixed flags.
4972        if (getCallingUid() != Process.SYSTEM_UID) {
4973            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4974            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4975        }
4976
4977        synchronized (mPackages) {
4978            boolean changed = false;
4979            final int packageCount = mPackages.size();
4980            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4981                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4982                SettingBase sb = (SettingBase) pkg.mExtras;
4983                if (sb == null) {
4984                    continue;
4985                }
4986                PermissionsState permissionsState = sb.getPermissionsState();
4987                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4988                        userId, flagMask, flagValues);
4989            }
4990            if (changed) {
4991                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4992            }
4993        }
4994    }
4995
4996    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4997        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4998                != PackageManager.PERMISSION_GRANTED
4999            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5000                != PackageManager.PERMISSION_GRANTED) {
5001            throw new SecurityException(message + " requires "
5002                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5003                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5004        }
5005    }
5006
5007    @Override
5008    public boolean shouldShowRequestPermissionRationale(String permissionName,
5009            String packageName, int userId) {
5010        if (UserHandle.getCallingUserId() != userId) {
5011            mContext.enforceCallingPermission(
5012                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5013                    "canShowRequestPermissionRationale for user " + userId);
5014        }
5015
5016        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5017        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5018            return false;
5019        }
5020
5021        if (checkPermission(permissionName, packageName, userId)
5022                == PackageManager.PERMISSION_GRANTED) {
5023            return false;
5024        }
5025
5026        final int flags;
5027
5028        final long identity = Binder.clearCallingIdentity();
5029        try {
5030            flags = getPermissionFlags(permissionName,
5031                    packageName, userId);
5032        } finally {
5033            Binder.restoreCallingIdentity(identity);
5034        }
5035
5036        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5037                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5038                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5039
5040        if ((flags & fixedFlags) != 0) {
5041            return false;
5042        }
5043
5044        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5045    }
5046
5047    @Override
5048    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5049        mContext.enforceCallingOrSelfPermission(
5050                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5051                "addOnPermissionsChangeListener");
5052
5053        synchronized (mPackages) {
5054            mOnPermissionChangeListeners.addListenerLocked(listener);
5055        }
5056    }
5057
5058    @Override
5059    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5060        synchronized (mPackages) {
5061            mOnPermissionChangeListeners.removeListenerLocked(listener);
5062        }
5063    }
5064
5065    @Override
5066    public boolean isProtectedBroadcast(String actionName) {
5067        synchronized (mPackages) {
5068            if (mProtectedBroadcasts.contains(actionName)) {
5069                return true;
5070            } else if (actionName != null) {
5071                // TODO: remove these terrible hacks
5072                if (actionName.startsWith("android.net.netmon.lingerExpired")
5073                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5074                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5075                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5076                    return true;
5077                }
5078            }
5079        }
5080        return false;
5081    }
5082
5083    @Override
5084    public int checkSignatures(String pkg1, String pkg2) {
5085        synchronized (mPackages) {
5086            final PackageParser.Package p1 = mPackages.get(pkg1);
5087            final PackageParser.Package p2 = mPackages.get(pkg2);
5088            if (p1 == null || p1.mExtras == null
5089                    || p2 == null || p2.mExtras == null) {
5090                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5091            }
5092            return compareSignatures(p1.mSignatures, p2.mSignatures);
5093        }
5094    }
5095
5096    @Override
5097    public int checkUidSignatures(int uid1, int uid2) {
5098        // Map to base uids.
5099        uid1 = UserHandle.getAppId(uid1);
5100        uid2 = UserHandle.getAppId(uid2);
5101        // reader
5102        synchronized (mPackages) {
5103            Signature[] s1;
5104            Signature[] s2;
5105            Object obj = mSettings.getUserIdLPr(uid1);
5106            if (obj != null) {
5107                if (obj instanceof SharedUserSetting) {
5108                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5109                } else if (obj instanceof PackageSetting) {
5110                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5111                } else {
5112                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5113                }
5114            } else {
5115                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5116            }
5117            obj = mSettings.getUserIdLPr(uid2);
5118            if (obj != null) {
5119                if (obj instanceof SharedUserSetting) {
5120                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5121                } else if (obj instanceof PackageSetting) {
5122                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5123                } else {
5124                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5125                }
5126            } else {
5127                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5128            }
5129            return compareSignatures(s1, s2);
5130        }
5131    }
5132
5133    /**
5134     * This method should typically only be used when granting or revoking
5135     * permissions, since the app may immediately restart after this call.
5136     * <p>
5137     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5138     * guard your work against the app being relaunched.
5139     */
5140    private void killUid(int appId, int userId, String reason) {
5141        final long identity = Binder.clearCallingIdentity();
5142        try {
5143            IActivityManager am = ActivityManager.getService();
5144            if (am != null) {
5145                try {
5146                    am.killUid(appId, userId, reason);
5147                } catch (RemoteException e) {
5148                    /* ignore - same process */
5149                }
5150            }
5151        } finally {
5152            Binder.restoreCallingIdentity(identity);
5153        }
5154    }
5155
5156    /**
5157     * Compares two sets of signatures. Returns:
5158     * <br />
5159     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5160     * <br />
5161     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5162     * <br />
5163     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5164     * <br />
5165     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5166     * <br />
5167     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5168     */
5169    static int compareSignatures(Signature[] s1, Signature[] s2) {
5170        if (s1 == null) {
5171            return s2 == null
5172                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5173                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5174        }
5175
5176        if (s2 == null) {
5177            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5178        }
5179
5180        if (s1.length != s2.length) {
5181            return PackageManager.SIGNATURE_NO_MATCH;
5182        }
5183
5184        // Since both signature sets are of size 1, we can compare without HashSets.
5185        if (s1.length == 1) {
5186            return s1[0].equals(s2[0]) ?
5187                    PackageManager.SIGNATURE_MATCH :
5188                    PackageManager.SIGNATURE_NO_MATCH;
5189        }
5190
5191        ArraySet<Signature> set1 = new ArraySet<Signature>();
5192        for (Signature sig : s1) {
5193            set1.add(sig);
5194        }
5195        ArraySet<Signature> set2 = new ArraySet<Signature>();
5196        for (Signature sig : s2) {
5197            set2.add(sig);
5198        }
5199        // Make sure s2 contains all signatures in s1.
5200        if (set1.equals(set2)) {
5201            return PackageManager.SIGNATURE_MATCH;
5202        }
5203        return PackageManager.SIGNATURE_NO_MATCH;
5204    }
5205
5206    /**
5207     * If the database version for this type of package (internal storage or
5208     * external storage) is less than the version where package signatures
5209     * were updated, return true.
5210     */
5211    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5212        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5213        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5214    }
5215
5216    /**
5217     * Used for backward compatibility to make sure any packages with
5218     * certificate chains get upgraded to the new style. {@code existingSigs}
5219     * will be in the old format (since they were stored on disk from before the
5220     * system upgrade) and {@code scannedSigs} will be in the newer format.
5221     */
5222    private int compareSignaturesCompat(PackageSignatures existingSigs,
5223            PackageParser.Package scannedPkg) {
5224        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5225            return PackageManager.SIGNATURE_NO_MATCH;
5226        }
5227
5228        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5229        for (Signature sig : existingSigs.mSignatures) {
5230            existingSet.add(sig);
5231        }
5232        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5233        for (Signature sig : scannedPkg.mSignatures) {
5234            try {
5235                Signature[] chainSignatures = sig.getChainSignatures();
5236                for (Signature chainSig : chainSignatures) {
5237                    scannedCompatSet.add(chainSig);
5238                }
5239            } catch (CertificateEncodingException e) {
5240                scannedCompatSet.add(sig);
5241            }
5242        }
5243        /*
5244         * Make sure the expanded scanned set contains all signatures in the
5245         * existing one.
5246         */
5247        if (scannedCompatSet.equals(existingSet)) {
5248            // Migrate the old signatures to the new scheme.
5249            existingSigs.assignSignatures(scannedPkg.mSignatures);
5250            // The new KeySets will be re-added later in the scanning process.
5251            synchronized (mPackages) {
5252                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5253            }
5254            return PackageManager.SIGNATURE_MATCH;
5255        }
5256        return PackageManager.SIGNATURE_NO_MATCH;
5257    }
5258
5259    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5260        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5261        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5262    }
5263
5264    private int compareSignaturesRecover(PackageSignatures existingSigs,
5265            PackageParser.Package scannedPkg) {
5266        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5267            return PackageManager.SIGNATURE_NO_MATCH;
5268        }
5269
5270        String msg = null;
5271        try {
5272            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5273                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5274                        + scannedPkg.packageName);
5275                return PackageManager.SIGNATURE_MATCH;
5276            }
5277        } catch (CertificateException e) {
5278            msg = e.getMessage();
5279        }
5280
5281        logCriticalInfo(Log.INFO,
5282                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5283        return PackageManager.SIGNATURE_NO_MATCH;
5284    }
5285
5286    @Override
5287    public List<String> getAllPackages() {
5288        synchronized (mPackages) {
5289            return new ArrayList<String>(mPackages.keySet());
5290        }
5291    }
5292
5293    @Override
5294    public String[] getPackagesForUid(int uid) {
5295        final int userId = UserHandle.getUserId(uid);
5296        uid = UserHandle.getAppId(uid);
5297        // reader
5298        synchronized (mPackages) {
5299            Object obj = mSettings.getUserIdLPr(uid);
5300            if (obj instanceof SharedUserSetting) {
5301                final SharedUserSetting sus = (SharedUserSetting) obj;
5302                final int N = sus.packages.size();
5303                String[] res = new String[N];
5304                final Iterator<PackageSetting> it = sus.packages.iterator();
5305                int i = 0;
5306                while (it.hasNext()) {
5307                    PackageSetting ps = it.next();
5308                    if (ps.getInstalled(userId)) {
5309                        res[i++] = ps.name;
5310                    } else {
5311                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5312                    }
5313                }
5314                return res;
5315            } else if (obj instanceof PackageSetting) {
5316                final PackageSetting ps = (PackageSetting) obj;
5317                if (ps.getInstalled(userId)) {
5318                    return new String[]{ps.name};
5319                }
5320            }
5321        }
5322        return null;
5323    }
5324
5325    @Override
5326    public String getNameForUid(int uid) {
5327        // reader
5328        synchronized (mPackages) {
5329            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5330            if (obj instanceof SharedUserSetting) {
5331                final SharedUserSetting sus = (SharedUserSetting) obj;
5332                return sus.name + ":" + sus.userId;
5333            } else if (obj instanceof PackageSetting) {
5334                final PackageSetting ps = (PackageSetting) obj;
5335                return ps.name;
5336            }
5337        }
5338        return null;
5339    }
5340
5341    @Override
5342    public int getUidForSharedUser(String sharedUserName) {
5343        if(sharedUserName == null) {
5344            return -1;
5345        }
5346        // reader
5347        synchronized (mPackages) {
5348            SharedUserSetting suid;
5349            try {
5350                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5351                if (suid != null) {
5352                    return suid.userId;
5353                }
5354            } catch (PackageManagerException ignore) {
5355                // can't happen, but, still need to catch it
5356            }
5357            return -1;
5358        }
5359    }
5360
5361    @Override
5362    public int getFlagsForUid(int uid) {
5363        synchronized (mPackages) {
5364            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5365            if (obj instanceof SharedUserSetting) {
5366                final SharedUserSetting sus = (SharedUserSetting) obj;
5367                return sus.pkgFlags;
5368            } else if (obj instanceof PackageSetting) {
5369                final PackageSetting ps = (PackageSetting) obj;
5370                return ps.pkgFlags;
5371            }
5372        }
5373        return 0;
5374    }
5375
5376    @Override
5377    public int getPrivateFlagsForUid(int uid) {
5378        synchronized (mPackages) {
5379            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5380            if (obj instanceof SharedUserSetting) {
5381                final SharedUserSetting sus = (SharedUserSetting) obj;
5382                return sus.pkgPrivateFlags;
5383            } else if (obj instanceof PackageSetting) {
5384                final PackageSetting ps = (PackageSetting) obj;
5385                return ps.pkgPrivateFlags;
5386            }
5387        }
5388        return 0;
5389    }
5390
5391    @Override
5392    public boolean isUidPrivileged(int uid) {
5393        uid = UserHandle.getAppId(uid);
5394        // reader
5395        synchronized (mPackages) {
5396            Object obj = mSettings.getUserIdLPr(uid);
5397            if (obj instanceof SharedUserSetting) {
5398                final SharedUserSetting sus = (SharedUserSetting) obj;
5399                final Iterator<PackageSetting> it = sus.packages.iterator();
5400                while (it.hasNext()) {
5401                    if (it.next().isPrivileged()) {
5402                        return true;
5403                    }
5404                }
5405            } else if (obj instanceof PackageSetting) {
5406                final PackageSetting ps = (PackageSetting) obj;
5407                return ps.isPrivileged();
5408            }
5409        }
5410        return false;
5411    }
5412
5413    @Override
5414    public String[] getAppOpPermissionPackages(String permissionName) {
5415        synchronized (mPackages) {
5416            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5417            if (pkgs == null) {
5418                return null;
5419            }
5420            return pkgs.toArray(new String[pkgs.size()]);
5421        }
5422    }
5423
5424    @Override
5425    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5426            int flags, int userId) {
5427        try {
5428            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5429
5430            if (!sUserManager.exists(userId)) return null;
5431            flags = updateFlagsForResolve(flags, userId, intent);
5432            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5433                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5434
5435            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5436            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5437                    flags, userId);
5438            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5439
5440            final ResolveInfo bestChoice =
5441                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5442            return bestChoice;
5443        } finally {
5444            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5445        }
5446    }
5447
5448    @Override
5449    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5450        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5451            throw new SecurityException(
5452                    "findPersistentPreferredActivity can only be run by the system");
5453        }
5454        if (!sUserManager.exists(userId)) {
5455            return null;
5456        }
5457        intent = updateIntentForResolve(intent);
5458        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5459        final int flags = updateFlagsForResolve(0, userId, intent);
5460        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5461                userId);
5462        synchronized (mPackages) {
5463            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5464                    userId);
5465        }
5466    }
5467
5468    @Override
5469    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5470            IntentFilter filter, int match, ComponentName activity) {
5471        final int userId = UserHandle.getCallingUserId();
5472        if (DEBUG_PREFERRED) {
5473            Log.v(TAG, "setLastChosenActivity intent=" + intent
5474                + " resolvedType=" + resolvedType
5475                + " flags=" + flags
5476                + " filter=" + filter
5477                + " match=" + match
5478                + " activity=" + activity);
5479            filter.dump(new PrintStreamPrinter(System.out), "    ");
5480        }
5481        intent.setComponent(null);
5482        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5483                userId);
5484        // Find any earlier preferred or last chosen entries and nuke them
5485        findPreferredActivity(intent, resolvedType,
5486                flags, query, 0, false, true, false, userId);
5487        // Add the new activity as the last chosen for this filter
5488        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5489                "Setting last chosen");
5490    }
5491
5492    @Override
5493    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5494        final int userId = UserHandle.getCallingUserId();
5495        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5496        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5497                userId);
5498        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5499                false, false, false, userId);
5500    }
5501
5502    private boolean isEphemeralDisabled() {
5503        // ephemeral apps have been disabled across the board
5504        if (DISABLE_EPHEMERAL_APPS) {
5505            return true;
5506        }
5507        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5508        if (!mSystemReady) {
5509            return true;
5510        }
5511        // we can't get a content resolver until the system is ready; these checks must happen last
5512        final ContentResolver resolver = mContext.getContentResolver();
5513        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5514            return true;
5515        }
5516        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5517    }
5518
5519    private boolean isEphemeralAllowed(
5520            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5521            boolean skipPackageCheck) {
5522        // Short circuit and return early if possible.
5523        if (isEphemeralDisabled()) {
5524            return false;
5525        }
5526        final int callingUser = UserHandle.getCallingUserId();
5527        if (callingUser != UserHandle.USER_SYSTEM) {
5528            return false;
5529        }
5530        if (mEphemeralResolverConnection == null) {
5531            return false;
5532        }
5533        if (mEphemeralInstallerComponent == null) {
5534            return false;
5535        }
5536        if (intent.getComponent() != null) {
5537            return false;
5538        }
5539        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5540            return false;
5541        }
5542        if (!skipPackageCheck && intent.getPackage() != null) {
5543            return false;
5544        }
5545        final boolean isWebUri = hasWebURI(intent);
5546        if (!isWebUri || intent.getData().getHost() == null) {
5547            return false;
5548        }
5549        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5550        synchronized (mPackages) {
5551            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5552            for (int n = 0; n < count; n++) {
5553                ResolveInfo info = resolvedActivities.get(n);
5554                String packageName = info.activityInfo.packageName;
5555                PackageSetting ps = mSettings.mPackages.get(packageName);
5556                if (ps != null) {
5557                    // Try to get the status from User settings first
5558                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5559                    int status = (int) (packedStatus >> 32);
5560                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5561                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5562                        if (DEBUG_EPHEMERAL) {
5563                            Slog.v(TAG, "DENY ephemeral apps;"
5564                                + " pkg: " + packageName + ", status: " + status);
5565                        }
5566                        return false;
5567                    }
5568                }
5569            }
5570        }
5571        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5572        return true;
5573    }
5574
5575    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5576            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5577            int userId) {
5578        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5579                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5580                        callingPackage, userId));
5581        mHandler.sendMessage(msg);
5582    }
5583
5584    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5585            int flags, List<ResolveInfo> query, int userId) {
5586        if (query != null) {
5587            final int N = query.size();
5588            if (N == 1) {
5589                return query.get(0);
5590            } else if (N > 1) {
5591                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5592                // If there is more than one activity with the same priority,
5593                // then let the user decide between them.
5594                ResolveInfo r0 = query.get(0);
5595                ResolveInfo r1 = query.get(1);
5596                if (DEBUG_INTENT_MATCHING || debug) {
5597                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5598                            + r1.activityInfo.name + "=" + r1.priority);
5599                }
5600                // If the first activity has a higher priority, or a different
5601                // default, then it is always desirable to pick it.
5602                if (r0.priority != r1.priority
5603                        || r0.preferredOrder != r1.preferredOrder
5604                        || r0.isDefault != r1.isDefault) {
5605                    return query.get(0);
5606                }
5607                // If we have saved a preference for a preferred activity for
5608                // this Intent, use that.
5609                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5610                        flags, query, r0.priority, true, false, debug, userId);
5611                if (ri != null) {
5612                    return ri;
5613                }
5614                ri = new ResolveInfo(mResolveInfo);
5615                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5616                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5617                // If all of the options come from the same package, show the application's
5618                // label and icon instead of the generic resolver's.
5619                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5620                // and then throw away the ResolveInfo itself, meaning that the caller loses
5621                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5622                // a fallback for this case; we only set the target package's resources on
5623                // the ResolveInfo, not the ActivityInfo.
5624                final String intentPackage = intent.getPackage();
5625                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5626                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5627                    ri.resolvePackageName = intentPackage;
5628                    if (userNeedsBadging(userId)) {
5629                        ri.noResourceId = true;
5630                    } else {
5631                        ri.icon = appi.icon;
5632                    }
5633                    ri.iconResourceId = appi.icon;
5634                    ri.labelRes = appi.labelRes;
5635                }
5636                ri.activityInfo.applicationInfo = new ApplicationInfo(
5637                        ri.activityInfo.applicationInfo);
5638                if (userId != 0) {
5639                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5640                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5641                }
5642                // Make sure that the resolver is displayable in car mode
5643                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5644                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5645                return ri;
5646            }
5647        }
5648        return null;
5649    }
5650
5651    /**
5652     * Return true if the given list is not empty and all of its contents have
5653     * an activityInfo with the given package name.
5654     */
5655    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5656        if (ArrayUtils.isEmpty(list)) {
5657            return false;
5658        }
5659        for (int i = 0, N = list.size(); i < N; i++) {
5660            final ResolveInfo ri = list.get(i);
5661            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5662            if (ai == null || !packageName.equals(ai.packageName)) {
5663                return false;
5664            }
5665        }
5666        return true;
5667    }
5668
5669    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5670            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5671        final int N = query.size();
5672        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5673                .get(userId);
5674        // Get the list of persistent preferred activities that handle the intent
5675        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5676        List<PersistentPreferredActivity> pprefs = ppir != null
5677                ? ppir.queryIntent(intent, resolvedType,
5678                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5679                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5680                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5681                : null;
5682        if (pprefs != null && pprefs.size() > 0) {
5683            final int M = pprefs.size();
5684            for (int i=0; i<M; i++) {
5685                final PersistentPreferredActivity ppa = pprefs.get(i);
5686                if (DEBUG_PREFERRED || debug) {
5687                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5688                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5689                            + "\n  component=" + ppa.mComponent);
5690                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5691                }
5692                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5693                        flags | MATCH_DISABLED_COMPONENTS, userId);
5694                if (DEBUG_PREFERRED || debug) {
5695                    Slog.v(TAG, "Found persistent preferred activity:");
5696                    if (ai != null) {
5697                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5698                    } else {
5699                        Slog.v(TAG, "  null");
5700                    }
5701                }
5702                if (ai == null) {
5703                    // This previously registered persistent preferred activity
5704                    // component is no longer known. Ignore it and do NOT remove it.
5705                    continue;
5706                }
5707                for (int j=0; j<N; j++) {
5708                    final ResolveInfo ri = query.get(j);
5709                    if (!ri.activityInfo.applicationInfo.packageName
5710                            .equals(ai.applicationInfo.packageName)) {
5711                        continue;
5712                    }
5713                    if (!ri.activityInfo.name.equals(ai.name)) {
5714                        continue;
5715                    }
5716                    //  Found a persistent preference that can handle the intent.
5717                    if (DEBUG_PREFERRED || debug) {
5718                        Slog.v(TAG, "Returning persistent preferred activity: " +
5719                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5720                    }
5721                    return ri;
5722                }
5723            }
5724        }
5725        return null;
5726    }
5727
5728    // TODO: handle preferred activities missing while user has amnesia
5729    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5730            List<ResolveInfo> query, int priority, boolean always,
5731            boolean removeMatches, boolean debug, int userId) {
5732        if (!sUserManager.exists(userId)) return null;
5733        flags = updateFlagsForResolve(flags, userId, intent);
5734        intent = updateIntentForResolve(intent);
5735        // writer
5736        synchronized (mPackages) {
5737            // Try to find a matching persistent preferred activity.
5738            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5739                    debug, userId);
5740
5741            // If a persistent preferred activity matched, use it.
5742            if (pri != null) {
5743                return pri;
5744            }
5745
5746            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5747            // Get the list of preferred activities that handle the intent
5748            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5749            List<PreferredActivity> prefs = pir != null
5750                    ? pir.queryIntent(intent, resolvedType,
5751                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5752                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5753                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5754                    : null;
5755            if (prefs != null && prefs.size() > 0) {
5756                boolean changed = false;
5757                try {
5758                    // First figure out how good the original match set is.
5759                    // We will only allow preferred activities that came
5760                    // from the same match quality.
5761                    int match = 0;
5762
5763                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5764
5765                    final int N = query.size();
5766                    for (int j=0; j<N; j++) {
5767                        final ResolveInfo ri = query.get(j);
5768                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5769                                + ": 0x" + Integer.toHexString(match));
5770                        if (ri.match > match) {
5771                            match = ri.match;
5772                        }
5773                    }
5774
5775                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5776                            + Integer.toHexString(match));
5777
5778                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5779                    final int M = prefs.size();
5780                    for (int i=0; i<M; i++) {
5781                        final PreferredActivity pa = prefs.get(i);
5782                        if (DEBUG_PREFERRED || debug) {
5783                            Slog.v(TAG, "Checking PreferredActivity ds="
5784                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5785                                    + "\n  component=" + pa.mPref.mComponent);
5786                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5787                        }
5788                        if (pa.mPref.mMatch != match) {
5789                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5790                                    + Integer.toHexString(pa.mPref.mMatch));
5791                            continue;
5792                        }
5793                        // If it's not an "always" type preferred activity and that's what we're
5794                        // looking for, skip it.
5795                        if (always && !pa.mPref.mAlways) {
5796                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5797                            continue;
5798                        }
5799                        final ActivityInfo ai = getActivityInfo(
5800                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5801                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5802                                userId);
5803                        if (DEBUG_PREFERRED || debug) {
5804                            Slog.v(TAG, "Found preferred activity:");
5805                            if (ai != null) {
5806                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5807                            } else {
5808                                Slog.v(TAG, "  null");
5809                            }
5810                        }
5811                        if (ai == null) {
5812                            // This previously registered preferred activity
5813                            // component is no longer known.  Most likely an update
5814                            // to the app was installed and in the new version this
5815                            // component no longer exists.  Clean it up by removing
5816                            // it from the preferred activities list, and skip it.
5817                            Slog.w(TAG, "Removing dangling preferred activity: "
5818                                    + pa.mPref.mComponent);
5819                            pir.removeFilter(pa);
5820                            changed = true;
5821                            continue;
5822                        }
5823                        for (int j=0; j<N; j++) {
5824                            final ResolveInfo ri = query.get(j);
5825                            if (!ri.activityInfo.applicationInfo.packageName
5826                                    .equals(ai.applicationInfo.packageName)) {
5827                                continue;
5828                            }
5829                            if (!ri.activityInfo.name.equals(ai.name)) {
5830                                continue;
5831                            }
5832
5833                            if (removeMatches) {
5834                                pir.removeFilter(pa);
5835                                changed = true;
5836                                if (DEBUG_PREFERRED) {
5837                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5838                                }
5839                                break;
5840                            }
5841
5842                            // Okay we found a previously set preferred or last chosen app.
5843                            // If the result set is different from when this
5844                            // was created, we need to clear it and re-ask the
5845                            // user their preference, if we're looking for an "always" type entry.
5846                            if (always && !pa.mPref.sameSet(query)) {
5847                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5848                                        + intent + " type " + resolvedType);
5849                                if (DEBUG_PREFERRED) {
5850                                    Slog.v(TAG, "Removing preferred activity since set changed "
5851                                            + pa.mPref.mComponent);
5852                                }
5853                                pir.removeFilter(pa);
5854                                // Re-add the filter as a "last chosen" entry (!always)
5855                                PreferredActivity lastChosen = new PreferredActivity(
5856                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5857                                pir.addFilter(lastChosen);
5858                                changed = true;
5859                                return null;
5860                            }
5861
5862                            // Yay! Either the set matched or we're looking for the last chosen
5863                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5864                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5865                            return ri;
5866                        }
5867                    }
5868                } finally {
5869                    if (changed) {
5870                        if (DEBUG_PREFERRED) {
5871                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5872                        }
5873                        scheduleWritePackageRestrictionsLocked(userId);
5874                    }
5875                }
5876            }
5877        }
5878        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5879        return null;
5880    }
5881
5882    /*
5883     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5884     */
5885    @Override
5886    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5887            int targetUserId) {
5888        mContext.enforceCallingOrSelfPermission(
5889                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5890        List<CrossProfileIntentFilter> matches =
5891                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5892        if (matches != null) {
5893            int size = matches.size();
5894            for (int i = 0; i < size; i++) {
5895                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5896            }
5897        }
5898        if (hasWebURI(intent)) {
5899            // cross-profile app linking works only towards the parent.
5900            final UserInfo parent = getProfileParent(sourceUserId);
5901            synchronized(mPackages) {
5902                int flags = updateFlagsForResolve(0, parent.id, intent);
5903                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5904                        intent, resolvedType, flags, sourceUserId, parent.id);
5905                return xpDomainInfo != null;
5906            }
5907        }
5908        return false;
5909    }
5910
5911    private UserInfo getProfileParent(int userId) {
5912        final long identity = Binder.clearCallingIdentity();
5913        try {
5914            return sUserManager.getProfileParent(userId);
5915        } finally {
5916            Binder.restoreCallingIdentity(identity);
5917        }
5918    }
5919
5920    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5921            String resolvedType, int userId) {
5922        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5923        if (resolver != null) {
5924            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5925                    false /*visibleToEphemeral*/, false /*isInstant*/, userId);
5926        }
5927        return null;
5928    }
5929
5930    @Override
5931    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5932            String resolvedType, int flags, int userId) {
5933        try {
5934            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5935
5936            return new ParceledListSlice<>(
5937                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5938        } finally {
5939            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5940        }
5941    }
5942
5943    /**
5944     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5945     * ephemeral, returns {@code null}.
5946     */
5947    private String getEphemeralPackageName(int callingUid) {
5948        final int appId = UserHandle.getAppId(callingUid);
5949        synchronized (mPackages) {
5950            final Object obj = mSettings.getUserIdLPr(appId);
5951            if (obj instanceof PackageSetting) {
5952                final PackageSetting ps = (PackageSetting) obj;
5953                return ps.pkg.applicationInfo.isInstantApp() ? ps.pkg.packageName : null;
5954            }
5955        }
5956        return null;
5957    }
5958
5959    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5960            String resolvedType, int flags, int userId) {
5961        if (!sUserManager.exists(userId)) return Collections.emptyList();
5962        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5963        flags = updateFlagsForResolve(flags, userId, intent);
5964        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5965                false /* requireFullPermission */, false /* checkShell */,
5966                "query intent activities");
5967        ComponentName comp = intent.getComponent();
5968        if (comp == null) {
5969            if (intent.getSelector() != null) {
5970                intent = intent.getSelector();
5971                comp = intent.getComponent();
5972            }
5973        }
5974
5975        if (comp != null) {
5976            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5977            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5978            if (ai != null) {
5979                // When specifying an explicit component, we prevent the activity from being
5980                // used when either 1) the calling package is normal and the activity is within
5981                // an ephemeral application or 2) the calling package is ephemeral and the
5982                // activity is not visible to ephemeral applications.
5983                boolean matchEphemeral =
5984                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5985                boolean ephemeralVisibleOnly =
5986                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5987                boolean blockResolution =
5988                        (!matchEphemeral && ephemeralPkgName == null
5989                                && (ai.applicationInfo.privateFlags
5990                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5991                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5992                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5993                if (!blockResolution) {
5994                    final ResolveInfo ri = new ResolveInfo();
5995                    ri.activityInfo = ai;
5996                    list.add(ri);
5997                }
5998            }
5999            return list;
6000        }
6001
6002        // reader
6003        boolean sortResult = false;
6004        boolean addEphemeral = false;
6005        List<ResolveInfo> result;
6006        final String pkgName = intent.getPackage();
6007        synchronized (mPackages) {
6008            if (pkgName == null) {
6009                List<CrossProfileIntentFilter> matchingFilters =
6010                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6011                // Check for results that need to skip the current profile.
6012                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6013                        resolvedType, flags, userId);
6014                if (xpResolveInfo != null) {
6015                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6016                    xpResult.add(xpResolveInfo);
6017                    return filterForEphemeral(
6018                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
6019                }
6020
6021                // Check for results in the current profile.
6022                result = filterIfNotSystemUser(mActivities.queryIntent(
6023                        intent, resolvedType, flags, userId), userId);
6024                addEphemeral =
6025                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6026
6027                // Check for cross profile results.
6028                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6029                xpResolveInfo = queryCrossProfileIntents(
6030                        matchingFilters, intent, resolvedType, flags, userId,
6031                        hasNonNegativePriorityResult);
6032                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6033                    boolean isVisibleToUser = filterIfNotSystemUser(
6034                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6035                    if (isVisibleToUser) {
6036                        result.add(xpResolveInfo);
6037                        sortResult = true;
6038                    }
6039                }
6040                if (hasWebURI(intent)) {
6041                    CrossProfileDomainInfo xpDomainInfo = null;
6042                    final UserInfo parent = getProfileParent(userId);
6043                    if (parent != null) {
6044                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6045                                flags, userId, parent.id);
6046                    }
6047                    if (xpDomainInfo != null) {
6048                        if (xpResolveInfo != null) {
6049                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6050                            // in the result.
6051                            result.remove(xpResolveInfo);
6052                        }
6053                        if (result.size() == 0 && !addEphemeral) {
6054                            // No result in current profile, but found candidate in parent user.
6055                            // And we are not going to add emphemeral app, so we can return the
6056                            // result straight away.
6057                            result.add(xpDomainInfo.resolveInfo);
6058                            return filterForEphemeral(result, ephemeralPkgName);
6059                        }
6060                    } else if (result.size() <= 1 && !addEphemeral) {
6061                        // No result in parent user and <= 1 result in current profile, and we
6062                        // are not going to add emphemeral app, so we can return the result without
6063                        // further processing.
6064                        return filterForEphemeral(result, ephemeralPkgName);
6065                    }
6066                    // We have more than one candidate (combining results from current and parent
6067                    // profile), so we need filtering and sorting.
6068                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6069                            intent, flags, result, xpDomainInfo, userId);
6070                    sortResult = true;
6071                }
6072            } else {
6073                final PackageParser.Package pkg = mPackages.get(pkgName);
6074                if (pkg != null) {
6075                    result = filterForEphemeral(filterIfNotSystemUser(
6076                            mActivities.queryIntentForPackage(
6077                                    intent, resolvedType, flags, pkg.activities, userId),
6078                            userId), ephemeralPkgName);
6079                } else {
6080                    // the caller wants to resolve for a particular package; however, there
6081                    // were no installed results, so, try to find an ephemeral result
6082                    addEphemeral = isEphemeralAllowed(
6083                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6084                    result = new ArrayList<ResolveInfo>();
6085                }
6086            }
6087        }
6088        if (addEphemeral) {
6089            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6090            final EphemeralRequest requestObject = new EphemeralRequest(
6091                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6092                    null /*launchIntent*/, null /*callingPackage*/, userId);
6093            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6094                    mContext, mEphemeralResolverConnection, requestObject);
6095            if (intentInfo != null) {
6096                if (DEBUG_EPHEMERAL) {
6097                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6098                }
6099                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6100                ephemeralInstaller.ephemeralResponse = intentInfo;
6101                // make sure this resolver is the default
6102                ephemeralInstaller.isDefault = true;
6103                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6104                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6105                // add a non-generic filter
6106                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6107                ephemeralInstaller.filter.addDataPath(
6108                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6109                result.add(ephemeralInstaller);
6110            }
6111            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6112        }
6113        if (sortResult) {
6114            Collections.sort(result, mResolvePrioritySorter);
6115        }
6116        return filterForEphemeral(result, ephemeralPkgName);
6117    }
6118
6119    private static class CrossProfileDomainInfo {
6120        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6121        ResolveInfo resolveInfo;
6122        /* Best domain verification status of the activities found in the other profile */
6123        int bestDomainVerificationStatus;
6124    }
6125
6126    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6127            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6128        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6129                sourceUserId)) {
6130            return null;
6131        }
6132        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6133                resolvedType, flags, parentUserId);
6134
6135        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6136            return null;
6137        }
6138        CrossProfileDomainInfo result = null;
6139        int size = resultTargetUser.size();
6140        for (int i = 0; i < size; i++) {
6141            ResolveInfo riTargetUser = resultTargetUser.get(i);
6142            // Intent filter verification is only for filters that specify a host. So don't return
6143            // those that handle all web uris.
6144            if (riTargetUser.handleAllWebDataURI) {
6145                continue;
6146            }
6147            String packageName = riTargetUser.activityInfo.packageName;
6148            PackageSetting ps = mSettings.mPackages.get(packageName);
6149            if (ps == null) {
6150                continue;
6151            }
6152            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6153            int status = (int)(verificationState >> 32);
6154            if (result == null) {
6155                result = new CrossProfileDomainInfo();
6156                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6157                        sourceUserId, parentUserId);
6158                result.bestDomainVerificationStatus = status;
6159            } else {
6160                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6161                        result.bestDomainVerificationStatus);
6162            }
6163        }
6164        // Don't consider matches with status NEVER across profiles.
6165        if (result != null && result.bestDomainVerificationStatus
6166                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6167            return null;
6168        }
6169        return result;
6170    }
6171
6172    /**
6173     * Verification statuses are ordered from the worse to the best, except for
6174     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6175     */
6176    private int bestDomainVerificationStatus(int status1, int status2) {
6177        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6178            return status2;
6179        }
6180        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6181            return status1;
6182        }
6183        return (int) MathUtils.max(status1, status2);
6184    }
6185
6186    private boolean isUserEnabled(int userId) {
6187        long callingId = Binder.clearCallingIdentity();
6188        try {
6189            UserInfo userInfo = sUserManager.getUserInfo(userId);
6190            return userInfo != null && userInfo.isEnabled();
6191        } finally {
6192            Binder.restoreCallingIdentity(callingId);
6193        }
6194    }
6195
6196    /**
6197     * Filter out activities with systemUserOnly flag set, when current user is not System.
6198     *
6199     * @return filtered list
6200     */
6201    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6202        if (userId == UserHandle.USER_SYSTEM) {
6203            return resolveInfos;
6204        }
6205        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6206            ResolveInfo info = resolveInfos.get(i);
6207            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6208                resolveInfos.remove(i);
6209            }
6210        }
6211        return resolveInfos;
6212    }
6213
6214    /**
6215     * Filters out ephemeral activities.
6216     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6217     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6218     *
6219     * @param resolveInfos The pre-filtered list of resolved activities
6220     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6221     *          is performed.
6222     * @return A filtered list of resolved activities.
6223     */
6224    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6225            String ephemeralPkgName) {
6226        if (ephemeralPkgName == null) {
6227            return resolveInfos;
6228        }
6229        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6230            ResolveInfo info = resolveInfos.get(i);
6231            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6232            // allow activities that are defined in the provided package
6233            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6234                continue;
6235            }
6236            // allow activities that have been explicitly exposed to ephemeral apps
6237            if (!isEphemeralApp
6238                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6239                continue;
6240            }
6241            resolveInfos.remove(i);
6242        }
6243        return resolveInfos;
6244    }
6245
6246    /**
6247     * @param resolveInfos list of resolve infos in descending priority order
6248     * @return if the list contains a resolve info with non-negative priority
6249     */
6250    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6251        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6252    }
6253
6254    private static boolean hasWebURI(Intent intent) {
6255        if (intent.getData() == null) {
6256            return false;
6257        }
6258        final String scheme = intent.getScheme();
6259        if (TextUtils.isEmpty(scheme)) {
6260            return false;
6261        }
6262        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6263    }
6264
6265    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6266            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6267            int userId) {
6268        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6269
6270        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6271            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6272                    candidates.size());
6273        }
6274
6275        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6276        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6277        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6278        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6279        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6280        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6281
6282        synchronized (mPackages) {
6283            final int count = candidates.size();
6284            // First, try to use linked apps. Partition the candidates into four lists:
6285            // one for the final results, one for the "do not use ever", one for "undefined status"
6286            // and finally one for "browser app type".
6287            for (int n=0; n<count; n++) {
6288                ResolveInfo info = candidates.get(n);
6289                String packageName = info.activityInfo.packageName;
6290                PackageSetting ps = mSettings.mPackages.get(packageName);
6291                if (ps != null) {
6292                    // Add to the special match all list (Browser use case)
6293                    if (info.handleAllWebDataURI) {
6294                        matchAllList.add(info);
6295                        continue;
6296                    }
6297                    // Try to get the status from User settings first
6298                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6299                    int status = (int)(packedStatus >> 32);
6300                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6301                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6302                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6303                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6304                                    + " : linkgen=" + linkGeneration);
6305                        }
6306                        // Use link-enabled generation as preferredOrder, i.e.
6307                        // prefer newly-enabled over earlier-enabled.
6308                        info.preferredOrder = linkGeneration;
6309                        alwaysList.add(info);
6310                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6311                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6312                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6313                        }
6314                        neverList.add(info);
6315                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6316                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6317                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6318                        }
6319                        alwaysAskList.add(info);
6320                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6321                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6322                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6323                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6324                        }
6325                        undefinedList.add(info);
6326                    }
6327                }
6328            }
6329
6330            // We'll want to include browser possibilities in a few cases
6331            boolean includeBrowser = false;
6332
6333            // First try to add the "always" resolution(s) for the current user, if any
6334            if (alwaysList.size() > 0) {
6335                result.addAll(alwaysList);
6336            } else {
6337                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6338                result.addAll(undefinedList);
6339                // Maybe add one for the other profile.
6340                if (xpDomainInfo != null && (
6341                        xpDomainInfo.bestDomainVerificationStatus
6342                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6343                    result.add(xpDomainInfo.resolveInfo);
6344                }
6345                includeBrowser = true;
6346            }
6347
6348            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6349            // If there were 'always' entries their preferred order has been set, so we also
6350            // back that off to make the alternatives equivalent
6351            if (alwaysAskList.size() > 0) {
6352                for (ResolveInfo i : result) {
6353                    i.preferredOrder = 0;
6354                }
6355                result.addAll(alwaysAskList);
6356                includeBrowser = true;
6357            }
6358
6359            if (includeBrowser) {
6360                // Also add browsers (all of them or only the default one)
6361                if (DEBUG_DOMAIN_VERIFICATION) {
6362                    Slog.v(TAG, "   ...including browsers in candidate set");
6363                }
6364                if ((matchFlags & MATCH_ALL) != 0) {
6365                    result.addAll(matchAllList);
6366                } else {
6367                    // Browser/generic handling case.  If there's a default browser, go straight
6368                    // to that (but only if there is no other higher-priority match).
6369                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6370                    int maxMatchPrio = 0;
6371                    ResolveInfo defaultBrowserMatch = null;
6372                    final int numCandidates = matchAllList.size();
6373                    for (int n = 0; n < numCandidates; n++) {
6374                        ResolveInfo info = matchAllList.get(n);
6375                        // track the highest overall match priority...
6376                        if (info.priority > maxMatchPrio) {
6377                            maxMatchPrio = info.priority;
6378                        }
6379                        // ...and the highest-priority default browser match
6380                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6381                            if (defaultBrowserMatch == null
6382                                    || (defaultBrowserMatch.priority < info.priority)) {
6383                                if (debug) {
6384                                    Slog.v(TAG, "Considering default browser match " + info);
6385                                }
6386                                defaultBrowserMatch = info;
6387                            }
6388                        }
6389                    }
6390                    if (defaultBrowserMatch != null
6391                            && defaultBrowserMatch.priority >= maxMatchPrio
6392                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6393                    {
6394                        if (debug) {
6395                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6396                        }
6397                        result.add(defaultBrowserMatch);
6398                    } else {
6399                        result.addAll(matchAllList);
6400                    }
6401                }
6402
6403                // If there is nothing selected, add all candidates and remove the ones that the user
6404                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6405                if (result.size() == 0) {
6406                    result.addAll(candidates);
6407                    result.removeAll(neverList);
6408                }
6409            }
6410        }
6411        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6412            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6413                    result.size());
6414            for (ResolveInfo info : result) {
6415                Slog.v(TAG, "  + " + info.activityInfo);
6416            }
6417        }
6418        return result;
6419    }
6420
6421    // Returns a packed value as a long:
6422    //
6423    // high 'int'-sized word: link status: undefined/ask/never/always.
6424    // low 'int'-sized word: relative priority among 'always' results.
6425    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6426        long result = ps.getDomainVerificationStatusForUser(userId);
6427        // if none available, get the master status
6428        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6429            if (ps.getIntentFilterVerificationInfo() != null) {
6430                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6431            }
6432        }
6433        return result;
6434    }
6435
6436    private ResolveInfo querySkipCurrentProfileIntents(
6437            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6438            int flags, int sourceUserId) {
6439        if (matchingFilters != null) {
6440            int size = matchingFilters.size();
6441            for (int i = 0; i < size; i ++) {
6442                CrossProfileIntentFilter filter = matchingFilters.get(i);
6443                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6444                    // Checking if there are activities in the target user that can handle the
6445                    // intent.
6446                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6447                            resolvedType, flags, sourceUserId);
6448                    if (resolveInfo != null) {
6449                        return resolveInfo;
6450                    }
6451                }
6452            }
6453        }
6454        return null;
6455    }
6456
6457    // Return matching ResolveInfo in target user if any.
6458    private ResolveInfo queryCrossProfileIntents(
6459            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6460            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6461        if (matchingFilters != null) {
6462            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6463            // match the same intent. For performance reasons, it is better not to
6464            // run queryIntent twice for the same userId
6465            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6466            int size = matchingFilters.size();
6467            for (int i = 0; i < size; i++) {
6468                CrossProfileIntentFilter filter = matchingFilters.get(i);
6469                int targetUserId = filter.getTargetUserId();
6470                boolean skipCurrentProfile =
6471                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6472                boolean skipCurrentProfileIfNoMatchFound =
6473                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6474                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6475                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6476                    // Checking if there are activities in the target user that can handle the
6477                    // intent.
6478                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6479                            resolvedType, flags, sourceUserId);
6480                    if (resolveInfo != null) return resolveInfo;
6481                    alreadyTriedUserIds.put(targetUserId, true);
6482                }
6483            }
6484        }
6485        return null;
6486    }
6487
6488    /**
6489     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6490     * will forward the intent to the filter's target user.
6491     * Otherwise, returns null.
6492     */
6493    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6494            String resolvedType, int flags, int sourceUserId) {
6495        int targetUserId = filter.getTargetUserId();
6496        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6497                resolvedType, flags, targetUserId);
6498        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6499            // If all the matches in the target profile are suspended, return null.
6500            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6501                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6502                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6503                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6504                            targetUserId);
6505                }
6506            }
6507        }
6508        return null;
6509    }
6510
6511    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6512            int sourceUserId, int targetUserId) {
6513        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6514        long ident = Binder.clearCallingIdentity();
6515        boolean targetIsProfile;
6516        try {
6517            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6518        } finally {
6519            Binder.restoreCallingIdentity(ident);
6520        }
6521        String className;
6522        if (targetIsProfile) {
6523            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6524        } else {
6525            className = FORWARD_INTENT_TO_PARENT;
6526        }
6527        ComponentName forwardingActivityComponentName = new ComponentName(
6528                mAndroidApplication.packageName, className);
6529        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6530                sourceUserId);
6531        if (!targetIsProfile) {
6532            forwardingActivityInfo.showUserIcon = targetUserId;
6533            forwardingResolveInfo.noResourceId = true;
6534        }
6535        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6536        forwardingResolveInfo.priority = 0;
6537        forwardingResolveInfo.preferredOrder = 0;
6538        forwardingResolveInfo.match = 0;
6539        forwardingResolveInfo.isDefault = true;
6540        forwardingResolveInfo.filter = filter;
6541        forwardingResolveInfo.targetUserId = targetUserId;
6542        return forwardingResolveInfo;
6543    }
6544
6545    @Override
6546    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6547            Intent[] specifics, String[] specificTypes, Intent intent,
6548            String resolvedType, int flags, int userId) {
6549        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6550                specificTypes, intent, resolvedType, flags, userId));
6551    }
6552
6553    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6554            Intent[] specifics, String[] specificTypes, Intent intent,
6555            String resolvedType, int flags, int userId) {
6556        if (!sUserManager.exists(userId)) return Collections.emptyList();
6557        flags = updateFlagsForResolve(flags, userId, intent);
6558        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6559                false /* requireFullPermission */, false /* checkShell */,
6560                "query intent activity options");
6561        final String resultsAction = intent.getAction();
6562
6563        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6564                | PackageManager.GET_RESOLVED_FILTER, userId);
6565
6566        if (DEBUG_INTENT_MATCHING) {
6567            Log.v(TAG, "Query " + intent + ": " + results);
6568        }
6569
6570        int specificsPos = 0;
6571        int N;
6572
6573        // todo: note that the algorithm used here is O(N^2).  This
6574        // isn't a problem in our current environment, but if we start running
6575        // into situations where we have more than 5 or 10 matches then this
6576        // should probably be changed to something smarter...
6577
6578        // First we go through and resolve each of the specific items
6579        // that were supplied, taking care of removing any corresponding
6580        // duplicate items in the generic resolve list.
6581        if (specifics != null) {
6582            for (int i=0; i<specifics.length; i++) {
6583                final Intent sintent = specifics[i];
6584                if (sintent == null) {
6585                    continue;
6586                }
6587
6588                if (DEBUG_INTENT_MATCHING) {
6589                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6590                }
6591
6592                String action = sintent.getAction();
6593                if (resultsAction != null && resultsAction.equals(action)) {
6594                    // If this action was explicitly requested, then don't
6595                    // remove things that have it.
6596                    action = null;
6597                }
6598
6599                ResolveInfo ri = null;
6600                ActivityInfo ai = null;
6601
6602                ComponentName comp = sintent.getComponent();
6603                if (comp == null) {
6604                    ri = resolveIntent(
6605                        sintent,
6606                        specificTypes != null ? specificTypes[i] : null,
6607                            flags, userId);
6608                    if (ri == null) {
6609                        continue;
6610                    }
6611                    if (ri == mResolveInfo) {
6612                        // ACK!  Must do something better with this.
6613                    }
6614                    ai = ri.activityInfo;
6615                    comp = new ComponentName(ai.applicationInfo.packageName,
6616                            ai.name);
6617                } else {
6618                    ai = getActivityInfo(comp, flags, userId);
6619                    if (ai == null) {
6620                        continue;
6621                    }
6622                }
6623
6624                // Look for any generic query activities that are duplicates
6625                // of this specific one, and remove them from the results.
6626                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6627                N = results.size();
6628                int j;
6629                for (j=specificsPos; j<N; j++) {
6630                    ResolveInfo sri = results.get(j);
6631                    if ((sri.activityInfo.name.equals(comp.getClassName())
6632                            && sri.activityInfo.applicationInfo.packageName.equals(
6633                                    comp.getPackageName()))
6634                        || (action != null && sri.filter.matchAction(action))) {
6635                        results.remove(j);
6636                        if (DEBUG_INTENT_MATCHING) Log.v(
6637                            TAG, "Removing duplicate item from " + j
6638                            + " due to specific " + specificsPos);
6639                        if (ri == null) {
6640                            ri = sri;
6641                        }
6642                        j--;
6643                        N--;
6644                    }
6645                }
6646
6647                // Add this specific item to its proper place.
6648                if (ri == null) {
6649                    ri = new ResolveInfo();
6650                    ri.activityInfo = ai;
6651                }
6652                results.add(specificsPos, ri);
6653                ri.specificIndex = i;
6654                specificsPos++;
6655            }
6656        }
6657
6658        // Now we go through the remaining generic results and remove any
6659        // duplicate actions that are found here.
6660        N = results.size();
6661        for (int i=specificsPos; i<N-1; i++) {
6662            final ResolveInfo rii = results.get(i);
6663            if (rii.filter == null) {
6664                continue;
6665            }
6666
6667            // Iterate over all of the actions of this result's intent
6668            // filter...  typically this should be just one.
6669            final Iterator<String> it = rii.filter.actionsIterator();
6670            if (it == null) {
6671                continue;
6672            }
6673            while (it.hasNext()) {
6674                final String action = it.next();
6675                if (resultsAction != null && resultsAction.equals(action)) {
6676                    // If this action was explicitly requested, then don't
6677                    // remove things that have it.
6678                    continue;
6679                }
6680                for (int j=i+1; j<N; j++) {
6681                    final ResolveInfo rij = results.get(j);
6682                    if (rij.filter != null && rij.filter.hasAction(action)) {
6683                        results.remove(j);
6684                        if (DEBUG_INTENT_MATCHING) Log.v(
6685                            TAG, "Removing duplicate item from " + j
6686                            + " due to action " + action + " at " + i);
6687                        j--;
6688                        N--;
6689                    }
6690                }
6691            }
6692
6693            // If the caller didn't request filter information, drop it now
6694            // so we don't have to marshall/unmarshall it.
6695            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6696                rii.filter = null;
6697            }
6698        }
6699
6700        // Filter out the caller activity if so requested.
6701        if (caller != null) {
6702            N = results.size();
6703            for (int i=0; i<N; i++) {
6704                ActivityInfo ainfo = results.get(i).activityInfo;
6705                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6706                        && caller.getClassName().equals(ainfo.name)) {
6707                    results.remove(i);
6708                    break;
6709                }
6710            }
6711        }
6712
6713        // If the caller didn't request filter information,
6714        // drop them now so we don't have to
6715        // marshall/unmarshall it.
6716        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6717            N = results.size();
6718            for (int i=0; i<N; i++) {
6719                results.get(i).filter = null;
6720            }
6721        }
6722
6723        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6724        return results;
6725    }
6726
6727    @Override
6728    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6729            String resolvedType, int flags, int userId) {
6730        return new ParceledListSlice<>(
6731                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6732    }
6733
6734    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6735            String resolvedType, int flags, int userId) {
6736        if (!sUserManager.exists(userId)) return Collections.emptyList();
6737        flags = updateFlagsForResolve(flags, userId, intent);
6738        ComponentName comp = intent.getComponent();
6739        if (comp == null) {
6740            if (intent.getSelector() != null) {
6741                intent = intent.getSelector();
6742                comp = intent.getComponent();
6743            }
6744        }
6745        if (comp != null) {
6746            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6747            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6748            if (ai != null) {
6749                ResolveInfo ri = new ResolveInfo();
6750                ri.activityInfo = ai;
6751                list.add(ri);
6752            }
6753            return list;
6754        }
6755
6756        // reader
6757        synchronized (mPackages) {
6758            String pkgName = intent.getPackage();
6759            if (pkgName == null) {
6760                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6761            }
6762            final PackageParser.Package pkg = mPackages.get(pkgName);
6763            if (pkg != null) {
6764                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6765                        userId);
6766            }
6767            return Collections.emptyList();
6768        }
6769    }
6770
6771    @Override
6772    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6773        if (!sUserManager.exists(userId)) return null;
6774        flags = updateFlagsForResolve(flags, userId, intent);
6775        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6776        if (query != null) {
6777            if (query.size() >= 1) {
6778                // If there is more than one service with the same priority,
6779                // just arbitrarily pick the first one.
6780                return query.get(0);
6781            }
6782        }
6783        return null;
6784    }
6785
6786    @Override
6787    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6788            String resolvedType, int flags, int userId) {
6789        return new ParceledListSlice<>(
6790                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6791    }
6792
6793    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6794            String resolvedType, int flags, int userId) {
6795        if (!sUserManager.exists(userId)) return Collections.emptyList();
6796        flags = updateFlagsForResolve(flags, userId, intent);
6797        ComponentName comp = intent.getComponent();
6798        if (comp == null) {
6799            if (intent.getSelector() != null) {
6800                intent = intent.getSelector();
6801                comp = intent.getComponent();
6802            }
6803        }
6804        if (comp != null) {
6805            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6806            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6807            if (si != null) {
6808                final ResolveInfo ri = new ResolveInfo();
6809                ri.serviceInfo = si;
6810                list.add(ri);
6811            }
6812            return list;
6813        }
6814
6815        // reader
6816        synchronized (mPackages) {
6817            String pkgName = intent.getPackage();
6818            if (pkgName == null) {
6819                return mServices.queryIntent(intent, resolvedType, flags, userId);
6820            }
6821            final PackageParser.Package pkg = mPackages.get(pkgName);
6822            if (pkg != null) {
6823                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6824                        userId);
6825            }
6826            return Collections.emptyList();
6827        }
6828    }
6829
6830    @Override
6831    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6832            String resolvedType, int flags, int userId) {
6833        return new ParceledListSlice<>(
6834                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6835    }
6836
6837    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6838            Intent intent, String resolvedType, int flags, int userId) {
6839        if (!sUserManager.exists(userId)) return Collections.emptyList();
6840        flags = updateFlagsForResolve(flags, userId, intent);
6841        ComponentName comp = intent.getComponent();
6842        if (comp == null) {
6843            if (intent.getSelector() != null) {
6844                intent = intent.getSelector();
6845                comp = intent.getComponent();
6846            }
6847        }
6848        if (comp != null) {
6849            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6850            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6851            if (pi != null) {
6852                final ResolveInfo ri = new ResolveInfo();
6853                ri.providerInfo = pi;
6854                list.add(ri);
6855            }
6856            return list;
6857        }
6858
6859        // reader
6860        synchronized (mPackages) {
6861            String pkgName = intent.getPackage();
6862            if (pkgName == null) {
6863                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6864            }
6865            final PackageParser.Package pkg = mPackages.get(pkgName);
6866            if (pkg != null) {
6867                return mProviders.queryIntentForPackage(
6868                        intent, resolvedType, flags, pkg.providers, userId);
6869            }
6870            return Collections.emptyList();
6871        }
6872    }
6873
6874    @Override
6875    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6876        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6877        flags = updateFlagsForPackage(flags, userId, null);
6878        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6879        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6880                true /* requireFullPermission */, false /* checkShell */,
6881                "get installed packages");
6882
6883        // writer
6884        synchronized (mPackages) {
6885            ArrayList<PackageInfo> list;
6886            if (listUninstalled) {
6887                list = new ArrayList<>(mSettings.mPackages.size());
6888                for (PackageSetting ps : mSettings.mPackages.values()) {
6889                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6890                        continue;
6891                    }
6892                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6893                    if (pi != null) {
6894                        list.add(pi);
6895                    }
6896                }
6897            } else {
6898                list = new ArrayList<>(mPackages.size());
6899                for (PackageParser.Package p : mPackages.values()) {
6900                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6901                            Binder.getCallingUid(), userId)) {
6902                        continue;
6903                    }
6904                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6905                            p.mExtras, flags, userId);
6906                    if (pi != null) {
6907                        list.add(pi);
6908                    }
6909                }
6910            }
6911
6912            return new ParceledListSlice<>(list);
6913        }
6914    }
6915
6916    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6917            String[] permissions, boolean[] tmp, int flags, int userId) {
6918        int numMatch = 0;
6919        final PermissionsState permissionsState = ps.getPermissionsState();
6920        for (int i=0; i<permissions.length; i++) {
6921            final String permission = permissions[i];
6922            if (permissionsState.hasPermission(permission, userId)) {
6923                tmp[i] = true;
6924                numMatch++;
6925            } else {
6926                tmp[i] = false;
6927            }
6928        }
6929        if (numMatch == 0) {
6930            return;
6931        }
6932        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6933
6934        // The above might return null in cases of uninstalled apps or install-state
6935        // skew across users/profiles.
6936        if (pi != null) {
6937            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6938                if (numMatch == permissions.length) {
6939                    pi.requestedPermissions = permissions;
6940                } else {
6941                    pi.requestedPermissions = new String[numMatch];
6942                    numMatch = 0;
6943                    for (int i=0; i<permissions.length; i++) {
6944                        if (tmp[i]) {
6945                            pi.requestedPermissions[numMatch] = permissions[i];
6946                            numMatch++;
6947                        }
6948                    }
6949                }
6950            }
6951            list.add(pi);
6952        }
6953    }
6954
6955    @Override
6956    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6957            String[] permissions, int flags, int userId) {
6958        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6959        flags = updateFlagsForPackage(flags, userId, permissions);
6960        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6961                true /* requireFullPermission */, false /* checkShell */,
6962                "get packages holding permissions");
6963        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6964
6965        // writer
6966        synchronized (mPackages) {
6967            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6968            boolean[] tmpBools = new boolean[permissions.length];
6969            if (listUninstalled) {
6970                for (PackageSetting ps : mSettings.mPackages.values()) {
6971                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6972                            userId);
6973                }
6974            } else {
6975                for (PackageParser.Package pkg : mPackages.values()) {
6976                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6977                    if (ps != null) {
6978                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6979                                userId);
6980                    }
6981                }
6982            }
6983
6984            return new ParceledListSlice<PackageInfo>(list);
6985        }
6986    }
6987
6988    @Override
6989    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6990        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6991        flags = updateFlagsForApplication(flags, userId, null);
6992        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6993
6994        // writer
6995        synchronized (mPackages) {
6996            ArrayList<ApplicationInfo> list;
6997            if (listUninstalled) {
6998                list = new ArrayList<>(mSettings.mPackages.size());
6999                for (PackageSetting ps : mSettings.mPackages.values()) {
7000                    ApplicationInfo ai;
7001                    int effectiveFlags = flags;
7002                    if (ps.isSystem()) {
7003                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7004                    }
7005                    if (ps.pkg != null) {
7006                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7007                            continue;
7008                        }
7009                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7010                                ps.readUserState(userId), userId);
7011                        if (ai != null) {
7012                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7013                        }
7014                    } else {
7015                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7016                        // and already converts to externally visible package name
7017                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7018                                Binder.getCallingUid(), effectiveFlags, userId);
7019                    }
7020                    if (ai != null) {
7021                        list.add(ai);
7022                    }
7023                }
7024            } else {
7025                list = new ArrayList<>(mPackages.size());
7026                for (PackageParser.Package p : mPackages.values()) {
7027                    if (p.mExtras != null) {
7028                        PackageSetting ps = (PackageSetting) p.mExtras;
7029                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7030                            continue;
7031                        }
7032                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7033                                ps.readUserState(userId), userId);
7034                        if (ai != null) {
7035                            ai.packageName = resolveExternalPackageNameLPr(p);
7036                            list.add(ai);
7037                        }
7038                    }
7039                }
7040            }
7041
7042            return new ParceledListSlice<>(list);
7043        }
7044    }
7045
7046    @Override
7047    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7048        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7049            return null;
7050        }
7051
7052        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7053                "getEphemeralApplications");
7054        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7055                true /* requireFullPermission */, false /* checkShell */,
7056                "getEphemeralApplications");
7057        synchronized (mPackages) {
7058            List<InstantAppInfo> instantApps = mInstantAppRegistry
7059                    .getInstantAppsLPr(userId);
7060            if (instantApps != null) {
7061                return new ParceledListSlice<>(instantApps);
7062            }
7063        }
7064        return null;
7065    }
7066
7067    @Override
7068    public boolean isInstantApp(String packageName, int userId) {
7069        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7070                true /* requireFullPermission */, false /* checkShell */,
7071                "isInstantApp");
7072        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7073            return false;
7074        }
7075
7076        if (!isCallerSameApp(packageName)) {
7077            return false;
7078        }
7079        synchronized (mPackages) {
7080            PackageParser.Package pkg = mPackages.get(packageName);
7081            if (pkg != null) {
7082                return pkg.applicationInfo.isInstantApp();
7083            }
7084        }
7085        return false;
7086    }
7087
7088    @Override
7089    public byte[] getInstantAppCookie(String packageName, int userId) {
7090        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7091            return null;
7092        }
7093
7094        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7095                true /* requireFullPermission */, false /* checkShell */,
7096                "getInstantAppCookie");
7097        if (!isCallerSameApp(packageName)) {
7098            return null;
7099        }
7100        synchronized (mPackages) {
7101            return mInstantAppRegistry.getInstantAppCookieLPw(
7102                    packageName, userId);
7103        }
7104    }
7105
7106    @Override
7107    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7108        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7109            return true;
7110        }
7111
7112        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7113                true /* requireFullPermission */, true /* checkShell */,
7114                "setInstantAppCookie");
7115        if (!isCallerSameApp(packageName)) {
7116            return false;
7117        }
7118        synchronized (mPackages) {
7119            return mInstantAppRegistry.setInstantAppCookieLPw(
7120                    packageName, cookie, userId);
7121        }
7122    }
7123
7124    @Override
7125    public Bitmap getInstantAppIcon(String packageName, int userId) {
7126        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7127            return null;
7128        }
7129
7130        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7131                "getInstantAppIcon");
7132
7133        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7134                true /* requireFullPermission */, false /* checkShell */,
7135                "getInstantAppIcon");
7136
7137        synchronized (mPackages) {
7138            return mInstantAppRegistry.getInstantAppIconLPw(
7139                    packageName, userId);
7140        }
7141    }
7142
7143    private boolean isCallerSameApp(String packageName) {
7144        PackageParser.Package pkg = mPackages.get(packageName);
7145        return pkg != null
7146                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7147    }
7148
7149    @Override
7150    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7151        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7152    }
7153
7154    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7155        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7156
7157        // reader
7158        synchronized (mPackages) {
7159            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7160            final int userId = UserHandle.getCallingUserId();
7161            while (i.hasNext()) {
7162                final PackageParser.Package p = i.next();
7163                if (p.applicationInfo == null) continue;
7164
7165                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7166                        && !p.applicationInfo.isDirectBootAware();
7167                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7168                        && p.applicationInfo.isDirectBootAware();
7169
7170                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7171                        && (!mSafeMode || isSystemApp(p))
7172                        && (matchesUnaware || matchesAware)) {
7173                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7174                    if (ps != null) {
7175                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7176                                ps.readUserState(userId), userId);
7177                        if (ai != null) {
7178                            finalList.add(ai);
7179                        }
7180                    }
7181                }
7182            }
7183        }
7184
7185        return finalList;
7186    }
7187
7188    @Override
7189    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7190        if (!sUserManager.exists(userId)) return null;
7191        flags = updateFlagsForComponent(flags, userId, name);
7192        // reader
7193        synchronized (mPackages) {
7194            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7195            PackageSetting ps = provider != null
7196                    ? mSettings.mPackages.get(provider.owner.packageName)
7197                    : null;
7198            return ps != null
7199                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7200                    ? PackageParser.generateProviderInfo(provider, flags,
7201                            ps.readUserState(userId), userId)
7202                    : null;
7203        }
7204    }
7205
7206    /**
7207     * @deprecated
7208     */
7209    @Deprecated
7210    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7211        // reader
7212        synchronized (mPackages) {
7213            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7214                    .entrySet().iterator();
7215            final int userId = UserHandle.getCallingUserId();
7216            while (i.hasNext()) {
7217                Map.Entry<String, PackageParser.Provider> entry = i.next();
7218                PackageParser.Provider p = entry.getValue();
7219                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7220
7221                if (ps != null && p.syncable
7222                        && (!mSafeMode || (p.info.applicationInfo.flags
7223                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7224                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7225                            ps.readUserState(userId), userId);
7226                    if (info != null) {
7227                        outNames.add(entry.getKey());
7228                        outInfo.add(info);
7229                    }
7230                }
7231            }
7232        }
7233    }
7234
7235    @Override
7236    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7237            int uid, int flags) {
7238        final int userId = processName != null ? UserHandle.getUserId(uid)
7239                : UserHandle.getCallingUserId();
7240        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7241        flags = updateFlagsForComponent(flags, userId, processName);
7242
7243        ArrayList<ProviderInfo> finalList = null;
7244        // reader
7245        synchronized (mPackages) {
7246            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7247            while (i.hasNext()) {
7248                final PackageParser.Provider p = i.next();
7249                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7250                if (ps != null && p.info.authority != null
7251                        && (processName == null
7252                                || (p.info.processName.equals(processName)
7253                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7254                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7255                    if (finalList == null) {
7256                        finalList = new ArrayList<ProviderInfo>(3);
7257                    }
7258                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7259                            ps.readUserState(userId), userId);
7260                    if (info != null) {
7261                        finalList.add(info);
7262                    }
7263                }
7264            }
7265        }
7266
7267        if (finalList != null) {
7268            Collections.sort(finalList, mProviderInitOrderSorter);
7269            return new ParceledListSlice<ProviderInfo>(finalList);
7270        }
7271
7272        return ParceledListSlice.emptyList();
7273    }
7274
7275    @Override
7276    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7277        // reader
7278        synchronized (mPackages) {
7279            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7280            return PackageParser.generateInstrumentationInfo(i, flags);
7281        }
7282    }
7283
7284    @Override
7285    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7286            String targetPackage, int flags) {
7287        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7288    }
7289
7290    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7291            int flags) {
7292        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7293
7294        // reader
7295        synchronized (mPackages) {
7296            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7297            while (i.hasNext()) {
7298                final PackageParser.Instrumentation p = i.next();
7299                if (targetPackage == null
7300                        || targetPackage.equals(p.info.targetPackage)) {
7301                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7302                            flags);
7303                    if (ii != null) {
7304                        finalList.add(ii);
7305                    }
7306                }
7307            }
7308        }
7309
7310        return finalList;
7311    }
7312
7313    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7314        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7315        if (overlays == null) {
7316            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7317            return;
7318        }
7319        for (PackageParser.Package opkg : overlays.values()) {
7320            // Not much to do if idmap fails: we already logged the error
7321            // and we certainly don't want to abort installation of pkg simply
7322            // because an overlay didn't fit properly. For these reasons,
7323            // ignore the return value of createIdmapForPackagePairLI.
7324            createIdmapForPackagePairLI(pkg, opkg);
7325        }
7326    }
7327
7328    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7329            PackageParser.Package opkg) {
7330        if (!opkg.mTrustedOverlay) {
7331            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7332                    opkg.baseCodePath + ": overlay not trusted");
7333            return false;
7334        }
7335        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7336        if (overlaySet == null) {
7337            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7338                    opkg.baseCodePath + " but target package has no known overlays");
7339            return false;
7340        }
7341        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7342        // TODO: generate idmap for split APKs
7343        try {
7344            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7345        } catch (InstallerException e) {
7346            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7347                    + opkg.baseCodePath);
7348            return false;
7349        }
7350        PackageParser.Package[] overlayArray =
7351            overlaySet.values().toArray(new PackageParser.Package[0]);
7352        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7353            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7354                return p1.mOverlayPriority - p2.mOverlayPriority;
7355            }
7356        };
7357        Arrays.sort(overlayArray, cmp);
7358
7359        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7360        int i = 0;
7361        for (PackageParser.Package p : overlayArray) {
7362            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7363        }
7364        return true;
7365    }
7366
7367    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7368        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7369        try {
7370            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7371        } finally {
7372            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7373        }
7374    }
7375
7376    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7377        final File[] files = dir.listFiles();
7378        if (ArrayUtils.isEmpty(files)) {
7379            Log.d(TAG, "No files in app dir " + dir);
7380            return;
7381        }
7382
7383        if (DEBUG_PACKAGE_SCANNING) {
7384            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7385                    + " flags=0x" + Integer.toHexString(parseFlags));
7386        }
7387        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7388                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7389
7390        // Submit files for parsing in parallel
7391        int fileCount = 0;
7392        for (File file : files) {
7393            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7394                    && !PackageInstallerService.isStageName(file.getName());
7395            if (!isPackage) {
7396                // Ignore entries which are not packages
7397                continue;
7398            }
7399            parallelPackageParser.submit(file, parseFlags);
7400            fileCount++;
7401        }
7402
7403        // Process results one by one
7404        for (; fileCount > 0; fileCount--) {
7405            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7406            Throwable throwable = parseResult.throwable;
7407            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7408
7409            if (throwable == null) {
7410                // Static shared libraries have synthetic package names
7411                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7412                    renameStaticSharedLibraryPackage(parseResult.pkg);
7413                }
7414                try {
7415                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7416                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7417                                currentTime, null);
7418                    }
7419                } catch (PackageManagerException e) {
7420                    errorCode = e.error;
7421                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7422                }
7423            } else if (throwable instanceof PackageParser.PackageParserException) {
7424                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7425                        throwable;
7426                errorCode = e.error;
7427                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7428            } else {
7429                throw new IllegalStateException("Unexpected exception occurred while parsing "
7430                        + parseResult.scanFile, throwable);
7431            }
7432
7433            // Delete invalid userdata apps
7434            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7435                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7436                logCriticalInfo(Log.WARN,
7437                        "Deleting invalid package at " + parseResult.scanFile);
7438                removeCodePathLI(parseResult.scanFile);
7439            }
7440        }
7441        parallelPackageParser.close();
7442    }
7443
7444    private static File getSettingsProblemFile() {
7445        File dataDir = Environment.getDataDirectory();
7446        File systemDir = new File(dataDir, "system");
7447        File fname = new File(systemDir, "uiderrors.txt");
7448        return fname;
7449    }
7450
7451    static void reportSettingsProblem(int priority, String msg) {
7452        logCriticalInfo(priority, msg);
7453    }
7454
7455    static void logCriticalInfo(int priority, String msg) {
7456        Slog.println(priority, TAG, msg);
7457        EventLogTags.writePmCriticalInfo(msg);
7458        try {
7459            File fname = getSettingsProblemFile();
7460            FileOutputStream out = new FileOutputStream(fname, true);
7461            PrintWriter pw = new FastPrintWriter(out);
7462            SimpleDateFormat formatter = new SimpleDateFormat();
7463            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7464            pw.println(dateString + ": " + msg);
7465            pw.close();
7466            FileUtils.setPermissions(
7467                    fname.toString(),
7468                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7469                    -1, -1);
7470        } catch (java.io.IOException e) {
7471        }
7472    }
7473
7474    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7475        if (srcFile.isDirectory()) {
7476            final File baseFile = new File(pkg.baseCodePath);
7477            long maxModifiedTime = baseFile.lastModified();
7478            if (pkg.splitCodePaths != null) {
7479                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7480                    final File splitFile = new File(pkg.splitCodePaths[i]);
7481                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7482                }
7483            }
7484            return maxModifiedTime;
7485        }
7486        return srcFile.lastModified();
7487    }
7488
7489    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7490            final int policyFlags) throws PackageManagerException {
7491        // When upgrading from pre-N MR1, verify the package time stamp using the package
7492        // directory and not the APK file.
7493        final long lastModifiedTime = mIsPreNMR1Upgrade
7494                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7495        if (ps != null
7496                && ps.codePath.equals(srcFile)
7497                && ps.timeStamp == lastModifiedTime
7498                && !isCompatSignatureUpdateNeeded(pkg)
7499                && !isRecoverSignatureUpdateNeeded(pkg)) {
7500            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7501            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7502            ArraySet<PublicKey> signingKs;
7503            synchronized (mPackages) {
7504                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7505            }
7506            if (ps.signatures.mSignatures != null
7507                    && ps.signatures.mSignatures.length != 0
7508                    && signingKs != null) {
7509                // Optimization: reuse the existing cached certificates
7510                // if the package appears to be unchanged.
7511                pkg.mSignatures = ps.signatures.mSignatures;
7512                pkg.mSigningKeys = signingKs;
7513                return;
7514            }
7515
7516            Slog.w(TAG, "PackageSetting for " + ps.name
7517                    + " is missing signatures.  Collecting certs again to recover them.");
7518        } else {
7519            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7520        }
7521
7522        try {
7523            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7524            PackageParser.collectCertificates(pkg, policyFlags);
7525        } catch (PackageParserException e) {
7526            throw PackageManagerException.from(e);
7527        } finally {
7528            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7529        }
7530    }
7531
7532    /**
7533     *  Traces a package scan.
7534     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7535     */
7536    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7537            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7538        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7539        try {
7540            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7541        } finally {
7542            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7543        }
7544    }
7545
7546    /**
7547     *  Scans a package and returns the newly parsed package.
7548     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7549     */
7550    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7551            long currentTime, UserHandle user) throws PackageManagerException {
7552        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7553        PackageParser pp = new PackageParser();
7554        pp.setSeparateProcesses(mSeparateProcesses);
7555        pp.setOnlyCoreApps(mOnlyCore);
7556        pp.setDisplayMetrics(mMetrics);
7557
7558        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7559            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7560        }
7561
7562        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7563        final PackageParser.Package pkg;
7564        try {
7565            pkg = pp.parsePackage(scanFile, parseFlags);
7566        } catch (PackageParserException e) {
7567            throw PackageManagerException.from(e);
7568        } finally {
7569            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7570        }
7571
7572        // Static shared libraries have synthetic package names
7573        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7574            renameStaticSharedLibraryPackage(pkg);
7575        }
7576
7577        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7578    }
7579
7580    /**
7581     *  Scans a package and returns the newly parsed package.
7582     *  @throws PackageManagerException on a parse error.
7583     */
7584    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7585            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7586            throws PackageManagerException {
7587        // If the package has children and this is the first dive in the function
7588        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7589        // packages (parent and children) would be successfully scanned before the
7590        // actual scan since scanning mutates internal state and we want to atomically
7591        // install the package and its children.
7592        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7593            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7594                scanFlags |= SCAN_CHECK_ONLY;
7595            }
7596        } else {
7597            scanFlags &= ~SCAN_CHECK_ONLY;
7598        }
7599
7600        // Scan the parent
7601        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7602                scanFlags, currentTime, user);
7603
7604        // Scan the children
7605        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7606        for (int i = 0; i < childCount; i++) {
7607            PackageParser.Package childPackage = pkg.childPackages.get(i);
7608            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7609                    currentTime, user);
7610        }
7611
7612
7613        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7614            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7615        }
7616
7617        return scannedPkg;
7618    }
7619
7620    /**
7621     *  Scans a package and returns the newly parsed package.
7622     *  @throws PackageManagerException on a parse error.
7623     */
7624    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7625            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7626            throws PackageManagerException {
7627        PackageSetting ps = null;
7628        PackageSetting updatedPkg;
7629        // reader
7630        synchronized (mPackages) {
7631            // Look to see if we already know about this package.
7632            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7633            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7634                // This package has been renamed to its original name.  Let's
7635                // use that.
7636                ps = mSettings.getPackageLPr(oldName);
7637            }
7638            // If there was no original package, see one for the real package name.
7639            if (ps == null) {
7640                ps = mSettings.getPackageLPr(pkg.packageName);
7641            }
7642            // Check to see if this package could be hiding/updating a system
7643            // package.  Must look for it either under the original or real
7644            // package name depending on our state.
7645            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7646            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7647
7648            // If this is a package we don't know about on the system partition, we
7649            // may need to remove disabled child packages on the system partition
7650            // or may need to not add child packages if the parent apk is updated
7651            // on the data partition and no longer defines this child package.
7652            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7653                // If this is a parent package for an updated system app and this system
7654                // app got an OTA update which no longer defines some of the child packages
7655                // we have to prune them from the disabled system packages.
7656                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7657                if (disabledPs != null) {
7658                    final int scannedChildCount = (pkg.childPackages != null)
7659                            ? pkg.childPackages.size() : 0;
7660                    final int disabledChildCount = disabledPs.childPackageNames != null
7661                            ? disabledPs.childPackageNames.size() : 0;
7662                    for (int i = 0; i < disabledChildCount; i++) {
7663                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7664                        boolean disabledPackageAvailable = false;
7665                        for (int j = 0; j < scannedChildCount; j++) {
7666                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7667                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7668                                disabledPackageAvailable = true;
7669                                break;
7670                            }
7671                         }
7672                         if (!disabledPackageAvailable) {
7673                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7674                         }
7675                    }
7676                }
7677            }
7678        }
7679
7680        boolean updatedPkgBetter = false;
7681        // First check if this is a system package that may involve an update
7682        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7683            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7684            // it needs to drop FLAG_PRIVILEGED.
7685            if (locationIsPrivileged(scanFile)) {
7686                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7687            } else {
7688                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7689            }
7690
7691            if (ps != null && !ps.codePath.equals(scanFile)) {
7692                // The path has changed from what was last scanned...  check the
7693                // version of the new path against what we have stored to determine
7694                // what to do.
7695                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7696                if (pkg.mVersionCode <= ps.versionCode) {
7697                    // The system package has been updated and the code path does not match
7698                    // Ignore entry. Skip it.
7699                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7700                            + " ignored: updated version " + ps.versionCode
7701                            + " better than this " + pkg.mVersionCode);
7702                    if (!updatedPkg.codePath.equals(scanFile)) {
7703                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7704                                + ps.name + " changing from " + updatedPkg.codePathString
7705                                + " to " + scanFile);
7706                        updatedPkg.codePath = scanFile;
7707                        updatedPkg.codePathString = scanFile.toString();
7708                        updatedPkg.resourcePath = scanFile;
7709                        updatedPkg.resourcePathString = scanFile.toString();
7710                    }
7711                    updatedPkg.pkg = pkg;
7712                    updatedPkg.versionCode = pkg.mVersionCode;
7713
7714                    // Update the disabled system child packages to point to the package too.
7715                    final int childCount = updatedPkg.childPackageNames != null
7716                            ? updatedPkg.childPackageNames.size() : 0;
7717                    for (int i = 0; i < childCount; i++) {
7718                        String childPackageName = updatedPkg.childPackageNames.get(i);
7719                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7720                                childPackageName);
7721                        if (updatedChildPkg != null) {
7722                            updatedChildPkg.pkg = pkg;
7723                            updatedChildPkg.versionCode = pkg.mVersionCode;
7724                        }
7725                    }
7726
7727                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7728                            + scanFile + " ignored: updated version " + ps.versionCode
7729                            + " better than this " + pkg.mVersionCode);
7730                } else {
7731                    // The current app on the system partition is better than
7732                    // what we have updated to on the data partition; switch
7733                    // back to the system partition version.
7734                    // At this point, its safely assumed that package installation for
7735                    // apps in system partition will go through. If not there won't be a working
7736                    // version of the app
7737                    // writer
7738                    synchronized (mPackages) {
7739                        // Just remove the loaded entries from package lists.
7740                        mPackages.remove(ps.name);
7741                    }
7742
7743                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7744                            + " reverting from " + ps.codePathString
7745                            + ": new version " + pkg.mVersionCode
7746                            + " better than installed " + ps.versionCode);
7747
7748                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7749                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7750                    synchronized (mInstallLock) {
7751                        args.cleanUpResourcesLI();
7752                    }
7753                    synchronized (mPackages) {
7754                        mSettings.enableSystemPackageLPw(ps.name);
7755                    }
7756                    updatedPkgBetter = true;
7757                }
7758            }
7759        }
7760
7761        if (updatedPkg != null) {
7762            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7763            // initially
7764            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7765
7766            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7767            // flag set initially
7768            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7769                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7770            }
7771        }
7772
7773        // Verify certificates against what was last scanned
7774        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7775
7776        /*
7777         * A new system app appeared, but we already had a non-system one of the
7778         * same name installed earlier.
7779         */
7780        boolean shouldHideSystemApp = false;
7781        if (updatedPkg == null && ps != null
7782                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7783            /*
7784             * Check to make sure the signatures match first. If they don't,
7785             * wipe the installed application and its data.
7786             */
7787            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7788                    != PackageManager.SIGNATURE_MATCH) {
7789                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7790                        + " signatures don't match existing userdata copy; removing");
7791                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7792                        "scanPackageInternalLI")) {
7793                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7794                }
7795                ps = null;
7796            } else {
7797                /*
7798                 * If the newly-added system app is an older version than the
7799                 * already installed version, hide it. It will be scanned later
7800                 * and re-added like an update.
7801                 */
7802                if (pkg.mVersionCode <= ps.versionCode) {
7803                    shouldHideSystemApp = true;
7804                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7805                            + " but new version " + pkg.mVersionCode + " better than installed "
7806                            + ps.versionCode + "; hiding system");
7807                } else {
7808                    /*
7809                     * The newly found system app is a newer version that the
7810                     * one previously installed. Simply remove the
7811                     * already-installed application and replace it with our own
7812                     * while keeping the application data.
7813                     */
7814                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7815                            + " reverting from " + ps.codePathString + ": new version "
7816                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7817                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7818                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7819                    synchronized (mInstallLock) {
7820                        args.cleanUpResourcesLI();
7821                    }
7822                }
7823            }
7824        }
7825
7826        // The apk is forward locked (not public) if its code and resources
7827        // are kept in different files. (except for app in either system or
7828        // vendor path).
7829        // TODO grab this value from PackageSettings
7830        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7831            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7832                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7833            }
7834        }
7835
7836        // TODO: extend to support forward-locked splits
7837        String resourcePath = null;
7838        String baseResourcePath = null;
7839        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7840            if (ps != null && ps.resourcePathString != null) {
7841                resourcePath = ps.resourcePathString;
7842                baseResourcePath = ps.resourcePathString;
7843            } else {
7844                // Should not happen at all. Just log an error.
7845                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7846            }
7847        } else {
7848            resourcePath = pkg.codePath;
7849            baseResourcePath = pkg.baseCodePath;
7850        }
7851
7852        // Set application objects path explicitly.
7853        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7854        pkg.setApplicationInfoCodePath(pkg.codePath);
7855        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7856        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7857        pkg.setApplicationInfoResourcePath(resourcePath);
7858        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7859        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7860
7861        // Note that we invoke the following method only if we are about to unpack an application
7862        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7863                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7864
7865        /*
7866         * If the system app should be overridden by a previously installed
7867         * data, hide the system app now and let the /data/app scan pick it up
7868         * again.
7869         */
7870        if (shouldHideSystemApp) {
7871            synchronized (mPackages) {
7872                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7873            }
7874        }
7875
7876        return scannedPkg;
7877    }
7878
7879    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7880        // Derive the new package synthetic package name
7881        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7882                + pkg.staticSharedLibVersion);
7883    }
7884
7885    private static String fixProcessName(String defProcessName,
7886            String processName) {
7887        if (processName == null) {
7888            return defProcessName;
7889        }
7890        return processName;
7891    }
7892
7893    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7894            throws PackageManagerException {
7895        if (pkgSetting.signatures.mSignatures != null) {
7896            // Already existing package. Make sure signatures match
7897            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7898                    == PackageManager.SIGNATURE_MATCH;
7899            if (!match) {
7900                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7901                        == PackageManager.SIGNATURE_MATCH;
7902            }
7903            if (!match) {
7904                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7905                        == PackageManager.SIGNATURE_MATCH;
7906            }
7907            if (!match) {
7908                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7909                        + pkg.packageName + " signatures do not match the "
7910                        + "previously installed version; ignoring!");
7911            }
7912        }
7913
7914        // Check for shared user signatures
7915        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7916            // Already existing package. Make sure signatures match
7917            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7918                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7919            if (!match) {
7920                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7921                        == PackageManager.SIGNATURE_MATCH;
7922            }
7923            if (!match) {
7924                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7925                        == PackageManager.SIGNATURE_MATCH;
7926            }
7927            if (!match) {
7928                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7929                        "Package " + pkg.packageName
7930                        + " has no signatures that match those in shared user "
7931                        + pkgSetting.sharedUser.name + "; ignoring!");
7932            }
7933        }
7934    }
7935
7936    /**
7937     * Enforces that only the system UID or root's UID can call a method exposed
7938     * via Binder.
7939     *
7940     * @param message used as message if SecurityException is thrown
7941     * @throws SecurityException if the caller is not system or root
7942     */
7943    private static final void enforceSystemOrRoot(String message) {
7944        final int uid = Binder.getCallingUid();
7945        if (uid != Process.SYSTEM_UID && uid != 0) {
7946            throw new SecurityException(message);
7947        }
7948    }
7949
7950    @Override
7951    public void performFstrimIfNeeded() {
7952        enforceSystemOrRoot("Only the system can request fstrim");
7953
7954        // Before everything else, see whether we need to fstrim.
7955        try {
7956            IStorageManager sm = PackageHelper.getStorageManager();
7957            if (sm != null) {
7958                boolean doTrim = false;
7959                final long interval = android.provider.Settings.Global.getLong(
7960                        mContext.getContentResolver(),
7961                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7962                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7963                if (interval > 0) {
7964                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7965                    if (timeSinceLast > interval) {
7966                        doTrim = true;
7967                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7968                                + "; running immediately");
7969                    }
7970                }
7971                if (doTrim) {
7972                    final boolean dexOptDialogShown;
7973                    synchronized (mPackages) {
7974                        dexOptDialogShown = mDexOptDialogShown;
7975                    }
7976                    if (!isFirstBoot() && dexOptDialogShown) {
7977                        try {
7978                            ActivityManager.getService().showBootMessage(
7979                                    mContext.getResources().getString(
7980                                            R.string.android_upgrading_fstrim), true);
7981                        } catch (RemoteException e) {
7982                        }
7983                    }
7984                    sm.runMaintenance();
7985                }
7986            } else {
7987                Slog.e(TAG, "storageManager service unavailable!");
7988            }
7989        } catch (RemoteException e) {
7990            // Can't happen; StorageManagerService is local
7991        }
7992    }
7993
7994    @Override
7995    public void updatePackagesIfNeeded() {
7996        enforceSystemOrRoot("Only the system can request package update");
7997
7998        // We need to re-extract after an OTA.
7999        boolean causeUpgrade = isUpgrade();
8000
8001        // First boot or factory reset.
8002        // Note: we also handle devices that are upgrading to N right now as if it is their
8003        //       first boot, as they do not have profile data.
8004        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8005
8006        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8007        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8008
8009        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8010            return;
8011        }
8012
8013        List<PackageParser.Package> pkgs;
8014        synchronized (mPackages) {
8015            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8016        }
8017
8018        final long startTime = System.nanoTime();
8019        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8020                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8021
8022        final int elapsedTimeSeconds =
8023                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8024
8025        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8026        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8027        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8028        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8029        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8030    }
8031
8032    /**
8033     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8034     * containing statistics about the invocation. The array consists of three elements,
8035     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8036     * and {@code numberOfPackagesFailed}.
8037     */
8038    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8039            String compilerFilter) {
8040
8041        int numberOfPackagesVisited = 0;
8042        int numberOfPackagesOptimized = 0;
8043        int numberOfPackagesSkipped = 0;
8044        int numberOfPackagesFailed = 0;
8045        final int numberOfPackagesToDexopt = pkgs.size();
8046
8047        for (PackageParser.Package pkg : pkgs) {
8048            numberOfPackagesVisited++;
8049
8050            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8051                if (DEBUG_DEXOPT) {
8052                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8053                }
8054                numberOfPackagesSkipped++;
8055                continue;
8056            }
8057
8058            if (DEBUG_DEXOPT) {
8059                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8060                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8061            }
8062
8063            if (showDialog) {
8064                try {
8065                    ActivityManager.getService().showBootMessage(
8066                            mContext.getResources().getString(R.string.android_upgrading_apk,
8067                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8068                } catch (RemoteException e) {
8069                }
8070                synchronized (mPackages) {
8071                    mDexOptDialogShown = true;
8072                }
8073            }
8074
8075            // If the OTA updates a system app which was previously preopted to a non-preopted state
8076            // the app might end up being verified at runtime. That's because by default the apps
8077            // are verify-profile but for preopted apps there's no profile.
8078            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8079            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8080            // filter (by default interpret-only).
8081            // Note that at this stage unused apps are already filtered.
8082            if (isSystemApp(pkg) &&
8083                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8084                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8085                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8086            }
8087
8088            // checkProfiles is false to avoid merging profiles during boot which
8089            // might interfere with background compilation (b/28612421).
8090            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8091            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8092            // trade-off worth doing to save boot time work.
8093            int dexOptStatus = performDexOptTraced(pkg.packageName,
8094                    false /* checkProfiles */,
8095                    compilerFilter,
8096                    false /* force */);
8097            switch (dexOptStatus) {
8098                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8099                    numberOfPackagesOptimized++;
8100                    break;
8101                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8102                    numberOfPackagesSkipped++;
8103                    break;
8104                case PackageDexOptimizer.DEX_OPT_FAILED:
8105                    numberOfPackagesFailed++;
8106                    break;
8107                default:
8108                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8109                    break;
8110            }
8111        }
8112
8113        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8114                numberOfPackagesFailed };
8115    }
8116
8117    @Override
8118    public void notifyPackageUse(String packageName, int reason) {
8119        synchronized (mPackages) {
8120            PackageParser.Package p = mPackages.get(packageName);
8121            if (p == null) {
8122                return;
8123            }
8124            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8125        }
8126    }
8127
8128    @Override
8129    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8130        int userId = UserHandle.getCallingUserId();
8131        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8132        if (ai == null) {
8133            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8134                + loadingPackageName + ", user=" + userId);
8135            return;
8136        }
8137        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8138    }
8139
8140    // TODO: this is not used nor needed. Delete it.
8141    @Override
8142    public boolean performDexOptIfNeeded(String packageName) {
8143        int dexOptStatus = performDexOptTraced(packageName,
8144                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8145        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8146    }
8147
8148    @Override
8149    public boolean performDexOpt(String packageName,
8150            boolean checkProfiles, int compileReason, boolean force) {
8151        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8152                getCompilerFilterForReason(compileReason), force);
8153        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8154    }
8155
8156    @Override
8157    public boolean performDexOptMode(String packageName,
8158            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8159        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8160                targetCompilerFilter, force);
8161        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8162    }
8163
8164    private int performDexOptTraced(String packageName,
8165                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8166        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8167        try {
8168            return performDexOptInternal(packageName, checkProfiles,
8169                    targetCompilerFilter, force);
8170        } finally {
8171            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8172        }
8173    }
8174
8175    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8176    // if the package can now be considered up to date for the given filter.
8177    private int performDexOptInternal(String packageName,
8178                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8179        PackageParser.Package p;
8180        synchronized (mPackages) {
8181            p = mPackages.get(packageName);
8182            if (p == null) {
8183                // Package could not be found. Report failure.
8184                return PackageDexOptimizer.DEX_OPT_FAILED;
8185            }
8186            mPackageUsage.maybeWriteAsync(mPackages);
8187            mCompilerStats.maybeWriteAsync();
8188        }
8189        long callingId = Binder.clearCallingIdentity();
8190        try {
8191            synchronized (mInstallLock) {
8192                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8193                        targetCompilerFilter, force);
8194            }
8195        } finally {
8196            Binder.restoreCallingIdentity(callingId);
8197        }
8198    }
8199
8200    public ArraySet<String> getOptimizablePackages() {
8201        ArraySet<String> pkgs = new ArraySet<String>();
8202        synchronized (mPackages) {
8203            for (PackageParser.Package p : mPackages.values()) {
8204                if (PackageDexOptimizer.canOptimizePackage(p)) {
8205                    pkgs.add(p.packageName);
8206                }
8207            }
8208        }
8209        return pkgs;
8210    }
8211
8212    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8213            boolean checkProfiles, String targetCompilerFilter,
8214            boolean force) {
8215        // Select the dex optimizer based on the force parameter.
8216        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8217        //       allocate an object here.
8218        PackageDexOptimizer pdo = force
8219                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8220                : mPackageDexOptimizer;
8221
8222        // Optimize all dependencies first. Note: we ignore the return value and march on
8223        // on errors.
8224        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8225        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8226        if (!deps.isEmpty()) {
8227            for (PackageParser.Package depPackage : deps) {
8228                // TODO: Analyze and investigate if we (should) profile libraries.
8229                // Currently this will do a full compilation of the library by default.
8230                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8231                        false /* checkProfiles */,
8232                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8233                        getOrCreateCompilerPackageStats(depPackage));
8234            }
8235        }
8236        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8237                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8238    }
8239
8240    // Performs dexopt on the used secondary dex files belonging to the given package.
8241    // Returns true if all dex files were process successfully (which could mean either dexopt or
8242    // skip). Returns false if any of the files caused errors.
8243    @Override
8244    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8245            boolean force) {
8246        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8247    }
8248
8249    /**
8250     * Reconcile the information we have about the secondary dex files belonging to
8251     * {@code packagName} and the actual dex files. For all dex files that were
8252     * deleted, update the internal records and delete the generated oat files.
8253     */
8254    @Override
8255    public void reconcileSecondaryDexFiles(String packageName) {
8256        mDexManager.reconcileSecondaryDexFiles(packageName);
8257    }
8258
8259    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8260    // a reference there.
8261    /*package*/ DexManager getDexManager() {
8262        return mDexManager;
8263    }
8264
8265    /**
8266     * Execute the background dexopt job immediately.
8267     */
8268    @Override
8269    public boolean runBackgroundDexoptJob() {
8270        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8271    }
8272
8273    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8274        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8275                || p.usesStaticLibraries != null) {
8276            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8277            Set<String> collectedNames = new HashSet<>();
8278            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8279
8280            retValue.remove(p);
8281
8282            return retValue;
8283        } else {
8284            return Collections.emptyList();
8285        }
8286    }
8287
8288    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8289            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8290        if (!collectedNames.contains(p.packageName)) {
8291            collectedNames.add(p.packageName);
8292            collected.add(p);
8293
8294            if (p.usesLibraries != null) {
8295                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8296                        null, collected, collectedNames);
8297            }
8298            if (p.usesOptionalLibraries != null) {
8299                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8300                        null, collected, collectedNames);
8301            }
8302            if (p.usesStaticLibraries != null) {
8303                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8304                        p.usesStaticLibrariesVersions, collected, collectedNames);
8305            }
8306        }
8307    }
8308
8309    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8310            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8311        final int libNameCount = libs.size();
8312        for (int i = 0; i < libNameCount; i++) {
8313            String libName = libs.get(i);
8314            int version = (versions != null && versions.length == libNameCount)
8315                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8316            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8317            if (libPkg != null) {
8318                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8319            }
8320        }
8321    }
8322
8323    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8324        synchronized (mPackages) {
8325            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8326            if (libEntry != null) {
8327                return mPackages.get(libEntry.apk);
8328            }
8329            return null;
8330        }
8331    }
8332
8333    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8334        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8335        if (versionedLib == null) {
8336            return null;
8337        }
8338        return versionedLib.get(version);
8339    }
8340
8341    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8342        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8343                pkg.staticSharedLibName);
8344        if (versionedLib == null) {
8345            return null;
8346        }
8347        int previousLibVersion = -1;
8348        final int versionCount = versionedLib.size();
8349        for (int i = 0; i < versionCount; i++) {
8350            final int libVersion = versionedLib.keyAt(i);
8351            if (libVersion < pkg.staticSharedLibVersion) {
8352                previousLibVersion = Math.max(previousLibVersion, libVersion);
8353            }
8354        }
8355        if (previousLibVersion >= 0) {
8356            return versionedLib.get(previousLibVersion);
8357        }
8358        return null;
8359    }
8360
8361    public void shutdown() {
8362        mPackageUsage.writeNow(mPackages);
8363        mCompilerStats.writeNow();
8364    }
8365
8366    @Override
8367    public void dumpProfiles(String packageName) {
8368        PackageParser.Package pkg;
8369        synchronized (mPackages) {
8370            pkg = mPackages.get(packageName);
8371            if (pkg == null) {
8372                throw new IllegalArgumentException("Unknown package: " + packageName);
8373            }
8374        }
8375        /* Only the shell, root, or the app user should be able to dump profiles. */
8376        int callingUid = Binder.getCallingUid();
8377        if (callingUid != Process.SHELL_UID &&
8378            callingUid != Process.ROOT_UID &&
8379            callingUid != pkg.applicationInfo.uid) {
8380            throw new SecurityException("dumpProfiles");
8381        }
8382
8383        synchronized (mInstallLock) {
8384            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8385            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8386            try {
8387                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8388                String codePaths = TextUtils.join(";", allCodePaths);
8389                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8390            } catch (InstallerException e) {
8391                Slog.w(TAG, "Failed to dump profiles", e);
8392            }
8393            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8394        }
8395    }
8396
8397    @Override
8398    public void forceDexOpt(String packageName) {
8399        enforceSystemOrRoot("forceDexOpt");
8400
8401        PackageParser.Package pkg;
8402        synchronized (mPackages) {
8403            pkg = mPackages.get(packageName);
8404            if (pkg == null) {
8405                throw new IllegalArgumentException("Unknown package: " + packageName);
8406            }
8407        }
8408
8409        synchronized (mInstallLock) {
8410            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8411
8412            // Whoever is calling forceDexOpt wants a fully compiled package.
8413            // Don't use profiles since that may cause compilation to be skipped.
8414            final int res = performDexOptInternalWithDependenciesLI(pkg,
8415                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8416                    true /* force */);
8417
8418            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8419            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8420                throw new IllegalStateException("Failed to dexopt: " + res);
8421            }
8422        }
8423    }
8424
8425    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8426        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8427            Slog.w(TAG, "Unable to update from " + oldPkg.name
8428                    + " to " + newPkg.packageName
8429                    + ": old package not in system partition");
8430            return false;
8431        } else if (mPackages.get(oldPkg.name) != null) {
8432            Slog.w(TAG, "Unable to update from " + oldPkg.name
8433                    + " to " + newPkg.packageName
8434                    + ": old package still exists");
8435            return false;
8436        }
8437        return true;
8438    }
8439
8440    void removeCodePathLI(File codePath) {
8441        if (codePath.isDirectory()) {
8442            try {
8443                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8444            } catch (InstallerException e) {
8445                Slog.w(TAG, "Failed to remove code path", e);
8446            }
8447        } else {
8448            codePath.delete();
8449        }
8450    }
8451
8452    private int[] resolveUserIds(int userId) {
8453        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8454    }
8455
8456    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8457        if (pkg == null) {
8458            Slog.wtf(TAG, "Package was null!", new Throwable());
8459            return;
8460        }
8461        clearAppDataLeafLIF(pkg, userId, flags);
8462        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8463        for (int i = 0; i < childCount; i++) {
8464            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8465        }
8466    }
8467
8468    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8469        final PackageSetting ps;
8470        synchronized (mPackages) {
8471            ps = mSettings.mPackages.get(pkg.packageName);
8472        }
8473        for (int realUserId : resolveUserIds(userId)) {
8474            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8475            try {
8476                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8477                        ceDataInode);
8478            } catch (InstallerException e) {
8479                Slog.w(TAG, String.valueOf(e));
8480            }
8481        }
8482    }
8483
8484    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8485        if (pkg == null) {
8486            Slog.wtf(TAG, "Package was null!", new Throwable());
8487            return;
8488        }
8489        destroyAppDataLeafLIF(pkg, userId, flags);
8490        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8491        for (int i = 0; i < childCount; i++) {
8492            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8493        }
8494    }
8495
8496    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8497        final PackageSetting ps;
8498        synchronized (mPackages) {
8499            ps = mSettings.mPackages.get(pkg.packageName);
8500        }
8501        for (int realUserId : resolveUserIds(userId)) {
8502            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8503            try {
8504                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8505                        ceDataInode);
8506            } catch (InstallerException e) {
8507                Slog.w(TAG, String.valueOf(e));
8508            }
8509        }
8510    }
8511
8512    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8513        if (pkg == null) {
8514            Slog.wtf(TAG, "Package was null!", new Throwable());
8515            return;
8516        }
8517        destroyAppProfilesLeafLIF(pkg);
8518        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8519        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8520        for (int i = 0; i < childCount; i++) {
8521            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8522            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8523                    true /* removeBaseMarker */);
8524        }
8525    }
8526
8527    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8528            boolean removeBaseMarker) {
8529        if (pkg.isForwardLocked()) {
8530            return;
8531        }
8532
8533        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8534            try {
8535                path = PackageManagerServiceUtils.realpath(new File(path));
8536            } catch (IOException e) {
8537                // TODO: Should we return early here ?
8538                Slog.w(TAG, "Failed to get canonical path", e);
8539                continue;
8540            }
8541
8542            final String useMarker = path.replace('/', '@');
8543            for (int realUserId : resolveUserIds(userId)) {
8544                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8545                if (removeBaseMarker) {
8546                    File foreignUseMark = new File(profileDir, useMarker);
8547                    if (foreignUseMark.exists()) {
8548                        if (!foreignUseMark.delete()) {
8549                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8550                                    + pkg.packageName);
8551                        }
8552                    }
8553                }
8554
8555                File[] markers = profileDir.listFiles();
8556                if (markers != null) {
8557                    final String searchString = "@" + pkg.packageName + "@";
8558                    // We also delete all markers that contain the package name we're
8559                    // uninstalling. These are associated with secondary dex-files belonging
8560                    // to the package. Reconstructing the path of these dex files is messy
8561                    // in general.
8562                    for (File marker : markers) {
8563                        if (marker.getName().indexOf(searchString) > 0) {
8564                            if (!marker.delete()) {
8565                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8566                                    + pkg.packageName);
8567                            }
8568                        }
8569                    }
8570                }
8571            }
8572        }
8573    }
8574
8575    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8576        try {
8577            mInstaller.destroyAppProfiles(pkg.packageName);
8578        } catch (InstallerException e) {
8579            Slog.w(TAG, String.valueOf(e));
8580        }
8581    }
8582
8583    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8584        if (pkg == null) {
8585            Slog.wtf(TAG, "Package was null!", new Throwable());
8586            return;
8587        }
8588        clearAppProfilesLeafLIF(pkg);
8589        // We don't remove the base foreign use marker when clearing profiles because
8590        // we will rename it when the app is updated. Unlike the actual profile contents,
8591        // the foreign use marker is good across installs.
8592        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8593        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8594        for (int i = 0; i < childCount; i++) {
8595            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8596        }
8597    }
8598
8599    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8600        try {
8601            mInstaller.clearAppProfiles(pkg.packageName);
8602        } catch (InstallerException e) {
8603            Slog.w(TAG, String.valueOf(e));
8604        }
8605    }
8606
8607    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8608            long lastUpdateTime) {
8609        // Set parent install/update time
8610        PackageSetting ps = (PackageSetting) pkg.mExtras;
8611        if (ps != null) {
8612            ps.firstInstallTime = firstInstallTime;
8613            ps.lastUpdateTime = lastUpdateTime;
8614        }
8615        // Set children install/update time
8616        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8617        for (int i = 0; i < childCount; i++) {
8618            PackageParser.Package childPkg = pkg.childPackages.get(i);
8619            ps = (PackageSetting) childPkg.mExtras;
8620            if (ps != null) {
8621                ps.firstInstallTime = firstInstallTime;
8622                ps.lastUpdateTime = lastUpdateTime;
8623            }
8624        }
8625    }
8626
8627    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8628            PackageParser.Package changingLib) {
8629        if (file.path != null) {
8630            usesLibraryFiles.add(file.path);
8631            return;
8632        }
8633        PackageParser.Package p = mPackages.get(file.apk);
8634        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8635            // If we are doing this while in the middle of updating a library apk,
8636            // then we need to make sure to use that new apk for determining the
8637            // dependencies here.  (We haven't yet finished committing the new apk
8638            // to the package manager state.)
8639            if (p == null || p.packageName.equals(changingLib.packageName)) {
8640                p = changingLib;
8641            }
8642        }
8643        if (p != null) {
8644            usesLibraryFiles.addAll(p.getAllCodePaths());
8645        }
8646    }
8647
8648    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8649            PackageParser.Package changingLib) throws PackageManagerException {
8650        if (pkg == null) {
8651            return;
8652        }
8653        ArraySet<String> usesLibraryFiles = null;
8654        if (pkg.usesLibraries != null) {
8655            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8656                    null, null, pkg.packageName, changingLib, true, null);
8657        }
8658        if (pkg.usesStaticLibraries != null) {
8659            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8660                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8661                    pkg.packageName, changingLib, true, usesLibraryFiles);
8662        }
8663        if (pkg.usesOptionalLibraries != null) {
8664            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8665                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8666        }
8667        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8668            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8669        } else {
8670            pkg.usesLibraryFiles = null;
8671        }
8672    }
8673
8674    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8675            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8676            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8677            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8678            throws PackageManagerException {
8679        final int libCount = requestedLibraries.size();
8680        for (int i = 0; i < libCount; i++) {
8681            final String libName = requestedLibraries.get(i);
8682            final int libVersion = requiredVersions != null ? requiredVersions[i]
8683                    : SharedLibraryInfo.VERSION_UNDEFINED;
8684            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8685            if (libEntry == null) {
8686                if (required) {
8687                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8688                            "Package " + packageName + " requires unavailable shared library "
8689                                    + libName + "; failing!");
8690                } else {
8691                    Slog.w(TAG, "Package " + packageName
8692                            + " desires unavailable shared library "
8693                            + libName + "; ignoring!");
8694                }
8695            } else {
8696                if (requiredVersions != null && requiredCertDigests != null) {
8697                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8698                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8699                            "Package " + packageName + " requires unavailable static shared"
8700                                    + " library " + libName + " version "
8701                                    + libEntry.info.getVersion() + "; failing!");
8702                    }
8703
8704                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8705                    if (libPkg == null) {
8706                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8707                                "Package " + packageName + " requires unavailable static shared"
8708                                        + " library; failing!");
8709                    }
8710
8711                    String expectedCertDigest = requiredCertDigests[i];
8712                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8713                                libPkg.mSignatures[0]);
8714                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8715                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8716                                "Package " + packageName + " requires differently signed" +
8717                                        " static shared library; failing!");
8718                    }
8719                }
8720
8721                if (outUsedLibraries == null) {
8722                    outUsedLibraries = new ArraySet<>();
8723                }
8724                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8725            }
8726        }
8727        return outUsedLibraries;
8728    }
8729
8730    private static boolean hasString(List<String> list, List<String> which) {
8731        if (list == null) {
8732            return false;
8733        }
8734        for (int i=list.size()-1; i>=0; i--) {
8735            for (int j=which.size()-1; j>=0; j--) {
8736                if (which.get(j).equals(list.get(i))) {
8737                    return true;
8738                }
8739            }
8740        }
8741        return false;
8742    }
8743
8744    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8745            PackageParser.Package changingPkg) {
8746        ArrayList<PackageParser.Package> res = null;
8747        for (PackageParser.Package pkg : mPackages.values()) {
8748            if (changingPkg != null
8749                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8750                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8751                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8752                            changingPkg.staticSharedLibName)) {
8753                return null;
8754            }
8755            if (res == null) {
8756                res = new ArrayList<>();
8757            }
8758            res.add(pkg);
8759            try {
8760                updateSharedLibrariesLPr(pkg, changingPkg);
8761            } catch (PackageManagerException e) {
8762                // If a system app update or an app and a required lib missing we
8763                // delete the package and for updated system apps keep the data as
8764                // it is better for the user to reinstall than to be in an limbo
8765                // state. Also libs disappearing under an app should never happen
8766                // - just in case.
8767                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8768                    final int flags = pkg.isUpdatedSystemApp()
8769                            ? PackageManager.DELETE_KEEP_DATA : 0;
8770                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8771                            flags , null, true, null);
8772                }
8773                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8774            }
8775        }
8776        return res;
8777    }
8778
8779    /**
8780     * Derive the value of the {@code cpuAbiOverride} based on the provided
8781     * value and an optional stored value from the package settings.
8782     */
8783    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8784        String cpuAbiOverride = null;
8785
8786        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8787            cpuAbiOverride = null;
8788        } else if (abiOverride != null) {
8789            cpuAbiOverride = abiOverride;
8790        } else if (settings != null) {
8791            cpuAbiOverride = settings.cpuAbiOverrideString;
8792        }
8793
8794        return cpuAbiOverride;
8795    }
8796
8797    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8798            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8799                    throws PackageManagerException {
8800        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8801        // If the package has children and this is the first dive in the function
8802        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8803        // whether all packages (parent and children) would be successfully scanned
8804        // before the actual scan since scanning mutates internal state and we want
8805        // to atomically install the package and its children.
8806        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8807            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8808                scanFlags |= SCAN_CHECK_ONLY;
8809            }
8810        } else {
8811            scanFlags &= ~SCAN_CHECK_ONLY;
8812        }
8813
8814        final PackageParser.Package scannedPkg;
8815        try {
8816            // Scan the parent
8817            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8818            // Scan the children
8819            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8820            for (int i = 0; i < childCount; i++) {
8821                PackageParser.Package childPkg = pkg.childPackages.get(i);
8822                scanPackageLI(childPkg, policyFlags,
8823                        scanFlags, currentTime, user);
8824            }
8825        } finally {
8826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8827        }
8828
8829        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8830            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8831        }
8832
8833        return scannedPkg;
8834    }
8835
8836    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8837            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8838        boolean success = false;
8839        try {
8840            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8841                    currentTime, user);
8842            success = true;
8843            return res;
8844        } finally {
8845            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8846                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8847                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8848                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8849                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8850            }
8851        }
8852    }
8853
8854    /**
8855     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8856     */
8857    private static boolean apkHasCode(String fileName) {
8858        StrictJarFile jarFile = null;
8859        try {
8860            jarFile = new StrictJarFile(fileName,
8861                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8862            return jarFile.findEntry("classes.dex") != null;
8863        } catch (IOException ignore) {
8864        } finally {
8865            try {
8866                if (jarFile != null) {
8867                    jarFile.close();
8868                }
8869            } catch (IOException ignore) {}
8870        }
8871        return false;
8872    }
8873
8874    /**
8875     * Enforces code policy for the package. This ensures that if an APK has
8876     * declared hasCode="true" in its manifest that the APK actually contains
8877     * code.
8878     *
8879     * @throws PackageManagerException If bytecode could not be found when it should exist
8880     */
8881    private static void assertCodePolicy(PackageParser.Package pkg)
8882            throws PackageManagerException {
8883        final boolean shouldHaveCode =
8884                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8885        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8886            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8887                    "Package " + pkg.baseCodePath + " code is missing");
8888        }
8889
8890        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8891            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8892                final boolean splitShouldHaveCode =
8893                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8894                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8895                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8896                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8897                }
8898            }
8899        }
8900    }
8901
8902    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8903            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8904                    throws PackageManagerException {
8905        if (DEBUG_PACKAGE_SCANNING) {
8906            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8907                Log.d(TAG, "Scanning package " + pkg.packageName);
8908        }
8909
8910        applyPolicy(pkg, policyFlags);
8911
8912        assertPackageIsValid(pkg, policyFlags, scanFlags);
8913
8914        // Initialize package source and resource directories
8915        final File scanFile = new File(pkg.codePath);
8916        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8917        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8918
8919        SharedUserSetting suid = null;
8920        PackageSetting pkgSetting = null;
8921
8922        // Getting the package setting may have a side-effect, so if we
8923        // are only checking if scan would succeed, stash a copy of the
8924        // old setting to restore at the end.
8925        PackageSetting nonMutatedPs = null;
8926
8927        // We keep references to the derived CPU Abis from settings in oder to reuse
8928        // them in the case where we're not upgrading or booting for the first time.
8929        String primaryCpuAbiFromSettings = null;
8930        String secondaryCpuAbiFromSettings = null;
8931
8932        // writer
8933        synchronized (mPackages) {
8934            if (pkg.mSharedUserId != null) {
8935                // SIDE EFFECTS; may potentially allocate a new shared user
8936                suid = mSettings.getSharedUserLPw(
8937                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8938                if (DEBUG_PACKAGE_SCANNING) {
8939                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8940                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8941                                + "): packages=" + suid.packages);
8942                }
8943            }
8944
8945            // Check if we are renaming from an original package name.
8946            PackageSetting origPackage = null;
8947            String realName = null;
8948            if (pkg.mOriginalPackages != null) {
8949                // This package may need to be renamed to a previously
8950                // installed name.  Let's check on that...
8951                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8952                if (pkg.mOriginalPackages.contains(renamed)) {
8953                    // This package had originally been installed as the
8954                    // original name, and we have already taken care of
8955                    // transitioning to the new one.  Just update the new
8956                    // one to continue using the old name.
8957                    realName = pkg.mRealPackage;
8958                    if (!pkg.packageName.equals(renamed)) {
8959                        // Callers into this function may have already taken
8960                        // care of renaming the package; only do it here if
8961                        // it is not already done.
8962                        pkg.setPackageName(renamed);
8963                    }
8964                } else {
8965                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8966                        if ((origPackage = mSettings.getPackageLPr(
8967                                pkg.mOriginalPackages.get(i))) != null) {
8968                            // We do have the package already installed under its
8969                            // original name...  should we use it?
8970                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8971                                // New package is not compatible with original.
8972                                origPackage = null;
8973                                continue;
8974                            } else if (origPackage.sharedUser != null) {
8975                                // Make sure uid is compatible between packages.
8976                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8977                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8978                                            + " to " + pkg.packageName + ": old uid "
8979                                            + origPackage.sharedUser.name
8980                                            + " differs from " + pkg.mSharedUserId);
8981                                    origPackage = null;
8982                                    continue;
8983                                }
8984                                // TODO: Add case when shared user id is added [b/28144775]
8985                            } else {
8986                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8987                                        + pkg.packageName + " to old name " + origPackage.name);
8988                            }
8989                            break;
8990                        }
8991                    }
8992                }
8993            }
8994
8995            if (mTransferedPackages.contains(pkg.packageName)) {
8996                Slog.w(TAG, "Package " + pkg.packageName
8997                        + " was transferred to another, but its .apk remains");
8998            }
8999
9000            // See comments in nonMutatedPs declaration
9001            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9002                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9003                if (foundPs != null) {
9004                    nonMutatedPs = new PackageSetting(foundPs);
9005                }
9006            }
9007
9008            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9009                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9010                if (foundPs != null) {
9011                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9012                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9013                }
9014            }
9015
9016            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9017            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9018                PackageManagerService.reportSettingsProblem(Log.WARN,
9019                        "Package " + pkg.packageName + " shared user changed from "
9020                                + (pkgSetting.sharedUser != null
9021                                        ? pkgSetting.sharedUser.name : "<nothing>")
9022                                + " to "
9023                                + (suid != null ? suid.name : "<nothing>")
9024                                + "; replacing with new");
9025                pkgSetting = null;
9026            }
9027            final PackageSetting oldPkgSetting =
9028                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9029            final PackageSetting disabledPkgSetting =
9030                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9031
9032            String[] usesStaticLibraries = null;
9033            if (pkg.usesStaticLibraries != null) {
9034                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9035                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9036            }
9037
9038            if (pkgSetting == null) {
9039                final String parentPackageName = (pkg.parentPackage != null)
9040                        ? pkg.parentPackage.packageName : null;
9041
9042                // REMOVE SharedUserSetting from method; update in a separate call
9043                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9044                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9045                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9046                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9047                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9048                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
9049                        UserManagerService.getInstance(), usesStaticLibraries,
9050                        pkg.usesStaticLibrariesVersions);
9051                // SIDE EFFECTS; updates system state; move elsewhere
9052                if (origPackage != null) {
9053                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9054                }
9055                mSettings.addUserToSettingLPw(pkgSetting);
9056            } else {
9057                // REMOVE SharedUserSetting from method; update in a separate call.
9058                //
9059                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9060                // secondaryCpuAbi are not known at this point so we always update them
9061                // to null here, only to reset them at a later point.
9062                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9063                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9064                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9065                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9066                        UserManagerService.getInstance(), usesStaticLibraries,
9067                        pkg.usesStaticLibrariesVersions);
9068            }
9069            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9070            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9071
9072            // SIDE EFFECTS; modifies system state; move elsewhere
9073            if (pkgSetting.origPackage != null) {
9074                // If we are first transitioning from an original package,
9075                // fix up the new package's name now.  We need to do this after
9076                // looking up the package under its new name, so getPackageLP
9077                // can take care of fiddling things correctly.
9078                pkg.setPackageName(origPackage.name);
9079
9080                // File a report about this.
9081                String msg = "New package " + pkgSetting.realName
9082                        + " renamed to replace old package " + pkgSetting.name;
9083                reportSettingsProblem(Log.WARN, msg);
9084
9085                // Make a note of it.
9086                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9087                    mTransferedPackages.add(origPackage.name);
9088                }
9089
9090                // No longer need to retain this.
9091                pkgSetting.origPackage = null;
9092            }
9093
9094            // SIDE EFFECTS; modifies system state; move elsewhere
9095            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9096                // Make a note of it.
9097                mTransferedPackages.add(pkg.packageName);
9098            }
9099
9100            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9101                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9102            }
9103
9104            if ((scanFlags & SCAN_BOOTING) == 0
9105                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9106                // Check all shared libraries and map to their actual file path.
9107                // We only do this here for apps not on a system dir, because those
9108                // are the only ones that can fail an install due to this.  We
9109                // will take care of the system apps by updating all of their
9110                // library paths after the scan is done. Also during the initial
9111                // scan don't update any libs as we do this wholesale after all
9112                // apps are scanned to avoid dependency based scanning.
9113                updateSharedLibrariesLPr(pkg, null);
9114            }
9115
9116            if (mFoundPolicyFile) {
9117                SELinuxMMAC.assignSeinfoValue(pkg);
9118            }
9119
9120            pkg.applicationInfo.uid = pkgSetting.appId;
9121            pkg.mExtras = pkgSetting;
9122
9123
9124            // Static shared libs have same package with different versions where
9125            // we internally use a synthetic package name to allow multiple versions
9126            // of the same package, therefore we need to compare signatures against
9127            // the package setting for the latest library version.
9128            PackageSetting signatureCheckPs = pkgSetting;
9129            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9130                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9131                if (libraryEntry != null) {
9132                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9133                }
9134            }
9135
9136            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9137                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9138                    // We just determined the app is signed correctly, so bring
9139                    // over the latest parsed certs.
9140                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9141                } else {
9142                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9143                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9144                                "Package " + pkg.packageName + " upgrade keys do not match the "
9145                                + "previously installed version");
9146                    } else {
9147                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9148                        String msg = "System package " + pkg.packageName
9149                                + " signature changed; retaining data.";
9150                        reportSettingsProblem(Log.WARN, msg);
9151                    }
9152                }
9153            } else {
9154                try {
9155                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9156                    verifySignaturesLP(signatureCheckPs, pkg);
9157                    // We just determined the app is signed correctly, so bring
9158                    // over the latest parsed certs.
9159                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9160                } catch (PackageManagerException e) {
9161                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9162                        throw e;
9163                    }
9164                    // The signature has changed, but this package is in the system
9165                    // image...  let's recover!
9166                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9167                    // However...  if this package is part of a shared user, but it
9168                    // doesn't match the signature of the shared user, let's fail.
9169                    // What this means is that you can't change the signatures
9170                    // associated with an overall shared user, which doesn't seem all
9171                    // that unreasonable.
9172                    if (signatureCheckPs.sharedUser != null) {
9173                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9174                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9175                            throw new PackageManagerException(
9176                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9177                                    "Signature mismatch for shared user: "
9178                                            + pkgSetting.sharedUser);
9179                        }
9180                    }
9181                    // File a report about this.
9182                    String msg = "System package " + pkg.packageName
9183                            + " signature changed; retaining data.";
9184                    reportSettingsProblem(Log.WARN, msg);
9185                }
9186            }
9187
9188            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9189                // This package wants to adopt ownership of permissions from
9190                // another package.
9191                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9192                    final String origName = pkg.mAdoptPermissions.get(i);
9193                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9194                    if (orig != null) {
9195                        if (verifyPackageUpdateLPr(orig, pkg)) {
9196                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9197                                    + pkg.packageName);
9198                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9199                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9200                        }
9201                    }
9202                }
9203            }
9204        }
9205
9206        pkg.applicationInfo.processName = fixProcessName(
9207                pkg.applicationInfo.packageName,
9208                pkg.applicationInfo.processName);
9209
9210        if (pkg != mPlatformPackage) {
9211            // Get all of our default paths setup
9212            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9213        }
9214
9215        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9216
9217        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9218            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9219                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9220                derivePackageAbi(
9221                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9222                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9223
9224                // Some system apps still use directory structure for native libraries
9225                // in which case we might end up not detecting abi solely based on apk
9226                // structure. Try to detect abi based on directory structure.
9227                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9228                        pkg.applicationInfo.primaryCpuAbi == null) {
9229                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9230                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9231                }
9232            } else {
9233                // This is not a first boot or an upgrade, don't bother deriving the
9234                // ABI during the scan. Instead, trust the value that was stored in the
9235                // package setting.
9236                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9237                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9238
9239                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9240
9241                if (DEBUG_ABI_SELECTION) {
9242                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9243                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9244                        pkg.applicationInfo.secondaryCpuAbi);
9245                }
9246            }
9247        } else {
9248            if ((scanFlags & SCAN_MOVE) != 0) {
9249                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9250                // but we already have this packages package info in the PackageSetting. We just
9251                // use that and derive the native library path based on the new codepath.
9252                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9253                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9254            }
9255
9256            // Set native library paths again. For moves, the path will be updated based on the
9257            // ABIs we've determined above. For non-moves, the path will be updated based on the
9258            // ABIs we determined during compilation, but the path will depend on the final
9259            // package path (after the rename away from the stage path).
9260            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9261        }
9262
9263        // This is a special case for the "system" package, where the ABI is
9264        // dictated by the zygote configuration (and init.rc). We should keep track
9265        // of this ABI so that we can deal with "normal" applications that run under
9266        // the same UID correctly.
9267        if (mPlatformPackage == pkg) {
9268            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9269                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9270        }
9271
9272        // If there's a mismatch between the abi-override in the package setting
9273        // and the abiOverride specified for the install. Warn about this because we
9274        // would've already compiled the app without taking the package setting into
9275        // account.
9276        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9277            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9278                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9279                        " for package " + pkg.packageName);
9280            }
9281        }
9282
9283        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9284        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9285        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9286
9287        // Copy the derived override back to the parsed package, so that we can
9288        // update the package settings accordingly.
9289        pkg.cpuAbiOverride = cpuAbiOverride;
9290
9291        if (DEBUG_ABI_SELECTION) {
9292            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9293                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9294                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9295        }
9296
9297        // Push the derived path down into PackageSettings so we know what to
9298        // clean up at uninstall time.
9299        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9300
9301        if (DEBUG_ABI_SELECTION) {
9302            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9303                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9304                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9305        }
9306
9307        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9308        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9309            // We don't do this here during boot because we can do it all
9310            // at once after scanning all existing packages.
9311            //
9312            // We also do this *before* we perform dexopt on this package, so that
9313            // we can avoid redundant dexopts, and also to make sure we've got the
9314            // code and package path correct.
9315            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9316        }
9317
9318        if (mFactoryTest && pkg.requestedPermissions.contains(
9319                android.Manifest.permission.FACTORY_TEST)) {
9320            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9321        }
9322
9323        if (isSystemApp(pkg)) {
9324            pkgSetting.isOrphaned = true;
9325        }
9326
9327        // Take care of first install / last update times.
9328        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9329        if (currentTime != 0) {
9330            if (pkgSetting.firstInstallTime == 0) {
9331                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9332            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9333                pkgSetting.lastUpdateTime = currentTime;
9334            }
9335        } else if (pkgSetting.firstInstallTime == 0) {
9336            // We need *something*.  Take time time stamp of the file.
9337            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9338        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9339            if (scanFileTime != pkgSetting.timeStamp) {
9340                // A package on the system image has changed; consider this
9341                // to be an update.
9342                pkgSetting.lastUpdateTime = scanFileTime;
9343            }
9344        }
9345        pkgSetting.setTimeStamp(scanFileTime);
9346
9347        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9348            if (nonMutatedPs != null) {
9349                synchronized (mPackages) {
9350                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9351                }
9352            }
9353        } else {
9354            // Modify state for the given package setting
9355            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9356                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9357            if (isEphemeral(pkg)) {
9358                final int userId = user == null ? 0 : user.getIdentifier();
9359                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9360            }
9361        }
9362        return pkg;
9363    }
9364
9365    /**
9366     * Applies policy to the parsed package based upon the given policy flags.
9367     * Ensures the package is in a good state.
9368     * <p>
9369     * Implementation detail: This method must NOT have any side effect. It would
9370     * ideally be static, but, it requires locks to read system state.
9371     */
9372    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9373        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9374            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9375            if (pkg.applicationInfo.isDirectBootAware()) {
9376                // we're direct boot aware; set for all components
9377                for (PackageParser.Service s : pkg.services) {
9378                    s.info.encryptionAware = s.info.directBootAware = true;
9379                }
9380                for (PackageParser.Provider p : pkg.providers) {
9381                    p.info.encryptionAware = p.info.directBootAware = true;
9382                }
9383                for (PackageParser.Activity a : pkg.activities) {
9384                    a.info.encryptionAware = a.info.directBootAware = true;
9385                }
9386                for (PackageParser.Activity r : pkg.receivers) {
9387                    r.info.encryptionAware = r.info.directBootAware = true;
9388                }
9389            }
9390        } else {
9391            // Only allow system apps to be flagged as core apps.
9392            pkg.coreApp = false;
9393            // clear flags not applicable to regular apps
9394            pkg.applicationInfo.privateFlags &=
9395                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9396            pkg.applicationInfo.privateFlags &=
9397                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9398        }
9399        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9400
9401        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9402            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9403        }
9404
9405        if (!isSystemApp(pkg)) {
9406            // Only system apps can use these features.
9407            pkg.mOriginalPackages = null;
9408            pkg.mRealPackage = null;
9409            pkg.mAdoptPermissions = null;
9410        }
9411    }
9412
9413    /**
9414     * Asserts the parsed package is valid according to the given policy. If the
9415     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9416     * <p>
9417     * Implementation detail: This method must NOT have any side effects. It would
9418     * ideally be static, but, it requires locks to read system state.
9419     *
9420     * @throws PackageManagerException If the package fails any of the validation checks
9421     */
9422    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9423            throws PackageManagerException {
9424        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9425            assertCodePolicy(pkg);
9426        }
9427
9428        if (pkg.applicationInfo.getCodePath() == null ||
9429                pkg.applicationInfo.getResourcePath() == null) {
9430            // Bail out. The resource and code paths haven't been set.
9431            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9432                    "Code and resource paths haven't been set correctly");
9433        }
9434
9435        // Make sure we're not adding any bogus keyset info
9436        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9437        ksms.assertScannedPackageValid(pkg);
9438
9439        synchronized (mPackages) {
9440            // The special "android" package can only be defined once
9441            if (pkg.packageName.equals("android")) {
9442                if (mAndroidApplication != null) {
9443                    Slog.w(TAG, "*************************************************");
9444                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9445                    Slog.w(TAG, " codePath=" + pkg.codePath);
9446                    Slog.w(TAG, "*************************************************");
9447                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9448                            "Core android package being redefined.  Skipping.");
9449                }
9450            }
9451
9452            // A package name must be unique; don't allow duplicates
9453            if (mPackages.containsKey(pkg.packageName)) {
9454                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9455                        "Application package " + pkg.packageName
9456                        + " already installed.  Skipping duplicate.");
9457            }
9458
9459            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9460                // Static libs have a synthetic package name containing the version
9461                // but we still want the base name to be unique.
9462                if (mPackages.containsKey(pkg.manifestPackageName)) {
9463                    throw new PackageManagerException(
9464                            "Duplicate static shared lib provider package");
9465                }
9466
9467                // Static shared libraries should have at least O target SDK
9468                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9469                    throw new PackageManagerException(
9470                            "Packages declaring static-shared libs must target O SDK or higher");
9471                }
9472
9473                // Package declaring static a shared lib cannot be ephemeral
9474                if (pkg.applicationInfo.isInstantApp()) {
9475                    throw new PackageManagerException(
9476                            "Packages declaring static-shared libs cannot be ephemeral");
9477                }
9478
9479                // Package declaring static a shared lib cannot be renamed since the package
9480                // name is synthetic and apps can't code around package manager internals.
9481                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9482                    throw new PackageManagerException(
9483                            "Packages declaring static-shared libs cannot be renamed");
9484                }
9485
9486                // Package declaring static a shared lib cannot declare child packages
9487                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9488                    throw new PackageManagerException(
9489                            "Packages declaring static-shared libs cannot have child packages");
9490                }
9491
9492                // Package declaring static a shared lib cannot declare dynamic libs
9493                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9494                    throw new PackageManagerException(
9495                            "Packages declaring static-shared libs cannot declare dynamic libs");
9496                }
9497
9498                // Package declaring static a shared lib cannot declare shared users
9499                if (pkg.mSharedUserId != null) {
9500                    throw new PackageManagerException(
9501                            "Packages declaring static-shared libs cannot declare shared users");
9502                }
9503
9504                // Static shared libs cannot declare activities
9505                if (!pkg.activities.isEmpty()) {
9506                    throw new PackageManagerException(
9507                            "Static shared libs cannot declare activities");
9508                }
9509
9510                // Static shared libs cannot declare services
9511                if (!pkg.services.isEmpty()) {
9512                    throw new PackageManagerException(
9513                            "Static shared libs cannot declare services");
9514                }
9515
9516                // Static shared libs cannot declare providers
9517                if (!pkg.providers.isEmpty()) {
9518                    throw new PackageManagerException(
9519                            "Static shared libs cannot declare content providers");
9520                }
9521
9522                // Static shared libs cannot declare receivers
9523                if (!pkg.receivers.isEmpty()) {
9524                    throw new PackageManagerException(
9525                            "Static shared libs cannot declare broadcast receivers");
9526                }
9527
9528                // Static shared libs cannot declare permission groups
9529                if (!pkg.permissionGroups.isEmpty()) {
9530                    throw new PackageManagerException(
9531                            "Static shared libs cannot declare permission groups");
9532                }
9533
9534                // Static shared libs cannot declare permissions
9535                if (!pkg.permissions.isEmpty()) {
9536                    throw new PackageManagerException(
9537                            "Static shared libs cannot declare permissions");
9538                }
9539
9540                // Static shared libs cannot declare protected broadcasts
9541                if (pkg.protectedBroadcasts != null) {
9542                    throw new PackageManagerException(
9543                            "Static shared libs cannot declare protected broadcasts");
9544                }
9545
9546                // Static shared libs cannot be overlay targets
9547                if (pkg.mOverlayTarget != null) {
9548                    throw new PackageManagerException(
9549                            "Static shared libs cannot be overlay targets");
9550                }
9551
9552                // The version codes must be ordered as lib versions
9553                int minVersionCode = Integer.MIN_VALUE;
9554                int maxVersionCode = Integer.MAX_VALUE;
9555
9556                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9557                        pkg.staticSharedLibName);
9558                if (versionedLib != null) {
9559                    final int versionCount = versionedLib.size();
9560                    for (int i = 0; i < versionCount; i++) {
9561                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9562                        // TODO: We will change version code to long, so in the new API it is long
9563                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9564                                .getVersionCode();
9565                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9566                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9567                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9568                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9569                        } else {
9570                            minVersionCode = maxVersionCode = libVersionCode;
9571                            break;
9572                        }
9573                    }
9574                }
9575                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9576                    throw new PackageManagerException("Static shared"
9577                            + " lib version codes must be ordered as lib versions");
9578                }
9579            }
9580
9581            // Only privileged apps and updated privileged apps can add child packages.
9582            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9583                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9584                    throw new PackageManagerException("Only privileged apps can add child "
9585                            + "packages. Ignoring package " + pkg.packageName);
9586                }
9587                final int childCount = pkg.childPackages.size();
9588                for (int i = 0; i < childCount; i++) {
9589                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9590                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9591                            childPkg.packageName)) {
9592                        throw new PackageManagerException("Can't override child of "
9593                                + "another disabled app. Ignoring package " + pkg.packageName);
9594                    }
9595                }
9596            }
9597
9598            // If we're only installing presumed-existing packages, require that the
9599            // scanned APK is both already known and at the path previously established
9600            // for it.  Previously unknown packages we pick up normally, but if we have an
9601            // a priori expectation about this package's install presence, enforce it.
9602            // With a singular exception for new system packages. When an OTA contains
9603            // a new system package, we allow the codepath to change from a system location
9604            // to the user-installed location. If we don't allow this change, any newer,
9605            // user-installed version of the application will be ignored.
9606            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9607                if (mExpectingBetter.containsKey(pkg.packageName)) {
9608                    logCriticalInfo(Log.WARN,
9609                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9610                } else {
9611                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9612                    if (known != null) {
9613                        if (DEBUG_PACKAGE_SCANNING) {
9614                            Log.d(TAG, "Examining " + pkg.codePath
9615                                    + " and requiring known paths " + known.codePathString
9616                                    + " & " + known.resourcePathString);
9617                        }
9618                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9619                                || !pkg.applicationInfo.getResourcePath().equals(
9620                                        known.resourcePathString)) {
9621                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9622                                    "Application package " + pkg.packageName
9623                                    + " found at " + pkg.applicationInfo.getCodePath()
9624                                    + " but expected at " + known.codePathString
9625                                    + "; ignoring.");
9626                        }
9627                    }
9628                }
9629            }
9630
9631            // Verify that this new package doesn't have any content providers
9632            // that conflict with existing packages.  Only do this if the
9633            // package isn't already installed, since we don't want to break
9634            // things that are installed.
9635            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9636                final int N = pkg.providers.size();
9637                int i;
9638                for (i=0; i<N; i++) {
9639                    PackageParser.Provider p = pkg.providers.get(i);
9640                    if (p.info.authority != null) {
9641                        String names[] = p.info.authority.split(";");
9642                        for (int j = 0; j < names.length; j++) {
9643                            if (mProvidersByAuthority.containsKey(names[j])) {
9644                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9645                                final String otherPackageName =
9646                                        ((other != null && other.getComponentName() != null) ?
9647                                                other.getComponentName().getPackageName() : "?");
9648                                throw new PackageManagerException(
9649                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9650                                        "Can't install because provider name " + names[j]
9651                                                + " (in package " + pkg.applicationInfo.packageName
9652                                                + ") is already used by " + otherPackageName);
9653                            }
9654                        }
9655                    }
9656                }
9657            }
9658        }
9659    }
9660
9661    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9662            int type, String declaringPackageName, int declaringVersionCode) {
9663        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9664        if (versionedLib == null) {
9665            versionedLib = new SparseArray<>();
9666            mSharedLibraries.put(name, versionedLib);
9667            if (type == SharedLibraryInfo.TYPE_STATIC) {
9668                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9669            }
9670        } else if (versionedLib.indexOfKey(version) >= 0) {
9671            return false;
9672        }
9673        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9674                version, type, declaringPackageName, declaringVersionCode);
9675        versionedLib.put(version, libEntry);
9676        return true;
9677    }
9678
9679    private boolean removeSharedLibraryLPw(String name, int version) {
9680        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9681        if (versionedLib == null) {
9682            return false;
9683        }
9684        final int libIdx = versionedLib.indexOfKey(version);
9685        if (libIdx < 0) {
9686            return false;
9687        }
9688        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9689        versionedLib.remove(version);
9690        if (versionedLib.size() <= 0) {
9691            mSharedLibraries.remove(name);
9692            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9693                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9694                        .getPackageName());
9695            }
9696        }
9697        return true;
9698    }
9699
9700    /**
9701     * Adds a scanned package to the system. When this method is finished, the package will
9702     * be available for query, resolution, etc...
9703     */
9704    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9705            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9706        final String pkgName = pkg.packageName;
9707        if (mCustomResolverComponentName != null &&
9708                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9709            setUpCustomResolverActivity(pkg);
9710        }
9711
9712        if (pkg.packageName.equals("android")) {
9713            synchronized (mPackages) {
9714                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9715                    // Set up information for our fall-back user intent resolution activity.
9716                    mPlatformPackage = pkg;
9717                    pkg.mVersionCode = mSdkVersion;
9718                    mAndroidApplication = pkg.applicationInfo;
9719
9720                    if (!mResolverReplaced) {
9721                        mResolveActivity.applicationInfo = mAndroidApplication;
9722                        mResolveActivity.name = ResolverActivity.class.getName();
9723                        mResolveActivity.packageName = mAndroidApplication.packageName;
9724                        mResolveActivity.processName = "system:ui";
9725                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9726                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9727                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9728                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9729                        mResolveActivity.exported = true;
9730                        mResolveActivity.enabled = true;
9731                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9732                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9733                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9734                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9735                                | ActivityInfo.CONFIG_ORIENTATION
9736                                | ActivityInfo.CONFIG_KEYBOARD
9737                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9738                        mResolveInfo.activityInfo = mResolveActivity;
9739                        mResolveInfo.priority = 0;
9740                        mResolveInfo.preferredOrder = 0;
9741                        mResolveInfo.match = 0;
9742                        mResolveComponentName = new ComponentName(
9743                                mAndroidApplication.packageName, mResolveActivity.name);
9744                    }
9745                }
9746            }
9747        }
9748
9749        ArrayList<PackageParser.Package> clientLibPkgs = null;
9750        // writer
9751        synchronized (mPackages) {
9752            boolean hasStaticSharedLibs = false;
9753
9754            // Any app can add new static shared libraries
9755            if (pkg.staticSharedLibName != null) {
9756                // Static shared libs don't allow renaming as they have synthetic package
9757                // names to allow install of multiple versions, so use name from manifest.
9758                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9759                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9760                        pkg.manifestPackageName, pkg.mVersionCode)) {
9761                    hasStaticSharedLibs = true;
9762                } else {
9763                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9764                                + pkg.staticSharedLibName + " already exists; skipping");
9765                }
9766                // Static shared libs cannot be updated once installed since they
9767                // use synthetic package name which includes the version code, so
9768                // not need to update other packages's shared lib dependencies.
9769            }
9770
9771            if (!hasStaticSharedLibs
9772                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9773                // Only system apps can add new dynamic shared libraries.
9774                if (pkg.libraryNames != null) {
9775                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9776                        String name = pkg.libraryNames.get(i);
9777                        boolean allowed = false;
9778                        if (pkg.isUpdatedSystemApp()) {
9779                            // New library entries can only be added through the
9780                            // system image.  This is important to get rid of a lot
9781                            // of nasty edge cases: for example if we allowed a non-
9782                            // system update of the app to add a library, then uninstalling
9783                            // the update would make the library go away, and assumptions
9784                            // we made such as through app install filtering would now
9785                            // have allowed apps on the device which aren't compatible
9786                            // with it.  Better to just have the restriction here, be
9787                            // conservative, and create many fewer cases that can negatively
9788                            // impact the user experience.
9789                            final PackageSetting sysPs = mSettings
9790                                    .getDisabledSystemPkgLPr(pkg.packageName);
9791                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9792                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9793                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9794                                        allowed = true;
9795                                        break;
9796                                    }
9797                                }
9798                            }
9799                        } else {
9800                            allowed = true;
9801                        }
9802                        if (allowed) {
9803                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9804                                    SharedLibraryInfo.VERSION_UNDEFINED,
9805                                    SharedLibraryInfo.TYPE_DYNAMIC,
9806                                    pkg.packageName, pkg.mVersionCode)) {
9807                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9808                                        + name + " already exists; skipping");
9809                            }
9810                        } else {
9811                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9812                                    + name + " that is not declared on system image; skipping");
9813                        }
9814                    }
9815
9816                    if ((scanFlags & SCAN_BOOTING) == 0) {
9817                        // If we are not booting, we need to update any applications
9818                        // that are clients of our shared library.  If we are booting,
9819                        // this will all be done once the scan is complete.
9820                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9821                    }
9822                }
9823            }
9824        }
9825
9826        if ((scanFlags & SCAN_BOOTING) != 0) {
9827            // No apps can run during boot scan, so they don't need to be frozen
9828        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9829            // Caller asked to not kill app, so it's probably not frozen
9830        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9831            // Caller asked us to ignore frozen check for some reason; they
9832            // probably didn't know the package name
9833        } else {
9834            // We're doing major surgery on this package, so it better be frozen
9835            // right now to keep it from launching
9836            checkPackageFrozen(pkgName);
9837        }
9838
9839        // Also need to kill any apps that are dependent on the library.
9840        if (clientLibPkgs != null) {
9841            for (int i=0; i<clientLibPkgs.size(); i++) {
9842                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9843                killApplication(clientPkg.applicationInfo.packageName,
9844                        clientPkg.applicationInfo.uid, "update lib");
9845            }
9846        }
9847
9848        // writer
9849        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9850
9851        boolean createIdmapFailed = false;
9852        synchronized (mPackages) {
9853            // We don't expect installation to fail beyond this point
9854
9855            if (pkgSetting.pkg != null) {
9856                // Note that |user| might be null during the initial boot scan. If a codePath
9857                // for an app has changed during a boot scan, it's due to an app update that's
9858                // part of the system partition and marker changes must be applied to all users.
9859                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9860                final int[] userIds = resolveUserIds(userId);
9861                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9862            }
9863
9864            // Add the new setting to mSettings
9865            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9866            // Add the new setting to mPackages
9867            mPackages.put(pkg.applicationInfo.packageName, pkg);
9868            // Make sure we don't accidentally delete its data.
9869            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9870            while (iter.hasNext()) {
9871                PackageCleanItem item = iter.next();
9872                if (pkgName.equals(item.packageName)) {
9873                    iter.remove();
9874                }
9875            }
9876
9877            // Add the package's KeySets to the global KeySetManagerService
9878            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9879            ksms.addScannedPackageLPw(pkg);
9880
9881            int N = pkg.providers.size();
9882            StringBuilder r = null;
9883            int i;
9884            for (i=0; i<N; i++) {
9885                PackageParser.Provider p = pkg.providers.get(i);
9886                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9887                        p.info.processName);
9888                mProviders.addProvider(p);
9889                p.syncable = p.info.isSyncable;
9890                if (p.info.authority != null) {
9891                    String names[] = p.info.authority.split(";");
9892                    p.info.authority = null;
9893                    for (int j = 0; j < names.length; j++) {
9894                        if (j == 1 && p.syncable) {
9895                            // We only want the first authority for a provider to possibly be
9896                            // syncable, so if we already added this provider using a different
9897                            // authority clear the syncable flag. We copy the provider before
9898                            // changing it because the mProviders object contains a reference
9899                            // to a provider that we don't want to change.
9900                            // Only do this for the second authority since the resulting provider
9901                            // object can be the same for all future authorities for this provider.
9902                            p = new PackageParser.Provider(p);
9903                            p.syncable = false;
9904                        }
9905                        if (!mProvidersByAuthority.containsKey(names[j])) {
9906                            mProvidersByAuthority.put(names[j], p);
9907                            if (p.info.authority == null) {
9908                                p.info.authority = names[j];
9909                            } else {
9910                                p.info.authority = p.info.authority + ";" + names[j];
9911                            }
9912                            if (DEBUG_PACKAGE_SCANNING) {
9913                                if (chatty)
9914                                    Log.d(TAG, "Registered content provider: " + names[j]
9915                                            + ", className = " + p.info.name + ", isSyncable = "
9916                                            + p.info.isSyncable);
9917                            }
9918                        } else {
9919                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9920                            Slog.w(TAG, "Skipping provider name " + names[j] +
9921                                    " (in package " + pkg.applicationInfo.packageName +
9922                                    "): name already used by "
9923                                    + ((other != null && other.getComponentName() != null)
9924                                            ? other.getComponentName().getPackageName() : "?"));
9925                        }
9926                    }
9927                }
9928                if (chatty) {
9929                    if (r == null) {
9930                        r = new StringBuilder(256);
9931                    } else {
9932                        r.append(' ');
9933                    }
9934                    r.append(p.info.name);
9935                }
9936            }
9937            if (r != null) {
9938                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9939            }
9940
9941            N = pkg.services.size();
9942            r = null;
9943            for (i=0; i<N; i++) {
9944                PackageParser.Service s = pkg.services.get(i);
9945                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9946                        s.info.processName);
9947                mServices.addService(s);
9948                if (chatty) {
9949                    if (r == null) {
9950                        r = new StringBuilder(256);
9951                    } else {
9952                        r.append(' ');
9953                    }
9954                    r.append(s.info.name);
9955                }
9956            }
9957            if (r != null) {
9958                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9959            }
9960
9961            N = pkg.receivers.size();
9962            r = null;
9963            for (i=0; i<N; i++) {
9964                PackageParser.Activity a = pkg.receivers.get(i);
9965                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9966                        a.info.processName);
9967                mReceivers.addActivity(a, "receiver");
9968                if (chatty) {
9969                    if (r == null) {
9970                        r = new StringBuilder(256);
9971                    } else {
9972                        r.append(' ');
9973                    }
9974                    r.append(a.info.name);
9975                }
9976            }
9977            if (r != null) {
9978                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9979            }
9980
9981            N = pkg.activities.size();
9982            r = null;
9983            for (i=0; i<N; i++) {
9984                PackageParser.Activity a = pkg.activities.get(i);
9985                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9986                        a.info.processName);
9987                mActivities.addActivity(a, "activity");
9988                if (chatty) {
9989                    if (r == null) {
9990                        r = new StringBuilder(256);
9991                    } else {
9992                        r.append(' ');
9993                    }
9994                    r.append(a.info.name);
9995                }
9996            }
9997            if (r != null) {
9998                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9999            }
10000
10001            N = pkg.permissionGroups.size();
10002            r = null;
10003            for (i=0; i<N; i++) {
10004                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10005                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10006                final String curPackageName = cur == null ? null : cur.info.packageName;
10007                // Dont allow ephemeral apps to define new permission groups.
10008                if (pkg.applicationInfo.isInstantApp()) {
10009                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10010                            + pg.info.packageName
10011                            + " ignored: ephemeral apps cannot define new permission groups.");
10012                    continue;
10013                }
10014                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10015                if (cur == null || isPackageUpdate) {
10016                    mPermissionGroups.put(pg.info.name, pg);
10017                    if (chatty) {
10018                        if (r == null) {
10019                            r = new StringBuilder(256);
10020                        } else {
10021                            r.append(' ');
10022                        }
10023                        if (isPackageUpdate) {
10024                            r.append("UPD:");
10025                        }
10026                        r.append(pg.info.name);
10027                    }
10028                } else {
10029                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10030                            + pg.info.packageName + " ignored: original from "
10031                            + cur.info.packageName);
10032                    if (chatty) {
10033                        if (r == null) {
10034                            r = new StringBuilder(256);
10035                        } else {
10036                            r.append(' ');
10037                        }
10038                        r.append("DUP:");
10039                        r.append(pg.info.name);
10040                    }
10041                }
10042            }
10043            if (r != null) {
10044                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10045            }
10046
10047            N = pkg.permissions.size();
10048            r = null;
10049            for (i=0; i<N; i++) {
10050                PackageParser.Permission p = pkg.permissions.get(i);
10051
10052                // Dont allow ephemeral apps to define new permissions.
10053                if (pkg.applicationInfo.isInstantApp()) {
10054                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10055                            + p.info.packageName
10056                            + " ignored: ephemeral apps cannot define new permissions.");
10057                    continue;
10058                }
10059
10060                // Assume by default that we did not install this permission into the system.
10061                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10062
10063                // Now that permission groups have a special meaning, we ignore permission
10064                // groups for legacy apps to prevent unexpected behavior. In particular,
10065                // permissions for one app being granted to someone just becase they happen
10066                // to be in a group defined by another app (before this had no implications).
10067                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10068                    p.group = mPermissionGroups.get(p.info.group);
10069                    // Warn for a permission in an unknown group.
10070                    if (p.info.group != null && p.group == null) {
10071                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10072                                + p.info.packageName + " in an unknown group " + p.info.group);
10073                    }
10074                }
10075
10076                ArrayMap<String, BasePermission> permissionMap =
10077                        p.tree ? mSettings.mPermissionTrees
10078                                : mSettings.mPermissions;
10079                BasePermission bp = permissionMap.get(p.info.name);
10080
10081                // Allow system apps to redefine non-system permissions
10082                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10083                    final boolean currentOwnerIsSystem = (bp.perm != null
10084                            && isSystemApp(bp.perm.owner));
10085                    if (isSystemApp(p.owner)) {
10086                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10087                            // It's a built-in permission and no owner, take ownership now
10088                            bp.packageSetting = pkgSetting;
10089                            bp.perm = p;
10090                            bp.uid = pkg.applicationInfo.uid;
10091                            bp.sourcePackage = p.info.packageName;
10092                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10093                        } else if (!currentOwnerIsSystem) {
10094                            String msg = "New decl " + p.owner + " of permission  "
10095                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10096                            reportSettingsProblem(Log.WARN, msg);
10097                            bp = null;
10098                        }
10099                    }
10100                }
10101
10102                if (bp == null) {
10103                    bp = new BasePermission(p.info.name, p.info.packageName,
10104                            BasePermission.TYPE_NORMAL);
10105                    permissionMap.put(p.info.name, bp);
10106                }
10107
10108                if (bp.perm == null) {
10109                    if (bp.sourcePackage == null
10110                            || bp.sourcePackage.equals(p.info.packageName)) {
10111                        BasePermission tree = findPermissionTreeLP(p.info.name);
10112                        if (tree == null
10113                                || tree.sourcePackage.equals(p.info.packageName)) {
10114                            bp.packageSetting = pkgSetting;
10115                            bp.perm = p;
10116                            bp.uid = pkg.applicationInfo.uid;
10117                            bp.sourcePackage = p.info.packageName;
10118                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10119                            if (chatty) {
10120                                if (r == null) {
10121                                    r = new StringBuilder(256);
10122                                } else {
10123                                    r.append(' ');
10124                                }
10125                                r.append(p.info.name);
10126                            }
10127                        } else {
10128                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10129                                    + p.info.packageName + " ignored: base tree "
10130                                    + tree.name + " is from package "
10131                                    + tree.sourcePackage);
10132                        }
10133                    } else {
10134                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10135                                + p.info.packageName + " ignored: original from "
10136                                + bp.sourcePackage);
10137                    }
10138                } else if (chatty) {
10139                    if (r == null) {
10140                        r = new StringBuilder(256);
10141                    } else {
10142                        r.append(' ');
10143                    }
10144                    r.append("DUP:");
10145                    r.append(p.info.name);
10146                }
10147                if (bp.perm == p) {
10148                    bp.protectionLevel = p.info.protectionLevel;
10149                }
10150            }
10151
10152            if (r != null) {
10153                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10154            }
10155
10156            N = pkg.instrumentation.size();
10157            r = null;
10158            for (i=0; i<N; i++) {
10159                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10160                a.info.packageName = pkg.applicationInfo.packageName;
10161                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10162                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10163                a.info.splitNames = pkg.splitNames;
10164                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10165                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10166                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10167                a.info.dataDir = pkg.applicationInfo.dataDir;
10168                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10169                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10170                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10171                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10172                mInstrumentation.put(a.getComponentName(), a);
10173                if (chatty) {
10174                    if (r == null) {
10175                        r = new StringBuilder(256);
10176                    } else {
10177                        r.append(' ');
10178                    }
10179                    r.append(a.info.name);
10180                }
10181            }
10182            if (r != null) {
10183                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10184            }
10185
10186            if (pkg.protectedBroadcasts != null) {
10187                N = pkg.protectedBroadcasts.size();
10188                for (i=0; i<N; i++) {
10189                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10190                }
10191            }
10192
10193            // Create idmap files for pairs of (packages, overlay packages).
10194            // Note: "android", ie framework-res.apk, is handled by native layers.
10195            if (pkg.mOverlayTarget != null) {
10196                // This is an overlay package.
10197                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10198                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10199                        mOverlays.put(pkg.mOverlayTarget,
10200                                new ArrayMap<String, PackageParser.Package>());
10201                    }
10202                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10203                    map.put(pkg.packageName, pkg);
10204                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10205                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10206                        createIdmapFailed = true;
10207                    }
10208                }
10209            } else if (mOverlays.containsKey(pkg.packageName) &&
10210                    !pkg.packageName.equals("android")) {
10211                // This is a regular package, with one or more known overlay packages.
10212                createIdmapsForPackageLI(pkg);
10213            }
10214        }
10215
10216        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10217
10218        if (createIdmapFailed) {
10219            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10220                    "scanPackageLI failed to createIdmap");
10221        }
10222    }
10223
10224    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10225            PackageParser.Package update, int[] userIds) {
10226        if (existing.applicationInfo == null || update.applicationInfo == null) {
10227            // This isn't due to an app installation.
10228            return;
10229        }
10230
10231        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10232        final File newCodePath = new File(update.applicationInfo.getCodePath());
10233
10234        // The codePath hasn't changed, so there's nothing for us to do.
10235        if (Objects.equals(oldCodePath, newCodePath)) {
10236            return;
10237        }
10238
10239        File canonicalNewCodePath;
10240        try {
10241            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10242        } catch (IOException e) {
10243            Slog.w(TAG, "Failed to get canonical path.", e);
10244            return;
10245        }
10246
10247        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10248        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10249        // that the last component of the path (i.e, the name) doesn't need canonicalization
10250        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10251        // but may change in the future. Hopefully this function won't exist at that point.
10252        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10253                oldCodePath.getName());
10254
10255        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10256        // with "@".
10257        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10258        if (!oldMarkerPrefix.endsWith("@")) {
10259            oldMarkerPrefix += "@";
10260        }
10261        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10262        if (!newMarkerPrefix.endsWith("@")) {
10263            newMarkerPrefix += "@";
10264        }
10265
10266        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10267        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10268        for (String updatedPath : updatedPaths) {
10269            String updatedPathName = new File(updatedPath).getName();
10270            markerSuffixes.add(updatedPathName.replace('/', '@'));
10271        }
10272
10273        for (int userId : userIds) {
10274            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10275
10276            for (String markerSuffix : markerSuffixes) {
10277                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10278                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10279                if (oldForeignUseMark.exists()) {
10280                    try {
10281                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10282                                newForeignUseMark.getAbsolutePath());
10283                    } catch (ErrnoException e) {
10284                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10285                        oldForeignUseMark.delete();
10286                    }
10287                }
10288            }
10289        }
10290    }
10291
10292    /**
10293     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10294     * is derived purely on the basis of the contents of {@code scanFile} and
10295     * {@code cpuAbiOverride}.
10296     *
10297     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10298     */
10299    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10300                                 String cpuAbiOverride, boolean extractLibs,
10301                                 File appLib32InstallDir)
10302            throws PackageManagerException {
10303        // Give ourselves some initial paths; we'll come back for another
10304        // pass once we've determined ABI below.
10305        setNativeLibraryPaths(pkg, appLib32InstallDir);
10306
10307        // We would never need to extract libs for forward-locked and external packages,
10308        // since the container service will do it for us. We shouldn't attempt to
10309        // extract libs from system app when it was not updated.
10310        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10311                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10312            extractLibs = false;
10313        }
10314
10315        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10316        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10317
10318        NativeLibraryHelper.Handle handle = null;
10319        try {
10320            handle = NativeLibraryHelper.Handle.create(pkg);
10321            // TODO(multiArch): This can be null for apps that didn't go through the
10322            // usual installation process. We can calculate it again, like we
10323            // do during install time.
10324            //
10325            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10326            // unnecessary.
10327            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10328
10329            // Null out the abis so that they can be recalculated.
10330            pkg.applicationInfo.primaryCpuAbi = null;
10331            pkg.applicationInfo.secondaryCpuAbi = null;
10332            if (isMultiArch(pkg.applicationInfo)) {
10333                // Warn if we've set an abiOverride for multi-lib packages..
10334                // By definition, we need to copy both 32 and 64 bit libraries for
10335                // such packages.
10336                if (pkg.cpuAbiOverride != null
10337                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10338                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10339                }
10340
10341                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10342                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10343                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10344                    if (extractLibs) {
10345                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10346                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10347                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10348                                useIsaSpecificSubdirs);
10349                    } else {
10350                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10351                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10352                    }
10353                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10354                }
10355
10356                maybeThrowExceptionForMultiArchCopy(
10357                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10358
10359                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10360                    if (extractLibs) {
10361                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10362                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10363                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10364                                useIsaSpecificSubdirs);
10365                    } else {
10366                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10367                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10368                    }
10369                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10370                }
10371
10372                maybeThrowExceptionForMultiArchCopy(
10373                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10374
10375                if (abi64 >= 0) {
10376                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10377                }
10378
10379                if (abi32 >= 0) {
10380                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10381                    if (abi64 >= 0) {
10382                        if (pkg.use32bitAbi) {
10383                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10384                            pkg.applicationInfo.primaryCpuAbi = abi;
10385                        } else {
10386                            pkg.applicationInfo.secondaryCpuAbi = abi;
10387                        }
10388                    } else {
10389                        pkg.applicationInfo.primaryCpuAbi = abi;
10390                    }
10391                }
10392
10393            } else {
10394                String[] abiList = (cpuAbiOverride != null) ?
10395                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10396
10397                // Enable gross and lame hacks for apps that are built with old
10398                // SDK tools. We must scan their APKs for renderscript bitcode and
10399                // not launch them if it's present. Don't bother checking on devices
10400                // that don't have 64 bit support.
10401                boolean needsRenderScriptOverride = false;
10402                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10403                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10404                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10405                    needsRenderScriptOverride = true;
10406                }
10407
10408                final int copyRet;
10409                if (extractLibs) {
10410                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10411                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10412                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10413                } else {
10414                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10415                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10416                }
10417                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10418
10419                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10420                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10421                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10422                }
10423
10424                if (copyRet >= 0) {
10425                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10426                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10427                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10428                } else if (needsRenderScriptOverride) {
10429                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10430                }
10431            }
10432        } catch (IOException ioe) {
10433            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10434        } finally {
10435            IoUtils.closeQuietly(handle);
10436        }
10437
10438        // Now that we've calculated the ABIs and determined if it's an internal app,
10439        // we will go ahead and populate the nativeLibraryPath.
10440        setNativeLibraryPaths(pkg, appLib32InstallDir);
10441    }
10442
10443    /**
10444     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10445     * i.e, so that all packages can be run inside a single process if required.
10446     *
10447     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10448     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10449     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10450     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10451     * updating a package that belongs to a shared user.
10452     *
10453     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10454     * adds unnecessary complexity.
10455     */
10456    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10457            PackageParser.Package scannedPackage) {
10458        String requiredInstructionSet = null;
10459        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10460            requiredInstructionSet = VMRuntime.getInstructionSet(
10461                     scannedPackage.applicationInfo.primaryCpuAbi);
10462        }
10463
10464        PackageSetting requirer = null;
10465        for (PackageSetting ps : packagesForUser) {
10466            // If packagesForUser contains scannedPackage, we skip it. This will happen
10467            // when scannedPackage is an update of an existing package. Without this check,
10468            // we will never be able to change the ABI of any package belonging to a shared
10469            // user, even if it's compatible with other packages.
10470            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10471                if (ps.primaryCpuAbiString == null) {
10472                    continue;
10473                }
10474
10475                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10476                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10477                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10478                    // this but there's not much we can do.
10479                    String errorMessage = "Instruction set mismatch, "
10480                            + ((requirer == null) ? "[caller]" : requirer)
10481                            + " requires " + requiredInstructionSet + " whereas " + ps
10482                            + " requires " + instructionSet;
10483                    Slog.w(TAG, errorMessage);
10484                }
10485
10486                if (requiredInstructionSet == null) {
10487                    requiredInstructionSet = instructionSet;
10488                    requirer = ps;
10489                }
10490            }
10491        }
10492
10493        if (requiredInstructionSet != null) {
10494            String adjustedAbi;
10495            if (requirer != null) {
10496                // requirer != null implies that either scannedPackage was null or that scannedPackage
10497                // did not require an ABI, in which case we have to adjust scannedPackage to match
10498                // the ABI of the set (which is the same as requirer's ABI)
10499                adjustedAbi = requirer.primaryCpuAbiString;
10500                if (scannedPackage != null) {
10501                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10502                }
10503            } else {
10504                // requirer == null implies that we're updating all ABIs in the set to
10505                // match scannedPackage.
10506                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10507            }
10508
10509            for (PackageSetting ps : packagesForUser) {
10510                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10511                    if (ps.primaryCpuAbiString != null) {
10512                        continue;
10513                    }
10514
10515                    ps.primaryCpuAbiString = adjustedAbi;
10516                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10517                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10518                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10519                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10520                                + " (requirer="
10521                                + (requirer == null ? "null" : requirer.pkg.packageName)
10522                                + ", scannedPackage="
10523                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10524                                + ")");
10525                        try {
10526                            mInstaller.rmdex(ps.codePathString,
10527                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10528                        } catch (InstallerException ignored) {
10529                        }
10530                    }
10531                }
10532            }
10533        }
10534    }
10535
10536    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10537        synchronized (mPackages) {
10538            mResolverReplaced = true;
10539            // Set up information for custom user intent resolution activity.
10540            mResolveActivity.applicationInfo = pkg.applicationInfo;
10541            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10542            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10543            mResolveActivity.processName = pkg.applicationInfo.packageName;
10544            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10545            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10546                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10547            mResolveActivity.theme = 0;
10548            mResolveActivity.exported = true;
10549            mResolveActivity.enabled = true;
10550            mResolveInfo.activityInfo = mResolveActivity;
10551            mResolveInfo.priority = 0;
10552            mResolveInfo.preferredOrder = 0;
10553            mResolveInfo.match = 0;
10554            mResolveComponentName = mCustomResolverComponentName;
10555            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10556                    mResolveComponentName);
10557        }
10558    }
10559
10560    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10561        if (installerComponent == null) {
10562            if (DEBUG_EPHEMERAL) {
10563                Slog.d(TAG, "Clear ephemeral installer activity");
10564            }
10565            mEphemeralInstallerActivity.applicationInfo = null;
10566            return;
10567        }
10568
10569        if (DEBUG_EPHEMERAL) {
10570            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10571        }
10572        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10573        // Set up information for ephemeral installer activity
10574        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10575        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10576        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10577        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10578        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10579        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10580                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10581        mEphemeralInstallerActivity.theme = 0;
10582        mEphemeralInstallerActivity.exported = true;
10583        mEphemeralInstallerActivity.enabled = true;
10584        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10585        mEphemeralInstallerInfo.priority = 0;
10586        mEphemeralInstallerInfo.preferredOrder = 1;
10587        mEphemeralInstallerInfo.isDefault = true;
10588        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10589                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10590    }
10591
10592    private static String calculateBundledApkRoot(final String codePathString) {
10593        final File codePath = new File(codePathString);
10594        final File codeRoot;
10595        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10596            codeRoot = Environment.getRootDirectory();
10597        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10598            codeRoot = Environment.getOemDirectory();
10599        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10600            codeRoot = Environment.getVendorDirectory();
10601        } else {
10602            // Unrecognized code path; take its top real segment as the apk root:
10603            // e.g. /something/app/blah.apk => /something
10604            try {
10605                File f = codePath.getCanonicalFile();
10606                File parent = f.getParentFile();    // non-null because codePath is a file
10607                File tmp;
10608                while ((tmp = parent.getParentFile()) != null) {
10609                    f = parent;
10610                    parent = tmp;
10611                }
10612                codeRoot = f;
10613                Slog.w(TAG, "Unrecognized code path "
10614                        + codePath + " - using " + codeRoot);
10615            } catch (IOException e) {
10616                // Can't canonicalize the code path -- shenanigans?
10617                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10618                return Environment.getRootDirectory().getPath();
10619            }
10620        }
10621        return codeRoot.getPath();
10622    }
10623
10624    /**
10625     * Derive and set the location of native libraries for the given package,
10626     * which varies depending on where and how the package was installed.
10627     */
10628    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10629        final ApplicationInfo info = pkg.applicationInfo;
10630        final String codePath = pkg.codePath;
10631        final File codeFile = new File(codePath);
10632        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10633        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10634
10635        info.nativeLibraryRootDir = null;
10636        info.nativeLibraryRootRequiresIsa = false;
10637        info.nativeLibraryDir = null;
10638        info.secondaryNativeLibraryDir = null;
10639
10640        if (isApkFile(codeFile)) {
10641            // Monolithic install
10642            if (bundledApp) {
10643                // If "/system/lib64/apkname" exists, assume that is the per-package
10644                // native library directory to use; otherwise use "/system/lib/apkname".
10645                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10646                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10647                        getPrimaryInstructionSet(info));
10648
10649                // This is a bundled system app so choose the path based on the ABI.
10650                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10651                // is just the default path.
10652                final String apkName = deriveCodePathName(codePath);
10653                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10654                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10655                        apkName).getAbsolutePath();
10656
10657                if (info.secondaryCpuAbi != null) {
10658                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10659                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10660                            secondaryLibDir, apkName).getAbsolutePath();
10661                }
10662            } else if (asecApp) {
10663                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10664                        .getAbsolutePath();
10665            } else {
10666                final String apkName = deriveCodePathName(codePath);
10667                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10668                        .getAbsolutePath();
10669            }
10670
10671            info.nativeLibraryRootRequiresIsa = false;
10672            info.nativeLibraryDir = info.nativeLibraryRootDir;
10673        } else {
10674            // Cluster install
10675            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10676            info.nativeLibraryRootRequiresIsa = true;
10677
10678            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10679                    getPrimaryInstructionSet(info)).getAbsolutePath();
10680
10681            if (info.secondaryCpuAbi != null) {
10682                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10683                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10684            }
10685        }
10686    }
10687
10688    /**
10689     * Calculate the abis and roots for a bundled app. These can uniquely
10690     * be determined from the contents of the system partition, i.e whether
10691     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10692     * of this information, and instead assume that the system was built
10693     * sensibly.
10694     */
10695    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10696                                           PackageSetting pkgSetting) {
10697        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10698
10699        // If "/system/lib64/apkname" exists, assume that is the per-package
10700        // native library directory to use; otherwise use "/system/lib/apkname".
10701        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10702        setBundledAppAbi(pkg, apkRoot, apkName);
10703        // pkgSetting might be null during rescan following uninstall of updates
10704        // to a bundled app, so accommodate that possibility.  The settings in
10705        // that case will be established later from the parsed package.
10706        //
10707        // If the settings aren't null, sync them up with what we've just derived.
10708        // note that apkRoot isn't stored in the package settings.
10709        if (pkgSetting != null) {
10710            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10711            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10712        }
10713    }
10714
10715    /**
10716     * Deduces the ABI of a bundled app and sets the relevant fields on the
10717     * parsed pkg object.
10718     *
10719     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10720     *        under which system libraries are installed.
10721     * @param apkName the name of the installed package.
10722     */
10723    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10724        final File codeFile = new File(pkg.codePath);
10725
10726        final boolean has64BitLibs;
10727        final boolean has32BitLibs;
10728        if (isApkFile(codeFile)) {
10729            // Monolithic install
10730            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10731            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10732        } else {
10733            // Cluster install
10734            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10735            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10736                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10737                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10738                has64BitLibs = (new File(rootDir, isa)).exists();
10739            } else {
10740                has64BitLibs = false;
10741            }
10742            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10743                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10744                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10745                has32BitLibs = (new File(rootDir, isa)).exists();
10746            } else {
10747                has32BitLibs = false;
10748            }
10749        }
10750
10751        if (has64BitLibs && !has32BitLibs) {
10752            // The package has 64 bit libs, but not 32 bit libs. Its primary
10753            // ABI should be 64 bit. We can safely assume here that the bundled
10754            // native libraries correspond to the most preferred ABI in the list.
10755
10756            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10757            pkg.applicationInfo.secondaryCpuAbi = null;
10758        } else if (has32BitLibs && !has64BitLibs) {
10759            // The package has 32 bit libs but not 64 bit libs. Its primary
10760            // ABI should be 32 bit.
10761
10762            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10763            pkg.applicationInfo.secondaryCpuAbi = null;
10764        } else if (has32BitLibs && has64BitLibs) {
10765            // The application has both 64 and 32 bit bundled libraries. We check
10766            // here that the app declares multiArch support, and warn if it doesn't.
10767            //
10768            // We will be lenient here and record both ABIs. The primary will be the
10769            // ABI that's higher on the list, i.e, a device that's configured to prefer
10770            // 64 bit apps will see a 64 bit primary ABI,
10771
10772            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10773                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10774            }
10775
10776            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10777                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10778                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10779            } else {
10780                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10781                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10782            }
10783        } else {
10784            pkg.applicationInfo.primaryCpuAbi = null;
10785            pkg.applicationInfo.secondaryCpuAbi = null;
10786        }
10787    }
10788
10789    private void killApplication(String pkgName, int appId, String reason) {
10790        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10791    }
10792
10793    private void killApplication(String pkgName, int appId, int userId, String reason) {
10794        // Request the ActivityManager to kill the process(only for existing packages)
10795        // so that we do not end up in a confused state while the user is still using the older
10796        // version of the application while the new one gets installed.
10797        final long token = Binder.clearCallingIdentity();
10798        try {
10799            IActivityManager am = ActivityManager.getService();
10800            if (am != null) {
10801                try {
10802                    am.killApplication(pkgName, appId, userId, reason);
10803                } catch (RemoteException e) {
10804                }
10805            }
10806        } finally {
10807            Binder.restoreCallingIdentity(token);
10808        }
10809    }
10810
10811    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10812        // Remove the parent package setting
10813        PackageSetting ps = (PackageSetting) pkg.mExtras;
10814        if (ps != null) {
10815            removePackageLI(ps, chatty);
10816        }
10817        // Remove the child package setting
10818        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10819        for (int i = 0; i < childCount; i++) {
10820            PackageParser.Package childPkg = pkg.childPackages.get(i);
10821            ps = (PackageSetting) childPkg.mExtras;
10822            if (ps != null) {
10823                removePackageLI(ps, chatty);
10824            }
10825        }
10826    }
10827
10828    void removePackageLI(PackageSetting ps, boolean chatty) {
10829        if (DEBUG_INSTALL) {
10830            if (chatty)
10831                Log.d(TAG, "Removing package " + ps.name);
10832        }
10833
10834        // writer
10835        synchronized (mPackages) {
10836            mPackages.remove(ps.name);
10837            final PackageParser.Package pkg = ps.pkg;
10838            if (pkg != null) {
10839                cleanPackageDataStructuresLILPw(pkg, chatty);
10840            }
10841        }
10842    }
10843
10844    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10845        if (DEBUG_INSTALL) {
10846            if (chatty)
10847                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10848        }
10849
10850        // writer
10851        synchronized (mPackages) {
10852            // Remove the parent package
10853            mPackages.remove(pkg.applicationInfo.packageName);
10854            cleanPackageDataStructuresLILPw(pkg, chatty);
10855
10856            // Remove the child packages
10857            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10858            for (int i = 0; i < childCount; i++) {
10859                PackageParser.Package childPkg = pkg.childPackages.get(i);
10860                mPackages.remove(childPkg.applicationInfo.packageName);
10861                cleanPackageDataStructuresLILPw(childPkg, chatty);
10862            }
10863        }
10864    }
10865
10866    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10867        int N = pkg.providers.size();
10868        StringBuilder r = null;
10869        int i;
10870        for (i=0; i<N; i++) {
10871            PackageParser.Provider p = pkg.providers.get(i);
10872            mProviders.removeProvider(p);
10873            if (p.info.authority == null) {
10874
10875                /* There was another ContentProvider with this authority when
10876                 * this app was installed so this authority is null,
10877                 * Ignore it as we don't have to unregister the provider.
10878                 */
10879                continue;
10880            }
10881            String names[] = p.info.authority.split(";");
10882            for (int j = 0; j < names.length; j++) {
10883                if (mProvidersByAuthority.get(names[j]) == p) {
10884                    mProvidersByAuthority.remove(names[j]);
10885                    if (DEBUG_REMOVE) {
10886                        if (chatty)
10887                            Log.d(TAG, "Unregistered content provider: " + names[j]
10888                                    + ", className = " + p.info.name + ", isSyncable = "
10889                                    + p.info.isSyncable);
10890                    }
10891                }
10892            }
10893            if (DEBUG_REMOVE && chatty) {
10894                if (r == null) {
10895                    r = new StringBuilder(256);
10896                } else {
10897                    r.append(' ');
10898                }
10899                r.append(p.info.name);
10900            }
10901        }
10902        if (r != null) {
10903            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10904        }
10905
10906        N = pkg.services.size();
10907        r = null;
10908        for (i=0; i<N; i++) {
10909            PackageParser.Service s = pkg.services.get(i);
10910            mServices.removeService(s);
10911            if (chatty) {
10912                if (r == null) {
10913                    r = new StringBuilder(256);
10914                } else {
10915                    r.append(' ');
10916                }
10917                r.append(s.info.name);
10918            }
10919        }
10920        if (r != null) {
10921            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10922        }
10923
10924        N = pkg.receivers.size();
10925        r = null;
10926        for (i=0; i<N; i++) {
10927            PackageParser.Activity a = pkg.receivers.get(i);
10928            mReceivers.removeActivity(a, "receiver");
10929            if (DEBUG_REMOVE && chatty) {
10930                if (r == null) {
10931                    r = new StringBuilder(256);
10932                } else {
10933                    r.append(' ');
10934                }
10935                r.append(a.info.name);
10936            }
10937        }
10938        if (r != null) {
10939            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10940        }
10941
10942        N = pkg.activities.size();
10943        r = null;
10944        for (i=0; i<N; i++) {
10945            PackageParser.Activity a = pkg.activities.get(i);
10946            mActivities.removeActivity(a, "activity");
10947            if (DEBUG_REMOVE && chatty) {
10948                if (r == null) {
10949                    r = new StringBuilder(256);
10950                } else {
10951                    r.append(' ');
10952                }
10953                r.append(a.info.name);
10954            }
10955        }
10956        if (r != null) {
10957            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10958        }
10959
10960        N = pkg.permissions.size();
10961        r = null;
10962        for (i=0; i<N; i++) {
10963            PackageParser.Permission p = pkg.permissions.get(i);
10964            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10965            if (bp == null) {
10966                bp = mSettings.mPermissionTrees.get(p.info.name);
10967            }
10968            if (bp != null && bp.perm == p) {
10969                bp.perm = null;
10970                if (DEBUG_REMOVE && chatty) {
10971                    if (r == null) {
10972                        r = new StringBuilder(256);
10973                    } else {
10974                        r.append(' ');
10975                    }
10976                    r.append(p.info.name);
10977                }
10978            }
10979            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10980                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10981                if (appOpPkgs != null) {
10982                    appOpPkgs.remove(pkg.packageName);
10983                }
10984            }
10985        }
10986        if (r != null) {
10987            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10988        }
10989
10990        N = pkg.requestedPermissions.size();
10991        r = null;
10992        for (i=0; i<N; i++) {
10993            String perm = pkg.requestedPermissions.get(i);
10994            BasePermission bp = mSettings.mPermissions.get(perm);
10995            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10996                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10997                if (appOpPkgs != null) {
10998                    appOpPkgs.remove(pkg.packageName);
10999                    if (appOpPkgs.isEmpty()) {
11000                        mAppOpPermissionPackages.remove(perm);
11001                    }
11002                }
11003            }
11004        }
11005        if (r != null) {
11006            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11007        }
11008
11009        N = pkg.instrumentation.size();
11010        r = null;
11011        for (i=0; i<N; i++) {
11012            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11013            mInstrumentation.remove(a.getComponentName());
11014            if (DEBUG_REMOVE && chatty) {
11015                if (r == null) {
11016                    r = new StringBuilder(256);
11017                } else {
11018                    r.append(' ');
11019                }
11020                r.append(a.info.name);
11021            }
11022        }
11023        if (r != null) {
11024            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11025        }
11026
11027        r = null;
11028        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11029            // Only system apps can hold shared libraries.
11030            if (pkg.libraryNames != null) {
11031                for (i = 0; i < pkg.libraryNames.size(); i++) {
11032                    String name = pkg.libraryNames.get(i);
11033                    if (removeSharedLibraryLPw(name, 0)) {
11034                        if (DEBUG_REMOVE && chatty) {
11035                            if (r == null) {
11036                                r = new StringBuilder(256);
11037                            } else {
11038                                r.append(' ');
11039                            }
11040                            r.append(name);
11041                        }
11042                    }
11043                }
11044            }
11045        }
11046
11047        r = null;
11048
11049        // Any package can hold static shared libraries.
11050        if (pkg.staticSharedLibName != null) {
11051            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11052                if (DEBUG_REMOVE && chatty) {
11053                    if (r == null) {
11054                        r = new StringBuilder(256);
11055                    } else {
11056                        r.append(' ');
11057                    }
11058                    r.append(pkg.staticSharedLibName);
11059                }
11060            }
11061        }
11062
11063        if (r != null) {
11064            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11065        }
11066    }
11067
11068    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11069        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11070            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11071                return true;
11072            }
11073        }
11074        return false;
11075    }
11076
11077    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11078    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11079    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11080
11081    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11082        // Update the parent permissions
11083        updatePermissionsLPw(pkg.packageName, pkg, flags);
11084        // Update the child permissions
11085        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11086        for (int i = 0; i < childCount; i++) {
11087            PackageParser.Package childPkg = pkg.childPackages.get(i);
11088            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11089        }
11090    }
11091
11092    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11093            int flags) {
11094        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11095        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11096    }
11097
11098    private void updatePermissionsLPw(String changingPkg,
11099            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11100        // Make sure there are no dangling permission trees.
11101        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11102        while (it.hasNext()) {
11103            final BasePermission bp = it.next();
11104            if (bp.packageSetting == null) {
11105                // We may not yet have parsed the package, so just see if
11106                // we still know about its settings.
11107                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11108            }
11109            if (bp.packageSetting == null) {
11110                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11111                        + " from package " + bp.sourcePackage);
11112                it.remove();
11113            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11114                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11115                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11116                            + " from package " + bp.sourcePackage);
11117                    flags |= UPDATE_PERMISSIONS_ALL;
11118                    it.remove();
11119                }
11120            }
11121        }
11122
11123        // Make sure all dynamic permissions have been assigned to a package,
11124        // and make sure there are no dangling permissions.
11125        it = mSettings.mPermissions.values().iterator();
11126        while (it.hasNext()) {
11127            final BasePermission bp = it.next();
11128            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11129                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11130                        + bp.name + " pkg=" + bp.sourcePackage
11131                        + " info=" + bp.pendingInfo);
11132                if (bp.packageSetting == null && bp.pendingInfo != null) {
11133                    final BasePermission tree = findPermissionTreeLP(bp.name);
11134                    if (tree != null && tree.perm != null) {
11135                        bp.packageSetting = tree.packageSetting;
11136                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11137                                new PermissionInfo(bp.pendingInfo));
11138                        bp.perm.info.packageName = tree.perm.info.packageName;
11139                        bp.perm.info.name = bp.name;
11140                        bp.uid = tree.uid;
11141                    }
11142                }
11143            }
11144            if (bp.packageSetting == null) {
11145                // We may not yet have parsed the package, so just see if
11146                // we still know about its settings.
11147                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11148            }
11149            if (bp.packageSetting == null) {
11150                Slog.w(TAG, "Removing dangling permission: " + bp.name
11151                        + " from package " + bp.sourcePackage);
11152                it.remove();
11153            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11154                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11155                    Slog.i(TAG, "Removing old permission: " + bp.name
11156                            + " from package " + bp.sourcePackage);
11157                    flags |= UPDATE_PERMISSIONS_ALL;
11158                    it.remove();
11159                }
11160            }
11161        }
11162
11163        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11164        // Now update the permissions for all packages, in particular
11165        // replace the granted permissions of the system packages.
11166        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11167            for (PackageParser.Package pkg : mPackages.values()) {
11168                if (pkg != pkgInfo) {
11169                    // Only replace for packages on requested volume
11170                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11171                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11172                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11173                    grantPermissionsLPw(pkg, replace, changingPkg);
11174                }
11175            }
11176        }
11177
11178        if (pkgInfo != null) {
11179            // Only replace for packages on requested volume
11180            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11181            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11182                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11183            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11184        }
11185        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11186    }
11187
11188    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11189            String packageOfInterest) {
11190        // IMPORTANT: There are two types of permissions: install and runtime.
11191        // Install time permissions are granted when the app is installed to
11192        // all device users and users added in the future. Runtime permissions
11193        // are granted at runtime explicitly to specific users. Normal and signature
11194        // protected permissions are install time permissions. Dangerous permissions
11195        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11196        // otherwise they are runtime permissions. This function does not manage
11197        // runtime permissions except for the case an app targeting Lollipop MR1
11198        // being upgraded to target a newer SDK, in which case dangerous permissions
11199        // are transformed from install time to runtime ones.
11200
11201        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11202        if (ps == null) {
11203            return;
11204        }
11205
11206        PermissionsState permissionsState = ps.getPermissionsState();
11207        PermissionsState origPermissions = permissionsState;
11208
11209        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11210
11211        boolean runtimePermissionsRevoked = false;
11212        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11213
11214        boolean changedInstallPermission = false;
11215
11216        if (replace) {
11217            ps.installPermissionsFixed = false;
11218            if (!ps.isSharedUser()) {
11219                origPermissions = new PermissionsState(permissionsState);
11220                permissionsState.reset();
11221            } else {
11222                // We need to know only about runtime permission changes since the
11223                // calling code always writes the install permissions state but
11224                // the runtime ones are written only if changed. The only cases of
11225                // changed runtime permissions here are promotion of an install to
11226                // runtime and revocation of a runtime from a shared user.
11227                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11228                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11229                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11230                    runtimePermissionsRevoked = true;
11231                }
11232            }
11233        }
11234
11235        permissionsState.setGlobalGids(mGlobalGids);
11236
11237        final int N = pkg.requestedPermissions.size();
11238        for (int i=0; i<N; i++) {
11239            final String name = pkg.requestedPermissions.get(i);
11240            final BasePermission bp = mSettings.mPermissions.get(name);
11241
11242            if (DEBUG_INSTALL) {
11243                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11244            }
11245
11246            if (bp == null || bp.packageSetting == null) {
11247                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11248                    Slog.w(TAG, "Unknown permission " + name
11249                            + " in package " + pkg.packageName);
11250                }
11251                continue;
11252            }
11253
11254
11255            // Limit ephemeral apps to ephemeral allowed permissions.
11256            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11257                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11258                        + pkg.packageName);
11259                continue;
11260            }
11261
11262            final String perm = bp.name;
11263            boolean allowedSig = false;
11264            int grant = GRANT_DENIED;
11265
11266            // Keep track of app op permissions.
11267            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11268                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11269                if (pkgs == null) {
11270                    pkgs = new ArraySet<>();
11271                    mAppOpPermissionPackages.put(bp.name, pkgs);
11272                }
11273                pkgs.add(pkg.packageName);
11274            }
11275
11276            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11277            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11278                    >= Build.VERSION_CODES.M;
11279            switch (level) {
11280                case PermissionInfo.PROTECTION_NORMAL: {
11281                    // For all apps normal permissions are install time ones.
11282                    grant = GRANT_INSTALL;
11283                } break;
11284
11285                case PermissionInfo.PROTECTION_DANGEROUS: {
11286                    // If a permission review is required for legacy apps we represent
11287                    // their permissions as always granted runtime ones since we need
11288                    // to keep the review required permission flag per user while an
11289                    // install permission's state is shared across all users.
11290                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11291                        // For legacy apps dangerous permissions are install time ones.
11292                        grant = GRANT_INSTALL;
11293                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11294                        // For legacy apps that became modern, install becomes runtime.
11295                        grant = GRANT_UPGRADE;
11296                    } else if (mPromoteSystemApps
11297                            && isSystemApp(ps)
11298                            && mExistingSystemPackages.contains(ps.name)) {
11299                        // For legacy system apps, install becomes runtime.
11300                        // We cannot check hasInstallPermission() for system apps since those
11301                        // permissions were granted implicitly and not persisted pre-M.
11302                        grant = GRANT_UPGRADE;
11303                    } else {
11304                        // For modern apps keep runtime permissions unchanged.
11305                        grant = GRANT_RUNTIME;
11306                    }
11307                } break;
11308
11309                case PermissionInfo.PROTECTION_SIGNATURE: {
11310                    // For all apps signature permissions are install time ones.
11311                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11312                    if (allowedSig) {
11313                        grant = GRANT_INSTALL;
11314                    }
11315                } break;
11316            }
11317
11318            if (DEBUG_INSTALL) {
11319                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11320            }
11321
11322            if (grant != GRANT_DENIED) {
11323                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11324                    // If this is an existing, non-system package, then
11325                    // we can't add any new permissions to it.
11326                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11327                        // Except...  if this is a permission that was added
11328                        // to the platform (note: need to only do this when
11329                        // updating the platform).
11330                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11331                            grant = GRANT_DENIED;
11332                        }
11333                    }
11334                }
11335
11336                switch (grant) {
11337                    case GRANT_INSTALL: {
11338                        // Revoke this as runtime permission to handle the case of
11339                        // a runtime permission being downgraded to an install one.
11340                        // Also in permission review mode we keep dangerous permissions
11341                        // for legacy apps
11342                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11343                            if (origPermissions.getRuntimePermissionState(
11344                                    bp.name, userId) != null) {
11345                                // Revoke the runtime permission and clear the flags.
11346                                origPermissions.revokeRuntimePermission(bp, userId);
11347                                origPermissions.updatePermissionFlags(bp, userId,
11348                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11349                                // If we revoked a permission permission, we have to write.
11350                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11351                                        changedRuntimePermissionUserIds, userId);
11352                            }
11353                        }
11354                        // Grant an install permission.
11355                        if (permissionsState.grantInstallPermission(bp) !=
11356                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11357                            changedInstallPermission = true;
11358                        }
11359                    } break;
11360
11361                    case GRANT_RUNTIME: {
11362                        // Grant previously granted runtime permissions.
11363                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11364                            PermissionState permissionState = origPermissions
11365                                    .getRuntimePermissionState(bp.name, userId);
11366                            int flags = permissionState != null
11367                                    ? permissionState.getFlags() : 0;
11368                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11369                                // Don't propagate the permission in a permission review mode if
11370                                // the former was revoked, i.e. marked to not propagate on upgrade.
11371                                // Note that in a permission review mode install permissions are
11372                                // represented as constantly granted runtime ones since we need to
11373                                // keep a per user state associated with the permission. Also the
11374                                // revoke on upgrade flag is no longer applicable and is reset.
11375                                final boolean revokeOnUpgrade = (flags & PackageManager
11376                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11377                                if (revokeOnUpgrade) {
11378                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11379                                    // Since we changed the flags, we have to write.
11380                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11381                                            changedRuntimePermissionUserIds, userId);
11382                                }
11383                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11384                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11385                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11386                                        // If we cannot put the permission as it was,
11387                                        // we have to write.
11388                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11389                                                changedRuntimePermissionUserIds, userId);
11390                                    }
11391                                }
11392
11393                                // If the app supports runtime permissions no need for a review.
11394                                if (mPermissionReviewRequired
11395                                        && appSupportsRuntimePermissions
11396                                        && (flags & PackageManager
11397                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11398                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11399                                    // Since we changed the flags, we have to write.
11400                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11401                                            changedRuntimePermissionUserIds, userId);
11402                                }
11403                            } else if (mPermissionReviewRequired
11404                                    && !appSupportsRuntimePermissions) {
11405                                // For legacy apps that need a permission review, every new
11406                                // runtime permission is granted but it is pending a review.
11407                                // We also need to review only platform defined runtime
11408                                // permissions as these are the only ones the platform knows
11409                                // how to disable the API to simulate revocation as legacy
11410                                // apps don't expect to run with revoked permissions.
11411                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11412                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11413                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11414                                        // We changed the flags, hence have to write.
11415                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11416                                                changedRuntimePermissionUserIds, userId);
11417                                    }
11418                                }
11419                                if (permissionsState.grantRuntimePermission(bp, userId)
11420                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11421                                    // We changed the permission, hence have to write.
11422                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11423                                            changedRuntimePermissionUserIds, userId);
11424                                }
11425                            }
11426                            // Propagate the permission flags.
11427                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11428                        }
11429                    } break;
11430
11431                    case GRANT_UPGRADE: {
11432                        // Grant runtime permissions for a previously held install permission.
11433                        PermissionState permissionState = origPermissions
11434                                .getInstallPermissionState(bp.name);
11435                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11436
11437                        if (origPermissions.revokeInstallPermission(bp)
11438                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11439                            // We will be transferring the permission flags, so clear them.
11440                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11441                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11442                            changedInstallPermission = true;
11443                        }
11444
11445                        // If the permission is not to be promoted to runtime we ignore it and
11446                        // also its other flags as they are not applicable to install permissions.
11447                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11448                            for (int userId : currentUserIds) {
11449                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11450                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11451                                    // Transfer the permission flags.
11452                                    permissionsState.updatePermissionFlags(bp, userId,
11453                                            flags, flags);
11454                                    // If we granted the permission, we have to write.
11455                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11456                                            changedRuntimePermissionUserIds, userId);
11457                                }
11458                            }
11459                        }
11460                    } break;
11461
11462                    default: {
11463                        if (packageOfInterest == null
11464                                || packageOfInterest.equals(pkg.packageName)) {
11465                            Slog.w(TAG, "Not granting permission " + perm
11466                                    + " to package " + pkg.packageName
11467                                    + " because it was previously installed without");
11468                        }
11469                    } break;
11470                }
11471            } else {
11472                if (permissionsState.revokeInstallPermission(bp) !=
11473                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11474                    // Also drop the permission flags.
11475                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11476                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11477                    changedInstallPermission = true;
11478                    Slog.i(TAG, "Un-granting permission " + perm
11479                            + " from package " + pkg.packageName
11480                            + " (protectionLevel=" + bp.protectionLevel
11481                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11482                            + ")");
11483                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11484                    // Don't print warning for app op permissions, since it is fine for them
11485                    // not to be granted, there is a UI for the user to decide.
11486                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11487                        Slog.w(TAG, "Not granting permission " + perm
11488                                + " to package " + pkg.packageName
11489                                + " (protectionLevel=" + bp.protectionLevel
11490                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11491                                + ")");
11492                    }
11493                }
11494            }
11495        }
11496
11497        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11498                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11499            // This is the first that we have heard about this package, so the
11500            // permissions we have now selected are fixed until explicitly
11501            // changed.
11502            ps.installPermissionsFixed = true;
11503        }
11504
11505        // Persist the runtime permissions state for users with changes. If permissions
11506        // were revoked because no app in the shared user declares them we have to
11507        // write synchronously to avoid losing runtime permissions state.
11508        for (int userId : changedRuntimePermissionUserIds) {
11509            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11510        }
11511    }
11512
11513    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11514        boolean allowed = false;
11515        final int NP = PackageParser.NEW_PERMISSIONS.length;
11516        for (int ip=0; ip<NP; ip++) {
11517            final PackageParser.NewPermissionInfo npi
11518                    = PackageParser.NEW_PERMISSIONS[ip];
11519            if (npi.name.equals(perm)
11520                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11521                allowed = true;
11522                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11523                        + pkg.packageName);
11524                break;
11525            }
11526        }
11527        return allowed;
11528    }
11529
11530    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11531            BasePermission bp, PermissionsState origPermissions) {
11532        boolean privilegedPermission = (bp.protectionLevel
11533                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11534        boolean privappPermissionsDisable =
11535                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11536        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11537        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11538        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11539                && !platformPackage && platformPermission) {
11540            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11541                    .getPrivAppPermissions(pkg.packageName);
11542            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11543            if (!whitelisted) {
11544                Slog.w(TAG, "Privileged permission " + perm + " for package "
11545                        + pkg.packageName + " - not in privapp-permissions whitelist");
11546                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11547                    return false;
11548                }
11549            }
11550        }
11551        boolean allowed = (compareSignatures(
11552                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11553                        == PackageManager.SIGNATURE_MATCH)
11554                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11555                        == PackageManager.SIGNATURE_MATCH);
11556        if (!allowed && privilegedPermission) {
11557            if (isSystemApp(pkg)) {
11558                // For updated system applications, a system permission
11559                // is granted only if it had been defined by the original application.
11560                if (pkg.isUpdatedSystemApp()) {
11561                    final PackageSetting sysPs = mSettings
11562                            .getDisabledSystemPkgLPr(pkg.packageName);
11563                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11564                        // If the original was granted this permission, we take
11565                        // that grant decision as read and propagate it to the
11566                        // update.
11567                        if (sysPs.isPrivileged()) {
11568                            allowed = true;
11569                        }
11570                    } else {
11571                        // The system apk may have been updated with an older
11572                        // version of the one on the data partition, but which
11573                        // granted a new system permission that it didn't have
11574                        // before.  In this case we do want to allow the app to
11575                        // now get the new permission if the ancestral apk is
11576                        // privileged to get it.
11577                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11578                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11579                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11580                                    allowed = true;
11581                                    break;
11582                                }
11583                            }
11584                        }
11585                        // Also if a privileged parent package on the system image or any of
11586                        // its children requested a privileged permission, the updated child
11587                        // packages can also get the permission.
11588                        if (pkg.parentPackage != null) {
11589                            final PackageSetting disabledSysParentPs = mSettings
11590                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11591                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11592                                    && disabledSysParentPs.isPrivileged()) {
11593                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11594                                    allowed = true;
11595                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11596                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11597                                    for (int i = 0; i < count; i++) {
11598                                        PackageParser.Package disabledSysChildPkg =
11599                                                disabledSysParentPs.pkg.childPackages.get(i);
11600                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11601                                                perm)) {
11602                                            allowed = true;
11603                                            break;
11604                                        }
11605                                    }
11606                                }
11607                            }
11608                        }
11609                    }
11610                } else {
11611                    allowed = isPrivilegedApp(pkg);
11612                }
11613            }
11614        }
11615        if (!allowed) {
11616            if (!allowed && (bp.protectionLevel
11617                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11618                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11619                // If this was a previously normal/dangerous permission that got moved
11620                // to a system permission as part of the runtime permission redesign, then
11621                // we still want to blindly grant it to old apps.
11622                allowed = true;
11623            }
11624            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11625                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11626                // If this permission is to be granted to the system installer and
11627                // this app is an installer, then it gets the permission.
11628                allowed = true;
11629            }
11630            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11631                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11632                // If this permission is to be granted to the system verifier and
11633                // this app is a verifier, then it gets the permission.
11634                allowed = true;
11635            }
11636            if (!allowed && (bp.protectionLevel
11637                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11638                    && isSystemApp(pkg)) {
11639                // Any pre-installed system app is allowed to get this permission.
11640                allowed = true;
11641            }
11642            if (!allowed && (bp.protectionLevel
11643                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11644                // For development permissions, a development permission
11645                // is granted only if it was already granted.
11646                allowed = origPermissions.hasInstallPermission(perm);
11647            }
11648            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11649                    && pkg.packageName.equals(mSetupWizardPackage)) {
11650                // If this permission is to be granted to the system setup wizard and
11651                // this app is a setup wizard, then it gets the permission.
11652                allowed = true;
11653            }
11654        }
11655        return allowed;
11656    }
11657
11658    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11659        final int permCount = pkg.requestedPermissions.size();
11660        for (int j = 0; j < permCount; j++) {
11661            String requestedPermission = pkg.requestedPermissions.get(j);
11662            if (permission.equals(requestedPermission)) {
11663                return true;
11664            }
11665        }
11666        return false;
11667    }
11668
11669    final class ActivityIntentResolver
11670            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11671        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11672                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11673            if (!sUserManager.exists(userId)) return null;
11674            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
11675                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
11676                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
11677            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11678                    isEphemeral, userId);
11679        }
11680
11681        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11682                int userId) {
11683            if (!sUserManager.exists(userId)) return null;
11684            mFlags = flags;
11685            return super.queryIntent(intent, resolvedType,
11686                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11687                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11688                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11689        }
11690
11691        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11692                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11693            if (!sUserManager.exists(userId)) return null;
11694            if (packageActivities == null) {
11695                return null;
11696            }
11697            mFlags = flags;
11698            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11699            final boolean vislbleToEphemeral =
11700                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11701            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
11702            final int N = packageActivities.size();
11703            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11704                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11705
11706            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11707            for (int i = 0; i < N; ++i) {
11708                intentFilters = packageActivities.get(i).intents;
11709                if (intentFilters != null && intentFilters.size() > 0) {
11710                    PackageParser.ActivityIntentInfo[] array =
11711                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11712                    intentFilters.toArray(array);
11713                    listCut.add(array);
11714                }
11715            }
11716            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11717                    vislbleToEphemeral, isEphemeral, listCut, userId);
11718        }
11719
11720        /**
11721         * Finds a privileged activity that matches the specified activity names.
11722         */
11723        private PackageParser.Activity findMatchingActivity(
11724                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11725            for (PackageParser.Activity sysActivity : activityList) {
11726                if (sysActivity.info.name.equals(activityInfo.name)) {
11727                    return sysActivity;
11728                }
11729                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11730                    return sysActivity;
11731                }
11732                if (sysActivity.info.targetActivity != null) {
11733                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11734                        return sysActivity;
11735                    }
11736                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11737                        return sysActivity;
11738                    }
11739                }
11740            }
11741            return null;
11742        }
11743
11744        public class IterGenerator<E> {
11745            public Iterator<E> generate(ActivityIntentInfo info) {
11746                return null;
11747            }
11748        }
11749
11750        public class ActionIterGenerator extends IterGenerator<String> {
11751            @Override
11752            public Iterator<String> generate(ActivityIntentInfo info) {
11753                return info.actionsIterator();
11754            }
11755        }
11756
11757        public class CategoriesIterGenerator extends IterGenerator<String> {
11758            @Override
11759            public Iterator<String> generate(ActivityIntentInfo info) {
11760                return info.categoriesIterator();
11761            }
11762        }
11763
11764        public class SchemesIterGenerator extends IterGenerator<String> {
11765            @Override
11766            public Iterator<String> generate(ActivityIntentInfo info) {
11767                return info.schemesIterator();
11768            }
11769        }
11770
11771        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11772            @Override
11773            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11774                return info.authoritiesIterator();
11775            }
11776        }
11777
11778        /**
11779         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11780         * MODIFIED. Do not pass in a list that should not be changed.
11781         */
11782        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11783                IterGenerator<T> generator, Iterator<T> searchIterator) {
11784            // loop through the set of actions; every one must be found in the intent filter
11785            while (searchIterator.hasNext()) {
11786                // we must have at least one filter in the list to consider a match
11787                if (intentList.size() == 0) {
11788                    break;
11789                }
11790
11791                final T searchAction = searchIterator.next();
11792
11793                // loop through the set of intent filters
11794                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11795                while (intentIter.hasNext()) {
11796                    final ActivityIntentInfo intentInfo = intentIter.next();
11797                    boolean selectionFound = false;
11798
11799                    // loop through the intent filter's selection criteria; at least one
11800                    // of them must match the searched criteria
11801                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11802                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11803                        final T intentSelection = intentSelectionIter.next();
11804                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11805                            selectionFound = true;
11806                            break;
11807                        }
11808                    }
11809
11810                    // the selection criteria wasn't found in this filter's set; this filter
11811                    // is not a potential match
11812                    if (!selectionFound) {
11813                        intentIter.remove();
11814                    }
11815                }
11816            }
11817        }
11818
11819        private boolean isProtectedAction(ActivityIntentInfo filter) {
11820            final Iterator<String> actionsIter = filter.actionsIterator();
11821            while (actionsIter != null && actionsIter.hasNext()) {
11822                final String filterAction = actionsIter.next();
11823                if (PROTECTED_ACTIONS.contains(filterAction)) {
11824                    return true;
11825                }
11826            }
11827            return false;
11828        }
11829
11830        /**
11831         * Adjusts the priority of the given intent filter according to policy.
11832         * <p>
11833         * <ul>
11834         * <li>The priority for non privileged applications is capped to '0'</li>
11835         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11836         * <li>The priority for unbundled updates to privileged applications is capped to the
11837         *      priority defined on the system partition</li>
11838         * </ul>
11839         * <p>
11840         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11841         * allowed to obtain any priority on any action.
11842         */
11843        private void adjustPriority(
11844                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11845            // nothing to do; priority is fine as-is
11846            if (intent.getPriority() <= 0) {
11847                return;
11848            }
11849
11850            final ActivityInfo activityInfo = intent.activity.info;
11851            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11852
11853            final boolean privilegedApp =
11854                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11855            if (!privilegedApp) {
11856                // non-privileged applications can never define a priority >0
11857                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11858                        + " package: " + applicationInfo.packageName
11859                        + " activity: " + intent.activity.className
11860                        + " origPrio: " + intent.getPriority());
11861                intent.setPriority(0);
11862                return;
11863            }
11864
11865            if (systemActivities == null) {
11866                // the system package is not disabled; we're parsing the system partition
11867                if (isProtectedAction(intent)) {
11868                    if (mDeferProtectedFilters) {
11869                        // We can't deal with these just yet. No component should ever obtain a
11870                        // >0 priority for a protected actions, with ONE exception -- the setup
11871                        // wizard. The setup wizard, however, cannot be known until we're able to
11872                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11873                        // until all intent filters have been processed. Chicken, meet egg.
11874                        // Let the filter temporarily have a high priority and rectify the
11875                        // priorities after all system packages have been scanned.
11876                        mProtectedFilters.add(intent);
11877                        if (DEBUG_FILTERS) {
11878                            Slog.i(TAG, "Protected action; save for later;"
11879                                    + " package: " + applicationInfo.packageName
11880                                    + " activity: " + intent.activity.className
11881                                    + " origPrio: " + intent.getPriority());
11882                        }
11883                        return;
11884                    } else {
11885                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11886                            Slog.i(TAG, "No setup wizard;"
11887                                + " All protected intents capped to priority 0");
11888                        }
11889                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11890                            if (DEBUG_FILTERS) {
11891                                Slog.i(TAG, "Found setup wizard;"
11892                                    + " allow priority " + intent.getPriority() + ";"
11893                                    + " package: " + intent.activity.info.packageName
11894                                    + " activity: " + intent.activity.className
11895                                    + " priority: " + intent.getPriority());
11896                            }
11897                            // setup wizard gets whatever it wants
11898                            return;
11899                        }
11900                        Slog.w(TAG, "Protected action; cap priority to 0;"
11901                                + " package: " + intent.activity.info.packageName
11902                                + " activity: " + intent.activity.className
11903                                + " origPrio: " + intent.getPriority());
11904                        intent.setPriority(0);
11905                        return;
11906                    }
11907                }
11908                // privileged apps on the system image get whatever priority they request
11909                return;
11910            }
11911
11912            // privileged app unbundled update ... try to find the same activity
11913            final PackageParser.Activity foundActivity =
11914                    findMatchingActivity(systemActivities, activityInfo);
11915            if (foundActivity == null) {
11916                // this is a new activity; it cannot obtain >0 priority
11917                if (DEBUG_FILTERS) {
11918                    Slog.i(TAG, "New activity; cap priority to 0;"
11919                            + " package: " + applicationInfo.packageName
11920                            + " activity: " + intent.activity.className
11921                            + " origPrio: " + intent.getPriority());
11922                }
11923                intent.setPriority(0);
11924                return;
11925            }
11926
11927            // found activity, now check for filter equivalence
11928
11929            // a shallow copy is enough; we modify the list, not its contents
11930            final List<ActivityIntentInfo> intentListCopy =
11931                    new ArrayList<>(foundActivity.intents);
11932            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11933
11934            // find matching action subsets
11935            final Iterator<String> actionsIterator = intent.actionsIterator();
11936            if (actionsIterator != null) {
11937                getIntentListSubset(
11938                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11939                if (intentListCopy.size() == 0) {
11940                    // no more intents to match; we're not equivalent
11941                    if (DEBUG_FILTERS) {
11942                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11943                                + " package: " + applicationInfo.packageName
11944                                + " activity: " + intent.activity.className
11945                                + " origPrio: " + intent.getPriority());
11946                    }
11947                    intent.setPriority(0);
11948                    return;
11949                }
11950            }
11951
11952            // find matching category subsets
11953            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11954            if (categoriesIterator != null) {
11955                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11956                        categoriesIterator);
11957                if (intentListCopy.size() == 0) {
11958                    // no more intents to match; we're not equivalent
11959                    if (DEBUG_FILTERS) {
11960                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11961                                + " package: " + applicationInfo.packageName
11962                                + " activity: " + intent.activity.className
11963                                + " origPrio: " + intent.getPriority());
11964                    }
11965                    intent.setPriority(0);
11966                    return;
11967                }
11968            }
11969
11970            // find matching schemes subsets
11971            final Iterator<String> schemesIterator = intent.schemesIterator();
11972            if (schemesIterator != null) {
11973                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11974                        schemesIterator);
11975                if (intentListCopy.size() == 0) {
11976                    // no more intents to match; we're not equivalent
11977                    if (DEBUG_FILTERS) {
11978                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11979                                + " package: " + applicationInfo.packageName
11980                                + " activity: " + intent.activity.className
11981                                + " origPrio: " + intent.getPriority());
11982                    }
11983                    intent.setPriority(0);
11984                    return;
11985                }
11986            }
11987
11988            // find matching authorities subsets
11989            final Iterator<IntentFilter.AuthorityEntry>
11990                    authoritiesIterator = intent.authoritiesIterator();
11991            if (authoritiesIterator != null) {
11992                getIntentListSubset(intentListCopy,
11993                        new AuthoritiesIterGenerator(),
11994                        authoritiesIterator);
11995                if (intentListCopy.size() == 0) {
11996                    // no more intents to match; we're not equivalent
11997                    if (DEBUG_FILTERS) {
11998                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11999                                + " package: " + applicationInfo.packageName
12000                                + " activity: " + intent.activity.className
12001                                + " origPrio: " + intent.getPriority());
12002                    }
12003                    intent.setPriority(0);
12004                    return;
12005                }
12006            }
12007
12008            // we found matching filter(s); app gets the max priority of all intents
12009            int cappedPriority = 0;
12010            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12011                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12012            }
12013            if (intent.getPriority() > cappedPriority) {
12014                if (DEBUG_FILTERS) {
12015                    Slog.i(TAG, "Found matching filter(s);"
12016                            + " cap priority to " + cappedPriority + ";"
12017                            + " package: " + applicationInfo.packageName
12018                            + " activity: " + intent.activity.className
12019                            + " origPrio: " + intent.getPriority());
12020                }
12021                intent.setPriority(cappedPriority);
12022                return;
12023            }
12024            // all this for nothing; the requested priority was <= what was on the system
12025        }
12026
12027        public final void addActivity(PackageParser.Activity a, String type) {
12028            mActivities.put(a.getComponentName(), a);
12029            if (DEBUG_SHOW_INFO)
12030                Log.v(
12031                TAG, "  " + type + " " +
12032                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12033            if (DEBUG_SHOW_INFO)
12034                Log.v(TAG, "    Class=" + a.info.name);
12035            final int NI = a.intents.size();
12036            for (int j=0; j<NI; j++) {
12037                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12038                if ("activity".equals(type)) {
12039                    final PackageSetting ps =
12040                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12041                    final List<PackageParser.Activity> systemActivities =
12042                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12043                    adjustPriority(systemActivities, intent);
12044                }
12045                if (DEBUG_SHOW_INFO) {
12046                    Log.v(TAG, "    IntentFilter:");
12047                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12048                }
12049                if (!intent.debugCheck()) {
12050                    Log.w(TAG, "==> For Activity " + a.info.name);
12051                }
12052                addFilter(intent);
12053            }
12054        }
12055
12056        public final void removeActivity(PackageParser.Activity a, String type) {
12057            mActivities.remove(a.getComponentName());
12058            if (DEBUG_SHOW_INFO) {
12059                Log.v(TAG, "  " + type + " "
12060                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12061                                : a.info.name) + ":");
12062                Log.v(TAG, "    Class=" + a.info.name);
12063            }
12064            final int NI = a.intents.size();
12065            for (int j=0; j<NI; j++) {
12066                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12067                if (DEBUG_SHOW_INFO) {
12068                    Log.v(TAG, "    IntentFilter:");
12069                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12070                }
12071                removeFilter(intent);
12072            }
12073        }
12074
12075        @Override
12076        protected boolean allowFilterResult(
12077                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12078            ActivityInfo filterAi = filter.activity.info;
12079            for (int i=dest.size()-1; i>=0; i--) {
12080                ActivityInfo destAi = dest.get(i).activityInfo;
12081                if (destAi.name == filterAi.name
12082                        && destAi.packageName == filterAi.packageName) {
12083                    return false;
12084                }
12085            }
12086            return true;
12087        }
12088
12089        @Override
12090        protected ActivityIntentInfo[] newArray(int size) {
12091            return new ActivityIntentInfo[size];
12092        }
12093
12094        @Override
12095        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12096            if (!sUserManager.exists(userId)) return true;
12097            PackageParser.Package p = filter.activity.owner;
12098            if (p != null) {
12099                PackageSetting ps = (PackageSetting)p.mExtras;
12100                if (ps != null) {
12101                    // System apps are never considered stopped for purposes of
12102                    // filtering, because there may be no way for the user to
12103                    // actually re-launch them.
12104                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12105                            && ps.getStopped(userId);
12106                }
12107            }
12108            return false;
12109        }
12110
12111        @Override
12112        protected boolean isPackageForFilter(String packageName,
12113                PackageParser.ActivityIntentInfo info) {
12114            return packageName.equals(info.activity.owner.packageName);
12115        }
12116
12117        @Override
12118        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12119                int match, int userId) {
12120            if (!sUserManager.exists(userId)) return null;
12121            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12122                return null;
12123            }
12124            final PackageParser.Activity activity = info.activity;
12125            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12126            if (ps == null) {
12127                return null;
12128            }
12129            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12130                    ps.readUserState(userId), userId);
12131            if (ai == null) {
12132                return null;
12133            }
12134            final ResolveInfo res = new ResolveInfo();
12135            res.activityInfo = ai;
12136            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12137                res.filter = info;
12138            }
12139            if (info != null) {
12140                res.handleAllWebDataURI = info.handleAllWebDataURI();
12141            }
12142            res.priority = info.getPriority();
12143            res.preferredOrder = activity.owner.mPreferredOrder;
12144            //System.out.println("Result: " + res.activityInfo.className +
12145            //                   " = " + res.priority);
12146            res.match = match;
12147            res.isDefault = info.hasDefault;
12148            res.labelRes = info.labelRes;
12149            res.nonLocalizedLabel = info.nonLocalizedLabel;
12150            if (userNeedsBadging(userId)) {
12151                res.noResourceId = true;
12152            } else {
12153                res.icon = info.icon;
12154            }
12155            res.iconResourceId = info.icon;
12156            res.system = res.activityInfo.applicationInfo.isSystemApp();
12157            return res;
12158        }
12159
12160        @Override
12161        protected void sortResults(List<ResolveInfo> results) {
12162            Collections.sort(results, mResolvePrioritySorter);
12163        }
12164
12165        @Override
12166        protected void dumpFilter(PrintWriter out, String prefix,
12167                PackageParser.ActivityIntentInfo filter) {
12168            out.print(prefix); out.print(
12169                    Integer.toHexString(System.identityHashCode(filter.activity)));
12170                    out.print(' ');
12171                    filter.activity.printComponentShortName(out);
12172                    out.print(" filter ");
12173                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12174        }
12175
12176        @Override
12177        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12178            return filter.activity;
12179        }
12180
12181        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12182            PackageParser.Activity activity = (PackageParser.Activity)label;
12183            out.print(prefix); out.print(
12184                    Integer.toHexString(System.identityHashCode(activity)));
12185                    out.print(' ');
12186                    activity.printComponentShortName(out);
12187            if (count > 1) {
12188                out.print(" ("); out.print(count); out.print(" filters)");
12189            }
12190            out.println();
12191        }
12192
12193        // Keys are String (activity class name), values are Activity.
12194        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12195                = new ArrayMap<ComponentName, PackageParser.Activity>();
12196        private int mFlags;
12197    }
12198
12199    private final class ServiceIntentResolver
12200            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12201        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12202                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12203            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12204            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12205                    isEphemeral, userId);
12206        }
12207
12208        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12209                int userId) {
12210            if (!sUserManager.exists(userId)) return null;
12211            mFlags = flags;
12212            return super.queryIntent(intent, resolvedType,
12213                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12214                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12215                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12216        }
12217
12218        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12219                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12220            if (!sUserManager.exists(userId)) return null;
12221            if (packageServices == null) {
12222                return null;
12223            }
12224            mFlags = flags;
12225            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12226            final boolean vislbleToEphemeral =
12227                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12228            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12229            final int N = packageServices.size();
12230            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12231                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12232
12233            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12234            for (int i = 0; i < N; ++i) {
12235                intentFilters = packageServices.get(i).intents;
12236                if (intentFilters != null && intentFilters.size() > 0) {
12237                    PackageParser.ServiceIntentInfo[] array =
12238                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12239                    intentFilters.toArray(array);
12240                    listCut.add(array);
12241                }
12242            }
12243            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12244                    vislbleToEphemeral, isEphemeral, listCut, userId);
12245        }
12246
12247        public final void addService(PackageParser.Service s) {
12248            mServices.put(s.getComponentName(), s);
12249            if (DEBUG_SHOW_INFO) {
12250                Log.v(TAG, "  "
12251                        + (s.info.nonLocalizedLabel != null
12252                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12253                Log.v(TAG, "    Class=" + s.info.name);
12254            }
12255            final int NI = s.intents.size();
12256            int j;
12257            for (j=0; j<NI; j++) {
12258                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12259                if (DEBUG_SHOW_INFO) {
12260                    Log.v(TAG, "    IntentFilter:");
12261                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12262                }
12263                if (!intent.debugCheck()) {
12264                    Log.w(TAG, "==> For Service " + s.info.name);
12265                }
12266                addFilter(intent);
12267            }
12268        }
12269
12270        public final void removeService(PackageParser.Service s) {
12271            mServices.remove(s.getComponentName());
12272            if (DEBUG_SHOW_INFO) {
12273                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12274                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12275                Log.v(TAG, "    Class=" + s.info.name);
12276            }
12277            final int NI = s.intents.size();
12278            int j;
12279            for (j=0; j<NI; j++) {
12280                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12281                if (DEBUG_SHOW_INFO) {
12282                    Log.v(TAG, "    IntentFilter:");
12283                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12284                }
12285                removeFilter(intent);
12286            }
12287        }
12288
12289        @Override
12290        protected boolean allowFilterResult(
12291                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12292            ServiceInfo filterSi = filter.service.info;
12293            for (int i=dest.size()-1; i>=0; i--) {
12294                ServiceInfo destAi = dest.get(i).serviceInfo;
12295                if (destAi.name == filterSi.name
12296                        && destAi.packageName == filterSi.packageName) {
12297                    return false;
12298                }
12299            }
12300            return true;
12301        }
12302
12303        @Override
12304        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12305            return new PackageParser.ServiceIntentInfo[size];
12306        }
12307
12308        @Override
12309        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12310            if (!sUserManager.exists(userId)) return true;
12311            PackageParser.Package p = filter.service.owner;
12312            if (p != null) {
12313                PackageSetting ps = (PackageSetting)p.mExtras;
12314                if (ps != null) {
12315                    // System apps are never considered stopped for purposes of
12316                    // filtering, because there may be no way for the user to
12317                    // actually re-launch them.
12318                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12319                            && ps.getStopped(userId);
12320                }
12321            }
12322            return false;
12323        }
12324
12325        @Override
12326        protected boolean isPackageForFilter(String packageName,
12327                PackageParser.ServiceIntentInfo info) {
12328            return packageName.equals(info.service.owner.packageName);
12329        }
12330
12331        @Override
12332        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12333                int match, int userId) {
12334            if (!sUserManager.exists(userId)) return null;
12335            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12336            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12337                return null;
12338            }
12339            final PackageParser.Service service = info.service;
12340            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12341            if (ps == null) {
12342                return null;
12343            }
12344            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12345                    ps.readUserState(userId), userId);
12346            if (si == null) {
12347                return null;
12348            }
12349            final ResolveInfo res = new ResolveInfo();
12350            res.serviceInfo = si;
12351            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12352                res.filter = filter;
12353            }
12354            res.priority = info.getPriority();
12355            res.preferredOrder = service.owner.mPreferredOrder;
12356            res.match = match;
12357            res.isDefault = info.hasDefault;
12358            res.labelRes = info.labelRes;
12359            res.nonLocalizedLabel = info.nonLocalizedLabel;
12360            res.icon = info.icon;
12361            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12362            return res;
12363        }
12364
12365        @Override
12366        protected void sortResults(List<ResolveInfo> results) {
12367            Collections.sort(results, mResolvePrioritySorter);
12368        }
12369
12370        @Override
12371        protected void dumpFilter(PrintWriter out, String prefix,
12372                PackageParser.ServiceIntentInfo filter) {
12373            out.print(prefix); out.print(
12374                    Integer.toHexString(System.identityHashCode(filter.service)));
12375                    out.print(' ');
12376                    filter.service.printComponentShortName(out);
12377                    out.print(" filter ");
12378                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12379        }
12380
12381        @Override
12382        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12383            return filter.service;
12384        }
12385
12386        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12387            PackageParser.Service service = (PackageParser.Service)label;
12388            out.print(prefix); out.print(
12389                    Integer.toHexString(System.identityHashCode(service)));
12390                    out.print(' ');
12391                    service.printComponentShortName(out);
12392            if (count > 1) {
12393                out.print(" ("); out.print(count); out.print(" filters)");
12394            }
12395            out.println();
12396        }
12397
12398//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12399//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12400//            final List<ResolveInfo> retList = Lists.newArrayList();
12401//            while (i.hasNext()) {
12402//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12403//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12404//                    retList.add(resolveInfo);
12405//                }
12406//            }
12407//            return retList;
12408//        }
12409
12410        // Keys are String (activity class name), values are Activity.
12411        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12412                = new ArrayMap<ComponentName, PackageParser.Service>();
12413        private int mFlags;
12414    }
12415
12416    private final class ProviderIntentResolver
12417            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12418        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12419                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12420            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12421            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12422                    isEphemeral, userId);
12423        }
12424
12425        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12426                int userId) {
12427            if (!sUserManager.exists(userId))
12428                return null;
12429            mFlags = flags;
12430            return super.queryIntent(intent, resolvedType,
12431                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12432                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12433                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12434        }
12435
12436        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12437                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12438            if (!sUserManager.exists(userId))
12439                return null;
12440            if (packageProviders == null) {
12441                return null;
12442            }
12443            mFlags = flags;
12444            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12445            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12446            final boolean vislbleToEphemeral =
12447                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12448            final int N = packageProviders.size();
12449            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12450                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12451
12452            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12453            for (int i = 0; i < N; ++i) {
12454                intentFilters = packageProviders.get(i).intents;
12455                if (intentFilters != null && intentFilters.size() > 0) {
12456                    PackageParser.ProviderIntentInfo[] array =
12457                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12458                    intentFilters.toArray(array);
12459                    listCut.add(array);
12460                }
12461            }
12462            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12463                    vislbleToEphemeral, isEphemeral, listCut, userId);
12464        }
12465
12466        public final void addProvider(PackageParser.Provider p) {
12467            if (mProviders.containsKey(p.getComponentName())) {
12468                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12469                return;
12470            }
12471
12472            mProviders.put(p.getComponentName(), p);
12473            if (DEBUG_SHOW_INFO) {
12474                Log.v(TAG, "  "
12475                        + (p.info.nonLocalizedLabel != null
12476                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12477                Log.v(TAG, "    Class=" + p.info.name);
12478            }
12479            final int NI = p.intents.size();
12480            int j;
12481            for (j = 0; j < NI; j++) {
12482                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12483                if (DEBUG_SHOW_INFO) {
12484                    Log.v(TAG, "    IntentFilter:");
12485                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12486                }
12487                if (!intent.debugCheck()) {
12488                    Log.w(TAG, "==> For Provider " + p.info.name);
12489                }
12490                addFilter(intent);
12491            }
12492        }
12493
12494        public final void removeProvider(PackageParser.Provider p) {
12495            mProviders.remove(p.getComponentName());
12496            if (DEBUG_SHOW_INFO) {
12497                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12498                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12499                Log.v(TAG, "    Class=" + p.info.name);
12500            }
12501            final int NI = p.intents.size();
12502            int j;
12503            for (j = 0; j < NI; j++) {
12504                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12505                if (DEBUG_SHOW_INFO) {
12506                    Log.v(TAG, "    IntentFilter:");
12507                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12508                }
12509                removeFilter(intent);
12510            }
12511        }
12512
12513        @Override
12514        protected boolean allowFilterResult(
12515                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12516            ProviderInfo filterPi = filter.provider.info;
12517            for (int i = dest.size() - 1; i >= 0; i--) {
12518                ProviderInfo destPi = dest.get(i).providerInfo;
12519                if (destPi.name == filterPi.name
12520                        && destPi.packageName == filterPi.packageName) {
12521                    return false;
12522                }
12523            }
12524            return true;
12525        }
12526
12527        @Override
12528        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12529            return new PackageParser.ProviderIntentInfo[size];
12530        }
12531
12532        @Override
12533        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12534            if (!sUserManager.exists(userId))
12535                return true;
12536            PackageParser.Package p = filter.provider.owner;
12537            if (p != null) {
12538                PackageSetting ps = (PackageSetting) p.mExtras;
12539                if (ps != null) {
12540                    // System apps are never considered stopped for purposes of
12541                    // filtering, because there may be no way for the user to
12542                    // actually re-launch them.
12543                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12544                            && ps.getStopped(userId);
12545                }
12546            }
12547            return false;
12548        }
12549
12550        @Override
12551        protected boolean isPackageForFilter(String packageName,
12552                PackageParser.ProviderIntentInfo info) {
12553            return packageName.equals(info.provider.owner.packageName);
12554        }
12555
12556        @Override
12557        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12558                int match, int userId) {
12559            if (!sUserManager.exists(userId))
12560                return null;
12561            final PackageParser.ProviderIntentInfo info = filter;
12562            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12563                return null;
12564            }
12565            final PackageParser.Provider provider = info.provider;
12566            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12567            if (ps == null) {
12568                return null;
12569            }
12570            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12571                    ps.readUserState(userId), userId);
12572            if (pi == null) {
12573                return null;
12574            }
12575            final ResolveInfo res = new ResolveInfo();
12576            res.providerInfo = pi;
12577            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12578                res.filter = filter;
12579            }
12580            res.priority = info.getPriority();
12581            res.preferredOrder = provider.owner.mPreferredOrder;
12582            res.match = match;
12583            res.isDefault = info.hasDefault;
12584            res.labelRes = info.labelRes;
12585            res.nonLocalizedLabel = info.nonLocalizedLabel;
12586            res.icon = info.icon;
12587            res.system = res.providerInfo.applicationInfo.isSystemApp();
12588            return res;
12589        }
12590
12591        @Override
12592        protected void sortResults(List<ResolveInfo> results) {
12593            Collections.sort(results, mResolvePrioritySorter);
12594        }
12595
12596        @Override
12597        protected void dumpFilter(PrintWriter out, String prefix,
12598                PackageParser.ProviderIntentInfo filter) {
12599            out.print(prefix);
12600            out.print(
12601                    Integer.toHexString(System.identityHashCode(filter.provider)));
12602            out.print(' ');
12603            filter.provider.printComponentShortName(out);
12604            out.print(" filter ");
12605            out.println(Integer.toHexString(System.identityHashCode(filter)));
12606        }
12607
12608        @Override
12609        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12610            return filter.provider;
12611        }
12612
12613        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12614            PackageParser.Provider provider = (PackageParser.Provider)label;
12615            out.print(prefix); out.print(
12616                    Integer.toHexString(System.identityHashCode(provider)));
12617                    out.print(' ');
12618                    provider.printComponentShortName(out);
12619            if (count > 1) {
12620                out.print(" ("); out.print(count); out.print(" filters)");
12621            }
12622            out.println();
12623        }
12624
12625        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12626                = new ArrayMap<ComponentName, PackageParser.Provider>();
12627        private int mFlags;
12628    }
12629
12630    static final class EphemeralIntentResolver
12631            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12632        /**
12633         * The result that has the highest defined order. Ordering applies on a
12634         * per-package basis. Mapping is from package name to Pair of order and
12635         * EphemeralResolveInfo.
12636         * <p>
12637         * NOTE: This is implemented as a field variable for convenience and efficiency.
12638         * By having a field variable, we're able to track filter ordering as soon as
12639         * a non-zero order is defined. Otherwise, multiple loops across the result set
12640         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12641         * this needs to be contained entirely within {@link #filterResults()}.
12642         */
12643        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12644
12645        @Override
12646        protected EphemeralResponse[] newArray(int size) {
12647            return new EphemeralResponse[size];
12648        }
12649
12650        @Override
12651        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12652            return true;
12653        }
12654
12655        @Override
12656        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12657                int userId) {
12658            if (!sUserManager.exists(userId)) {
12659                return null;
12660            }
12661            final String packageName = responseObj.resolveInfo.getPackageName();
12662            final Integer order = responseObj.getOrder();
12663            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12664                    mOrderResult.get(packageName);
12665            // ordering is enabled and this item's order isn't high enough
12666            if (lastOrderResult != null && lastOrderResult.first >= order) {
12667                return null;
12668            }
12669            final EphemeralResolveInfo res = responseObj.resolveInfo;
12670            if (order > 0) {
12671                // non-zero order, enable ordering
12672                mOrderResult.put(packageName, new Pair<>(order, res));
12673            }
12674            return responseObj;
12675        }
12676
12677        @Override
12678        protected void filterResults(List<EphemeralResponse> results) {
12679            // only do work if ordering is enabled [most of the time it won't be]
12680            if (mOrderResult.size() == 0) {
12681                return;
12682            }
12683            int resultSize = results.size();
12684            for (int i = 0; i < resultSize; i++) {
12685                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12686                final String packageName = info.getPackageName();
12687                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12688                if (savedInfo == null) {
12689                    // package doesn't having ordering
12690                    continue;
12691                }
12692                if (savedInfo.second == info) {
12693                    // circled back to the highest ordered item; remove from order list
12694                    mOrderResult.remove(savedInfo);
12695                    if (mOrderResult.size() == 0) {
12696                        // no more ordered items
12697                        break;
12698                    }
12699                    continue;
12700                }
12701                // item has a worse order, remove it from the result list
12702                results.remove(i);
12703                resultSize--;
12704                i--;
12705            }
12706        }
12707    }
12708
12709    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12710            new Comparator<ResolveInfo>() {
12711        public int compare(ResolveInfo r1, ResolveInfo r2) {
12712            int v1 = r1.priority;
12713            int v2 = r2.priority;
12714            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12715            if (v1 != v2) {
12716                return (v1 > v2) ? -1 : 1;
12717            }
12718            v1 = r1.preferredOrder;
12719            v2 = r2.preferredOrder;
12720            if (v1 != v2) {
12721                return (v1 > v2) ? -1 : 1;
12722            }
12723            if (r1.isDefault != r2.isDefault) {
12724                return r1.isDefault ? -1 : 1;
12725            }
12726            v1 = r1.match;
12727            v2 = r2.match;
12728            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12729            if (v1 != v2) {
12730                return (v1 > v2) ? -1 : 1;
12731            }
12732            if (r1.system != r2.system) {
12733                return r1.system ? -1 : 1;
12734            }
12735            if (r1.activityInfo != null) {
12736                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12737            }
12738            if (r1.serviceInfo != null) {
12739                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12740            }
12741            if (r1.providerInfo != null) {
12742                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12743            }
12744            return 0;
12745        }
12746    };
12747
12748    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12749            new Comparator<ProviderInfo>() {
12750        public int compare(ProviderInfo p1, ProviderInfo p2) {
12751            final int v1 = p1.initOrder;
12752            final int v2 = p2.initOrder;
12753            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12754        }
12755    };
12756
12757    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12758            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12759            final int[] userIds) {
12760        mHandler.post(new Runnable() {
12761            @Override
12762            public void run() {
12763                try {
12764                    final IActivityManager am = ActivityManager.getService();
12765                    if (am == null) return;
12766                    final int[] resolvedUserIds;
12767                    if (userIds == null) {
12768                        resolvedUserIds = am.getRunningUserIds();
12769                    } else {
12770                        resolvedUserIds = userIds;
12771                    }
12772                    for (int id : resolvedUserIds) {
12773                        final Intent intent = new Intent(action,
12774                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12775                        if (extras != null) {
12776                            intent.putExtras(extras);
12777                        }
12778                        if (targetPkg != null) {
12779                            intent.setPackage(targetPkg);
12780                        }
12781                        // Modify the UID when posting to other users
12782                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12783                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12784                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12785                            intent.putExtra(Intent.EXTRA_UID, uid);
12786                        }
12787                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12788                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12789                        if (DEBUG_BROADCASTS) {
12790                            RuntimeException here = new RuntimeException("here");
12791                            here.fillInStackTrace();
12792                            Slog.d(TAG, "Sending to user " + id + ": "
12793                                    + intent.toShortString(false, true, false, false)
12794                                    + " " + intent.getExtras(), here);
12795                        }
12796                        am.broadcastIntent(null, intent, null, finishedReceiver,
12797                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12798                                null, finishedReceiver != null, false, id);
12799                    }
12800                } catch (RemoteException ex) {
12801                }
12802            }
12803        });
12804    }
12805
12806    /**
12807     * Check if the external storage media is available. This is true if there
12808     * is a mounted external storage medium or if the external storage is
12809     * emulated.
12810     */
12811    private boolean isExternalMediaAvailable() {
12812        return mMediaMounted || Environment.isExternalStorageEmulated();
12813    }
12814
12815    @Override
12816    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12817        // writer
12818        synchronized (mPackages) {
12819            if (!isExternalMediaAvailable()) {
12820                // If the external storage is no longer mounted at this point,
12821                // the caller may not have been able to delete all of this
12822                // packages files and can not delete any more.  Bail.
12823                return null;
12824            }
12825            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12826            if (lastPackage != null) {
12827                pkgs.remove(lastPackage);
12828            }
12829            if (pkgs.size() > 0) {
12830                return pkgs.get(0);
12831            }
12832        }
12833        return null;
12834    }
12835
12836    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12837        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12838                userId, andCode ? 1 : 0, packageName);
12839        if (mSystemReady) {
12840            msg.sendToTarget();
12841        } else {
12842            if (mPostSystemReadyMessages == null) {
12843                mPostSystemReadyMessages = new ArrayList<>();
12844            }
12845            mPostSystemReadyMessages.add(msg);
12846        }
12847    }
12848
12849    void startCleaningPackages() {
12850        // reader
12851        if (!isExternalMediaAvailable()) {
12852            return;
12853        }
12854        synchronized (mPackages) {
12855            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12856                return;
12857            }
12858        }
12859        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12860        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12861        IActivityManager am = ActivityManager.getService();
12862        if (am != null) {
12863            try {
12864                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12865                        UserHandle.USER_SYSTEM);
12866            } catch (RemoteException e) {
12867            }
12868        }
12869    }
12870
12871    @Override
12872    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12873            int installFlags, String installerPackageName, int userId) {
12874        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12875
12876        final int callingUid = Binder.getCallingUid();
12877        enforceCrossUserPermission(callingUid, userId,
12878                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12879
12880        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12881            try {
12882                if (observer != null) {
12883                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12884                }
12885            } catch (RemoteException re) {
12886            }
12887            return;
12888        }
12889
12890        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12891            installFlags |= PackageManager.INSTALL_FROM_ADB;
12892
12893        } else {
12894            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12895            // about installerPackageName.
12896
12897            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12898            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12899        }
12900
12901        UserHandle user;
12902        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12903            user = UserHandle.ALL;
12904        } else {
12905            user = new UserHandle(userId);
12906        }
12907
12908        // Only system components can circumvent runtime permissions when installing.
12909        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12910                && mContext.checkCallingOrSelfPermission(Manifest.permission
12911                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12912            throw new SecurityException("You need the "
12913                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12914                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12915        }
12916
12917        final File originFile = new File(originPath);
12918        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12919
12920        final Message msg = mHandler.obtainMessage(INIT_COPY);
12921        final VerificationInfo verificationInfo = new VerificationInfo(
12922                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12923        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12924                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12925                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12926                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12927        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12928        msg.obj = params;
12929
12930        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12931                System.identityHashCode(msg.obj));
12932        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12933                System.identityHashCode(msg.obj));
12934
12935        mHandler.sendMessage(msg);
12936    }
12937
12938
12939    /**
12940     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12941     * it is acting on behalf on an enterprise or the user).
12942     *
12943     * Note that the ordering of the conditionals in this method is important. The checks we perform
12944     * are as follows, in this order:
12945     *
12946     * 1) If the install is being performed by a system app, we can trust the app to have set the
12947     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12948     *    what it is.
12949     * 2) If the install is being performed by a device or profile owner app, the install reason
12950     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12951     *    set the install reason correctly. If the app targets an older SDK version where install
12952     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12953     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12954     * 3) In all other cases, the install is being performed by a regular app that is neither part
12955     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12956     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12957     *    set to enterprise policy and if so, change it to unknown instead.
12958     */
12959    private int fixUpInstallReason(String installerPackageName, int installerUid,
12960            int installReason) {
12961        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12962                == PERMISSION_GRANTED) {
12963            // If the install is being performed by a system app, we trust that app to have set the
12964            // install reason correctly.
12965            return installReason;
12966        }
12967
12968        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12969            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12970        if (dpm != null) {
12971            ComponentName owner = null;
12972            try {
12973                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12974                if (owner == null) {
12975                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12976                }
12977            } catch (RemoteException e) {
12978            }
12979            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12980                // If the install is being performed by a device or profile owner, the install
12981                // reason should be enterprise policy.
12982                return PackageManager.INSTALL_REASON_POLICY;
12983            }
12984        }
12985
12986        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12987            // If the install is being performed by a regular app (i.e. neither system app nor
12988            // device or profile owner), we have no reason to believe that the app is acting on
12989            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12990            // change it to unknown instead.
12991            return PackageManager.INSTALL_REASON_UNKNOWN;
12992        }
12993
12994        // If the install is being performed by a regular app and the install reason was set to any
12995        // value but enterprise policy, leave the install reason unchanged.
12996        return installReason;
12997    }
12998
12999    void installStage(String packageName, File stagedDir, String stagedCid,
13000            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13001            String installerPackageName, int installerUid, UserHandle user,
13002            Certificate[][] certificates) {
13003        if (DEBUG_EPHEMERAL) {
13004            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13005                Slog.d(TAG, "Ephemeral install of " + packageName);
13006            }
13007        }
13008        final VerificationInfo verificationInfo = new VerificationInfo(
13009                sessionParams.originatingUri, sessionParams.referrerUri,
13010                sessionParams.originatingUid, installerUid);
13011
13012        final OriginInfo origin;
13013        if (stagedDir != null) {
13014            origin = OriginInfo.fromStagedFile(stagedDir);
13015        } else {
13016            origin = OriginInfo.fromStagedContainer(stagedCid);
13017        }
13018
13019        final Message msg = mHandler.obtainMessage(INIT_COPY);
13020        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13021                sessionParams.installReason);
13022        final InstallParams params = new InstallParams(origin, null, observer,
13023                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13024                verificationInfo, user, sessionParams.abiOverride,
13025                sessionParams.grantedRuntimePermissions, certificates, installReason);
13026        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13027        msg.obj = params;
13028
13029        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13030                System.identityHashCode(msg.obj));
13031        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13032                System.identityHashCode(msg.obj));
13033
13034        mHandler.sendMessage(msg);
13035    }
13036
13037    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13038            int userId) {
13039        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13040        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13041    }
13042
13043    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13044            int appId, int... userIds) {
13045        if (ArrayUtils.isEmpty(userIds)) {
13046            return;
13047        }
13048        Bundle extras = new Bundle(1);
13049        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13050        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13051
13052        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13053                packageName, extras, 0, null, null, userIds);
13054        if (isSystem) {
13055            mHandler.post(() -> {
13056                        for (int userId : userIds) {
13057                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13058                        }
13059                    }
13060            );
13061        }
13062    }
13063
13064    /**
13065     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13066     * automatically without needing an explicit launch.
13067     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13068     */
13069    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13070        // If user is not running, the app didn't miss any broadcast
13071        if (!mUserManagerInternal.isUserRunning(userId)) {
13072            return;
13073        }
13074        final IActivityManager am = ActivityManager.getService();
13075        try {
13076            // Deliver LOCKED_BOOT_COMPLETED first
13077            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13078                    .setPackage(packageName);
13079            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13080            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13081                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13082
13083            // Deliver BOOT_COMPLETED only if user is unlocked
13084            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13085                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13086                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13087                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13088            }
13089        } catch (RemoteException e) {
13090            throw e.rethrowFromSystemServer();
13091        }
13092    }
13093
13094    @Override
13095    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13096            int userId) {
13097        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13098        PackageSetting pkgSetting;
13099        final int uid = Binder.getCallingUid();
13100        enforceCrossUserPermission(uid, userId,
13101                true /* requireFullPermission */, true /* checkShell */,
13102                "setApplicationHiddenSetting for user " + userId);
13103
13104        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13105            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13106            return false;
13107        }
13108
13109        long callingId = Binder.clearCallingIdentity();
13110        try {
13111            boolean sendAdded = false;
13112            boolean sendRemoved = false;
13113            // writer
13114            synchronized (mPackages) {
13115                pkgSetting = mSettings.mPackages.get(packageName);
13116                if (pkgSetting == null) {
13117                    return false;
13118                }
13119                // Do not allow "android" is being disabled
13120                if ("android".equals(packageName)) {
13121                    Slog.w(TAG, "Cannot hide package: android");
13122                    return false;
13123                }
13124                // Cannot hide static shared libs as they are considered
13125                // a part of the using app (emulating static linking). Also
13126                // static libs are installed always on internal storage.
13127                PackageParser.Package pkg = mPackages.get(packageName);
13128                if (pkg != null && pkg.staticSharedLibName != null) {
13129                    Slog.w(TAG, "Cannot hide package: " + packageName
13130                            + " providing static shared library: "
13131                            + pkg.staticSharedLibName);
13132                    return false;
13133                }
13134                // Only allow protected packages to hide themselves.
13135                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13136                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13137                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13138                    return false;
13139                }
13140
13141                if (pkgSetting.getHidden(userId) != hidden) {
13142                    pkgSetting.setHidden(hidden, userId);
13143                    mSettings.writePackageRestrictionsLPr(userId);
13144                    if (hidden) {
13145                        sendRemoved = true;
13146                    } else {
13147                        sendAdded = true;
13148                    }
13149                }
13150            }
13151            if (sendAdded) {
13152                sendPackageAddedForUser(packageName, pkgSetting, userId);
13153                return true;
13154            }
13155            if (sendRemoved) {
13156                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13157                        "hiding pkg");
13158                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13159                return true;
13160            }
13161        } finally {
13162            Binder.restoreCallingIdentity(callingId);
13163        }
13164        return false;
13165    }
13166
13167    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13168            int userId) {
13169        final PackageRemovedInfo info = new PackageRemovedInfo();
13170        info.removedPackage = packageName;
13171        info.removedUsers = new int[] {userId};
13172        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13173        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13174    }
13175
13176    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13177        if (pkgList.length > 0) {
13178            Bundle extras = new Bundle(1);
13179            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13180
13181            sendPackageBroadcast(
13182                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13183                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13184                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13185                    new int[] {userId});
13186        }
13187    }
13188
13189    /**
13190     * Returns true if application is not found or there was an error. Otherwise it returns
13191     * the hidden state of the package for the given user.
13192     */
13193    @Override
13194    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13195        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13196        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13197                true /* requireFullPermission */, false /* checkShell */,
13198                "getApplicationHidden for user " + userId);
13199        PackageSetting pkgSetting;
13200        long callingId = Binder.clearCallingIdentity();
13201        try {
13202            // writer
13203            synchronized (mPackages) {
13204                pkgSetting = mSettings.mPackages.get(packageName);
13205                if (pkgSetting == null) {
13206                    return true;
13207                }
13208                return pkgSetting.getHidden(userId);
13209            }
13210        } finally {
13211            Binder.restoreCallingIdentity(callingId);
13212        }
13213    }
13214
13215    /**
13216     * @hide
13217     */
13218    @Override
13219    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
13220        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13221                null);
13222        PackageSetting pkgSetting;
13223        final int uid = Binder.getCallingUid();
13224        enforceCrossUserPermission(uid, userId,
13225                true /* requireFullPermission */, true /* checkShell */,
13226                "installExistingPackage for user " + userId);
13227        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13228            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13229        }
13230
13231        long callingId = Binder.clearCallingIdentity();
13232        try {
13233            boolean installed = false;
13234
13235            // writer
13236            synchronized (mPackages) {
13237                pkgSetting = mSettings.mPackages.get(packageName);
13238                if (pkgSetting == null) {
13239                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13240                }
13241                if (!pkgSetting.getInstalled(userId)) {
13242                    pkgSetting.setInstalled(true, userId);
13243                    pkgSetting.setHidden(false, userId);
13244                    pkgSetting.setInstallReason(installReason, userId);
13245                    mSettings.writePackageRestrictionsLPr(userId);
13246                    installed = true;
13247                }
13248            }
13249
13250            if (installed) {
13251                if (pkgSetting.pkg != null) {
13252                    synchronized (mInstallLock) {
13253                        // We don't need to freeze for a brand new install
13254                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13255                    }
13256                }
13257                sendPackageAddedForUser(packageName, pkgSetting, userId);
13258            }
13259        } finally {
13260            Binder.restoreCallingIdentity(callingId);
13261        }
13262
13263        return PackageManager.INSTALL_SUCCEEDED;
13264    }
13265
13266    boolean isUserRestricted(int userId, String restrictionKey) {
13267        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13268        if (restrictions.getBoolean(restrictionKey, false)) {
13269            Log.w(TAG, "User is restricted: " + restrictionKey);
13270            return true;
13271        }
13272        return false;
13273    }
13274
13275    @Override
13276    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13277            int userId) {
13278        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13279        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13280                true /* requireFullPermission */, true /* checkShell */,
13281                "setPackagesSuspended for user " + userId);
13282
13283        if (ArrayUtils.isEmpty(packageNames)) {
13284            return packageNames;
13285        }
13286
13287        // List of package names for whom the suspended state has changed.
13288        List<String> changedPackages = new ArrayList<>(packageNames.length);
13289        // List of package names for whom the suspended state is not set as requested in this
13290        // method.
13291        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13292        long callingId = Binder.clearCallingIdentity();
13293        try {
13294            for (int i = 0; i < packageNames.length; i++) {
13295                String packageName = packageNames[i];
13296                boolean changed = false;
13297                final int appId;
13298                synchronized (mPackages) {
13299                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13300                    if (pkgSetting == null) {
13301                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13302                                + "\". Skipping suspending/un-suspending.");
13303                        unactionedPackages.add(packageName);
13304                        continue;
13305                    }
13306                    appId = pkgSetting.appId;
13307                    if (pkgSetting.getSuspended(userId) != suspended) {
13308                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13309                            unactionedPackages.add(packageName);
13310                            continue;
13311                        }
13312                        pkgSetting.setSuspended(suspended, userId);
13313                        mSettings.writePackageRestrictionsLPr(userId);
13314                        changed = true;
13315                        changedPackages.add(packageName);
13316                    }
13317                }
13318
13319                if (changed && suspended) {
13320                    killApplication(packageName, UserHandle.getUid(userId, appId),
13321                            "suspending package");
13322                }
13323            }
13324        } finally {
13325            Binder.restoreCallingIdentity(callingId);
13326        }
13327
13328        if (!changedPackages.isEmpty()) {
13329            sendPackagesSuspendedForUser(changedPackages.toArray(
13330                    new String[changedPackages.size()]), userId, suspended);
13331        }
13332
13333        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13334    }
13335
13336    @Override
13337    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13338        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13339                true /* requireFullPermission */, false /* checkShell */,
13340                "isPackageSuspendedForUser for user " + userId);
13341        synchronized (mPackages) {
13342            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13343            if (pkgSetting == null) {
13344                throw new IllegalArgumentException("Unknown target package: " + packageName);
13345            }
13346            return pkgSetting.getSuspended(userId);
13347        }
13348    }
13349
13350    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13351        if (isPackageDeviceAdmin(packageName, userId)) {
13352            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13353                    + "\": has an active device admin");
13354            return false;
13355        }
13356
13357        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13358        if (packageName.equals(activeLauncherPackageName)) {
13359            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13360                    + "\": contains the active launcher");
13361            return false;
13362        }
13363
13364        if (packageName.equals(mRequiredInstallerPackage)) {
13365            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13366                    + "\": required for package installation");
13367            return false;
13368        }
13369
13370        if (packageName.equals(mRequiredUninstallerPackage)) {
13371            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13372                    + "\": required for package uninstallation");
13373            return false;
13374        }
13375
13376        if (packageName.equals(mRequiredVerifierPackage)) {
13377            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13378                    + "\": required for package verification");
13379            return false;
13380        }
13381
13382        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13383            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13384                    + "\": is the default dialer");
13385            return false;
13386        }
13387
13388        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13389            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13390                    + "\": protected package");
13391            return false;
13392        }
13393
13394        // Cannot suspend static shared libs as they are considered
13395        // a part of the using app (emulating static linking). Also
13396        // static libs are installed always on internal storage.
13397        PackageParser.Package pkg = mPackages.get(packageName);
13398        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13399            Slog.w(TAG, "Cannot suspend package: " + packageName
13400                    + " providing static shared library: "
13401                    + pkg.staticSharedLibName);
13402            return false;
13403        }
13404
13405        return true;
13406    }
13407
13408    private String getActiveLauncherPackageName(int userId) {
13409        Intent intent = new Intent(Intent.ACTION_MAIN);
13410        intent.addCategory(Intent.CATEGORY_HOME);
13411        ResolveInfo resolveInfo = resolveIntent(
13412                intent,
13413                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13414                PackageManager.MATCH_DEFAULT_ONLY,
13415                userId);
13416
13417        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13418    }
13419
13420    private String getDefaultDialerPackageName(int userId) {
13421        synchronized (mPackages) {
13422            return mSettings.getDefaultDialerPackageNameLPw(userId);
13423        }
13424    }
13425
13426    @Override
13427    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13428        mContext.enforceCallingOrSelfPermission(
13429                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13430                "Only package verification agents can verify applications");
13431
13432        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13433        final PackageVerificationResponse response = new PackageVerificationResponse(
13434                verificationCode, Binder.getCallingUid());
13435        msg.arg1 = id;
13436        msg.obj = response;
13437        mHandler.sendMessage(msg);
13438    }
13439
13440    @Override
13441    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13442            long millisecondsToDelay) {
13443        mContext.enforceCallingOrSelfPermission(
13444                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13445                "Only package verification agents can extend verification timeouts");
13446
13447        final PackageVerificationState state = mPendingVerification.get(id);
13448        final PackageVerificationResponse response = new PackageVerificationResponse(
13449                verificationCodeAtTimeout, Binder.getCallingUid());
13450
13451        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13452            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13453        }
13454        if (millisecondsToDelay < 0) {
13455            millisecondsToDelay = 0;
13456        }
13457        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13458                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13459            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13460        }
13461
13462        if ((state != null) && !state.timeoutExtended()) {
13463            state.extendTimeout();
13464
13465            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13466            msg.arg1 = id;
13467            msg.obj = response;
13468            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13469        }
13470    }
13471
13472    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13473            int verificationCode, UserHandle user) {
13474        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13475        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13476        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13477        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13478        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13479
13480        mContext.sendBroadcastAsUser(intent, user,
13481                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13482    }
13483
13484    private ComponentName matchComponentForVerifier(String packageName,
13485            List<ResolveInfo> receivers) {
13486        ActivityInfo targetReceiver = null;
13487
13488        final int NR = receivers.size();
13489        for (int i = 0; i < NR; i++) {
13490            final ResolveInfo info = receivers.get(i);
13491            if (info.activityInfo == null) {
13492                continue;
13493            }
13494
13495            if (packageName.equals(info.activityInfo.packageName)) {
13496                targetReceiver = info.activityInfo;
13497                break;
13498            }
13499        }
13500
13501        if (targetReceiver == null) {
13502            return null;
13503        }
13504
13505        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13506    }
13507
13508    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13509            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13510        if (pkgInfo.verifiers.length == 0) {
13511            return null;
13512        }
13513
13514        final int N = pkgInfo.verifiers.length;
13515        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13516        for (int i = 0; i < N; i++) {
13517            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13518
13519            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13520                    receivers);
13521            if (comp == null) {
13522                continue;
13523            }
13524
13525            final int verifierUid = getUidForVerifier(verifierInfo);
13526            if (verifierUid == -1) {
13527                continue;
13528            }
13529
13530            if (DEBUG_VERIFY) {
13531                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13532                        + " with the correct signature");
13533            }
13534            sufficientVerifiers.add(comp);
13535            verificationState.addSufficientVerifier(verifierUid);
13536        }
13537
13538        return sufficientVerifiers;
13539    }
13540
13541    private int getUidForVerifier(VerifierInfo verifierInfo) {
13542        synchronized (mPackages) {
13543            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13544            if (pkg == null) {
13545                return -1;
13546            } else if (pkg.mSignatures.length != 1) {
13547                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13548                        + " has more than one signature; ignoring");
13549                return -1;
13550            }
13551
13552            /*
13553             * If the public key of the package's signature does not match
13554             * our expected public key, then this is a different package and
13555             * we should skip.
13556             */
13557
13558            final byte[] expectedPublicKey;
13559            try {
13560                final Signature verifierSig = pkg.mSignatures[0];
13561                final PublicKey publicKey = verifierSig.getPublicKey();
13562                expectedPublicKey = publicKey.getEncoded();
13563            } catch (CertificateException e) {
13564                return -1;
13565            }
13566
13567            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13568
13569            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13570                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13571                        + " does not have the expected public key; ignoring");
13572                return -1;
13573            }
13574
13575            return pkg.applicationInfo.uid;
13576        }
13577    }
13578
13579    @Override
13580    public void finishPackageInstall(int token, boolean didLaunch) {
13581        enforceSystemOrRoot("Only the system is allowed to finish installs");
13582
13583        if (DEBUG_INSTALL) {
13584            Slog.v(TAG, "BM finishing package install for " + token);
13585        }
13586        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13587
13588        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13589        mHandler.sendMessage(msg);
13590    }
13591
13592    /**
13593     * Get the verification agent timeout.
13594     *
13595     * @return verification timeout in milliseconds
13596     */
13597    private long getVerificationTimeout() {
13598        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13599                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13600                DEFAULT_VERIFICATION_TIMEOUT);
13601    }
13602
13603    /**
13604     * Get the default verification agent response code.
13605     *
13606     * @return default verification response code
13607     */
13608    private int getDefaultVerificationResponse() {
13609        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13610                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13611                DEFAULT_VERIFICATION_RESPONSE);
13612    }
13613
13614    /**
13615     * Check whether or not package verification has been enabled.
13616     *
13617     * @return true if verification should be performed
13618     */
13619    private boolean isVerificationEnabled(int userId, int installFlags) {
13620        if (!DEFAULT_VERIFY_ENABLE) {
13621            return false;
13622        }
13623        // Ephemeral apps don't get the full verification treatment
13624        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13625            if (DEBUG_EPHEMERAL) {
13626                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13627            }
13628            return false;
13629        }
13630
13631        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13632
13633        // Check if installing from ADB
13634        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13635            // Do not run verification in a test harness environment
13636            if (ActivityManager.isRunningInTestHarness()) {
13637                return false;
13638            }
13639            if (ensureVerifyAppsEnabled) {
13640                return true;
13641            }
13642            // Check if the developer does not want package verification for ADB installs
13643            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13644                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13645                return false;
13646            }
13647        }
13648
13649        if (ensureVerifyAppsEnabled) {
13650            return true;
13651        }
13652
13653        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13654                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13655    }
13656
13657    @Override
13658    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13659            throws RemoteException {
13660        mContext.enforceCallingOrSelfPermission(
13661                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13662                "Only intentfilter verification agents can verify applications");
13663
13664        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13665        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13666                Binder.getCallingUid(), verificationCode, failedDomains);
13667        msg.arg1 = id;
13668        msg.obj = response;
13669        mHandler.sendMessage(msg);
13670    }
13671
13672    @Override
13673    public int getIntentVerificationStatus(String packageName, int userId) {
13674        synchronized (mPackages) {
13675            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13676        }
13677    }
13678
13679    @Override
13680    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13681        mContext.enforceCallingOrSelfPermission(
13682                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13683
13684        boolean result = false;
13685        synchronized (mPackages) {
13686            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13687        }
13688        if (result) {
13689            scheduleWritePackageRestrictionsLocked(userId);
13690        }
13691        return result;
13692    }
13693
13694    @Override
13695    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13696            String packageName) {
13697        synchronized (mPackages) {
13698            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13699        }
13700    }
13701
13702    @Override
13703    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13704        if (TextUtils.isEmpty(packageName)) {
13705            return ParceledListSlice.emptyList();
13706        }
13707        synchronized (mPackages) {
13708            PackageParser.Package pkg = mPackages.get(packageName);
13709            if (pkg == null || pkg.activities == null) {
13710                return ParceledListSlice.emptyList();
13711            }
13712            final int count = pkg.activities.size();
13713            ArrayList<IntentFilter> result = new ArrayList<>();
13714            for (int n=0; n<count; n++) {
13715                PackageParser.Activity activity = pkg.activities.get(n);
13716                if (activity.intents != null && activity.intents.size() > 0) {
13717                    result.addAll(activity.intents);
13718                }
13719            }
13720            return new ParceledListSlice<>(result);
13721        }
13722    }
13723
13724    @Override
13725    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13726        mContext.enforceCallingOrSelfPermission(
13727                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13728
13729        synchronized (mPackages) {
13730            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13731            if (packageName != null) {
13732                result |= updateIntentVerificationStatus(packageName,
13733                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13734                        userId);
13735                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13736                        packageName, userId);
13737            }
13738            return result;
13739        }
13740    }
13741
13742    @Override
13743    public String getDefaultBrowserPackageName(int userId) {
13744        synchronized (mPackages) {
13745            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13746        }
13747    }
13748
13749    /**
13750     * Get the "allow unknown sources" setting.
13751     *
13752     * @return the current "allow unknown sources" setting
13753     */
13754    private int getUnknownSourcesSettings() {
13755        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13756                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13757                -1);
13758    }
13759
13760    @Override
13761    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13762        final int uid = Binder.getCallingUid();
13763        // writer
13764        synchronized (mPackages) {
13765            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13766            if (targetPackageSetting == null) {
13767                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13768            }
13769
13770            PackageSetting installerPackageSetting;
13771            if (installerPackageName != null) {
13772                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13773                if (installerPackageSetting == null) {
13774                    throw new IllegalArgumentException("Unknown installer package: "
13775                            + installerPackageName);
13776                }
13777            } else {
13778                installerPackageSetting = null;
13779            }
13780
13781            Signature[] callerSignature;
13782            Object obj = mSettings.getUserIdLPr(uid);
13783            if (obj != null) {
13784                if (obj instanceof SharedUserSetting) {
13785                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13786                } else if (obj instanceof PackageSetting) {
13787                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13788                } else {
13789                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13790                }
13791            } else {
13792                throw new SecurityException("Unknown calling UID: " + uid);
13793            }
13794
13795            // Verify: can't set installerPackageName to a package that is
13796            // not signed with the same cert as the caller.
13797            if (installerPackageSetting != null) {
13798                if (compareSignatures(callerSignature,
13799                        installerPackageSetting.signatures.mSignatures)
13800                        != PackageManager.SIGNATURE_MATCH) {
13801                    throw new SecurityException(
13802                            "Caller does not have same cert as new installer package "
13803                            + installerPackageName);
13804                }
13805            }
13806
13807            // Verify: if target already has an installer package, it must
13808            // be signed with the same cert as the caller.
13809            if (targetPackageSetting.installerPackageName != null) {
13810                PackageSetting setting = mSettings.mPackages.get(
13811                        targetPackageSetting.installerPackageName);
13812                // If the currently set package isn't valid, then it's always
13813                // okay to change it.
13814                if (setting != null) {
13815                    if (compareSignatures(callerSignature,
13816                            setting.signatures.mSignatures)
13817                            != PackageManager.SIGNATURE_MATCH) {
13818                        throw new SecurityException(
13819                                "Caller does not have same cert as old installer package "
13820                                + targetPackageSetting.installerPackageName);
13821                    }
13822                }
13823            }
13824
13825            // Okay!
13826            targetPackageSetting.installerPackageName = installerPackageName;
13827            if (installerPackageName != null) {
13828                mSettings.mInstallerPackages.add(installerPackageName);
13829            }
13830            scheduleWriteSettingsLocked();
13831        }
13832    }
13833
13834    @Override
13835    public void setApplicationCategoryHint(String packageName, int categoryHint,
13836            String callerPackageName) {
13837        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13838                callerPackageName);
13839        synchronized (mPackages) {
13840            PackageSetting ps = mSettings.mPackages.get(packageName);
13841            if (ps == null) {
13842                throw new IllegalArgumentException("Unknown target package " + packageName);
13843            }
13844
13845            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13846                throw new IllegalArgumentException("Calling package " + callerPackageName
13847                        + " is not installer for " + packageName);
13848            }
13849
13850            if (ps.categoryHint != categoryHint) {
13851                ps.categoryHint = categoryHint;
13852                scheduleWriteSettingsLocked();
13853            }
13854        }
13855    }
13856
13857    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13858        // Queue up an async operation since the package installation may take a little while.
13859        mHandler.post(new Runnable() {
13860            public void run() {
13861                mHandler.removeCallbacks(this);
13862                 // Result object to be returned
13863                PackageInstalledInfo res = new PackageInstalledInfo();
13864                res.setReturnCode(currentStatus);
13865                res.uid = -1;
13866                res.pkg = null;
13867                res.removedInfo = null;
13868                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13869                    args.doPreInstall(res.returnCode);
13870                    synchronized (mInstallLock) {
13871                        installPackageTracedLI(args, res);
13872                    }
13873                    args.doPostInstall(res.returnCode, res.uid);
13874                }
13875
13876                // A restore should be performed at this point if (a) the install
13877                // succeeded, (b) the operation is not an update, and (c) the new
13878                // package has not opted out of backup participation.
13879                final boolean update = res.removedInfo != null
13880                        && res.removedInfo.removedPackage != null;
13881                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13882                boolean doRestore = !update
13883                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13884
13885                // Set up the post-install work request bookkeeping.  This will be used
13886                // and cleaned up by the post-install event handling regardless of whether
13887                // there's a restore pass performed.  Token values are >= 1.
13888                int token;
13889                if (mNextInstallToken < 0) mNextInstallToken = 1;
13890                token = mNextInstallToken++;
13891
13892                PostInstallData data = new PostInstallData(args, res);
13893                mRunningInstalls.put(token, data);
13894                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13895
13896                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13897                    // Pass responsibility to the Backup Manager.  It will perform a
13898                    // restore if appropriate, then pass responsibility back to the
13899                    // Package Manager to run the post-install observer callbacks
13900                    // and broadcasts.
13901                    IBackupManager bm = IBackupManager.Stub.asInterface(
13902                            ServiceManager.getService(Context.BACKUP_SERVICE));
13903                    if (bm != null) {
13904                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13905                                + " to BM for possible restore");
13906                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13907                        try {
13908                            // TODO: http://b/22388012
13909                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13910                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13911                            } else {
13912                                doRestore = false;
13913                            }
13914                        } catch (RemoteException e) {
13915                            // can't happen; the backup manager is local
13916                        } catch (Exception e) {
13917                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13918                            doRestore = false;
13919                        }
13920                    } else {
13921                        Slog.e(TAG, "Backup Manager not found!");
13922                        doRestore = false;
13923                    }
13924                }
13925
13926                if (!doRestore) {
13927                    // No restore possible, or the Backup Manager was mysteriously not
13928                    // available -- just fire the post-install work request directly.
13929                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13930
13931                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13932
13933                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13934                    mHandler.sendMessage(msg);
13935                }
13936            }
13937        });
13938    }
13939
13940    /**
13941     * Callback from PackageSettings whenever an app is first transitioned out of the
13942     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13943     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13944     * here whether the app is the target of an ongoing install, and only send the
13945     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13946     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13947     * handling.
13948     */
13949    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13950        // Serialize this with the rest of the install-process message chain.  In the
13951        // restore-at-install case, this Runnable will necessarily run before the
13952        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13953        // are coherent.  In the non-restore case, the app has already completed install
13954        // and been launched through some other means, so it is not in a problematic
13955        // state for observers to see the FIRST_LAUNCH signal.
13956        mHandler.post(new Runnable() {
13957            @Override
13958            public void run() {
13959                for (int i = 0; i < mRunningInstalls.size(); i++) {
13960                    final PostInstallData data = mRunningInstalls.valueAt(i);
13961                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13962                        continue;
13963                    }
13964                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13965                        // right package; but is it for the right user?
13966                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13967                            if (userId == data.res.newUsers[uIndex]) {
13968                                if (DEBUG_BACKUP) {
13969                                    Slog.i(TAG, "Package " + pkgName
13970                                            + " being restored so deferring FIRST_LAUNCH");
13971                                }
13972                                return;
13973                            }
13974                        }
13975                    }
13976                }
13977                // didn't find it, so not being restored
13978                if (DEBUG_BACKUP) {
13979                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13980                }
13981                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13982            }
13983        });
13984    }
13985
13986    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13987        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13988                installerPkg, null, userIds);
13989    }
13990
13991    private abstract class HandlerParams {
13992        private static final int MAX_RETRIES = 4;
13993
13994        /**
13995         * Number of times startCopy() has been attempted and had a non-fatal
13996         * error.
13997         */
13998        private int mRetries = 0;
13999
14000        /** User handle for the user requesting the information or installation. */
14001        private final UserHandle mUser;
14002        String traceMethod;
14003        int traceCookie;
14004
14005        HandlerParams(UserHandle user) {
14006            mUser = user;
14007        }
14008
14009        UserHandle getUser() {
14010            return mUser;
14011        }
14012
14013        HandlerParams setTraceMethod(String traceMethod) {
14014            this.traceMethod = traceMethod;
14015            return this;
14016        }
14017
14018        HandlerParams setTraceCookie(int traceCookie) {
14019            this.traceCookie = traceCookie;
14020            return this;
14021        }
14022
14023        final boolean startCopy() {
14024            boolean res;
14025            try {
14026                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14027
14028                if (++mRetries > MAX_RETRIES) {
14029                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14030                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14031                    handleServiceError();
14032                    return false;
14033                } else {
14034                    handleStartCopy();
14035                    res = true;
14036                }
14037            } catch (RemoteException e) {
14038                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14039                mHandler.sendEmptyMessage(MCS_RECONNECT);
14040                res = false;
14041            }
14042            handleReturnCode();
14043            return res;
14044        }
14045
14046        final void serviceError() {
14047            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14048            handleServiceError();
14049            handleReturnCode();
14050        }
14051
14052        abstract void handleStartCopy() throws RemoteException;
14053        abstract void handleServiceError();
14054        abstract void handleReturnCode();
14055    }
14056
14057    class MeasureParams extends HandlerParams {
14058        private final PackageStats mStats;
14059        private boolean mSuccess;
14060
14061        private final IPackageStatsObserver mObserver;
14062
14063        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14064            super(new UserHandle(stats.userHandle));
14065            mObserver = observer;
14066            mStats = stats;
14067        }
14068
14069        @Override
14070        public String toString() {
14071            return "MeasureParams{"
14072                + Integer.toHexString(System.identityHashCode(this))
14073                + " " + mStats.packageName + "}";
14074        }
14075
14076        @Override
14077        void handleStartCopy() throws RemoteException {
14078            synchronized (mInstallLock) {
14079                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14080            }
14081
14082            if (mSuccess) {
14083                boolean mounted = false;
14084                try {
14085                    final String status = Environment.getExternalStorageState();
14086                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14087                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14088                } catch (Exception e) {
14089                }
14090
14091                if (mounted) {
14092                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14093
14094                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14095                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14096
14097                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14098                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14099
14100                    // Always subtract cache size, since it's a subdirectory
14101                    mStats.externalDataSize -= mStats.externalCacheSize;
14102
14103                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14104                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14105
14106                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14107                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14108                }
14109            }
14110        }
14111
14112        @Override
14113        void handleReturnCode() {
14114            if (mObserver != null) {
14115                try {
14116                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14117                } catch (RemoteException e) {
14118                    Slog.i(TAG, "Observer no longer exists.");
14119                }
14120            }
14121        }
14122
14123        @Override
14124        void handleServiceError() {
14125            Slog.e(TAG, "Could not measure application " + mStats.packageName
14126                            + " external storage");
14127        }
14128    }
14129
14130    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14131            throws RemoteException {
14132        long result = 0;
14133        for (File path : paths) {
14134            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14135        }
14136        return result;
14137    }
14138
14139    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14140        for (File path : paths) {
14141            try {
14142                mcs.clearDirectory(path.getAbsolutePath());
14143            } catch (RemoteException e) {
14144            }
14145        }
14146    }
14147
14148    static class OriginInfo {
14149        /**
14150         * Location where install is coming from, before it has been
14151         * copied/renamed into place. This could be a single monolithic APK
14152         * file, or a cluster directory. This location may be untrusted.
14153         */
14154        final File file;
14155        final String cid;
14156
14157        /**
14158         * Flag indicating that {@link #file} or {@link #cid} has already been
14159         * staged, meaning downstream users don't need to defensively copy the
14160         * contents.
14161         */
14162        final boolean staged;
14163
14164        /**
14165         * Flag indicating that {@link #file} or {@link #cid} is an already
14166         * installed app that is being moved.
14167         */
14168        final boolean existing;
14169
14170        final String resolvedPath;
14171        final File resolvedFile;
14172
14173        static OriginInfo fromNothing() {
14174            return new OriginInfo(null, null, false, false);
14175        }
14176
14177        static OriginInfo fromUntrustedFile(File file) {
14178            return new OriginInfo(file, null, false, false);
14179        }
14180
14181        static OriginInfo fromExistingFile(File file) {
14182            return new OriginInfo(file, null, false, true);
14183        }
14184
14185        static OriginInfo fromStagedFile(File file) {
14186            return new OriginInfo(file, null, true, false);
14187        }
14188
14189        static OriginInfo fromStagedContainer(String cid) {
14190            return new OriginInfo(null, cid, true, false);
14191        }
14192
14193        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14194            this.file = file;
14195            this.cid = cid;
14196            this.staged = staged;
14197            this.existing = existing;
14198
14199            if (cid != null) {
14200                resolvedPath = PackageHelper.getSdDir(cid);
14201                resolvedFile = new File(resolvedPath);
14202            } else if (file != null) {
14203                resolvedPath = file.getAbsolutePath();
14204                resolvedFile = file;
14205            } else {
14206                resolvedPath = null;
14207                resolvedFile = null;
14208            }
14209        }
14210    }
14211
14212    static class MoveInfo {
14213        final int moveId;
14214        final String fromUuid;
14215        final String toUuid;
14216        final String packageName;
14217        final String dataAppName;
14218        final int appId;
14219        final String seinfo;
14220        final int targetSdkVersion;
14221
14222        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14223                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14224            this.moveId = moveId;
14225            this.fromUuid = fromUuid;
14226            this.toUuid = toUuid;
14227            this.packageName = packageName;
14228            this.dataAppName = dataAppName;
14229            this.appId = appId;
14230            this.seinfo = seinfo;
14231            this.targetSdkVersion = targetSdkVersion;
14232        }
14233    }
14234
14235    static class VerificationInfo {
14236        /** A constant used to indicate that a uid value is not present. */
14237        public static final int NO_UID = -1;
14238
14239        /** URI referencing where the package was downloaded from. */
14240        final Uri originatingUri;
14241
14242        /** HTTP referrer URI associated with the originatingURI. */
14243        final Uri referrer;
14244
14245        /** UID of the application that the install request originated from. */
14246        final int originatingUid;
14247
14248        /** UID of application requesting the install */
14249        final int installerUid;
14250
14251        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14252            this.originatingUri = originatingUri;
14253            this.referrer = referrer;
14254            this.originatingUid = originatingUid;
14255            this.installerUid = installerUid;
14256        }
14257    }
14258
14259    class InstallParams extends HandlerParams {
14260        final OriginInfo origin;
14261        final MoveInfo move;
14262        final IPackageInstallObserver2 observer;
14263        int installFlags;
14264        final String installerPackageName;
14265        final String volumeUuid;
14266        private InstallArgs mArgs;
14267        private int mRet;
14268        final String packageAbiOverride;
14269        final String[] grantedRuntimePermissions;
14270        final VerificationInfo verificationInfo;
14271        final Certificate[][] certificates;
14272        final int installReason;
14273
14274        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14275                int installFlags, String installerPackageName, String volumeUuid,
14276                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14277                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14278            super(user);
14279            this.origin = origin;
14280            this.move = move;
14281            this.observer = observer;
14282            this.installFlags = installFlags;
14283            this.installerPackageName = installerPackageName;
14284            this.volumeUuid = volumeUuid;
14285            this.verificationInfo = verificationInfo;
14286            this.packageAbiOverride = packageAbiOverride;
14287            this.grantedRuntimePermissions = grantedPermissions;
14288            this.certificates = certificates;
14289            this.installReason = installReason;
14290        }
14291
14292        @Override
14293        public String toString() {
14294            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14295                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14296        }
14297
14298        private int installLocationPolicy(PackageInfoLite pkgLite) {
14299            String packageName = pkgLite.packageName;
14300            int installLocation = pkgLite.installLocation;
14301            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14302            // reader
14303            synchronized (mPackages) {
14304                // Currently installed package which the new package is attempting to replace or
14305                // null if no such package is installed.
14306                PackageParser.Package installedPkg = mPackages.get(packageName);
14307                // Package which currently owns the data which the new package will own if installed.
14308                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14309                // will be null whereas dataOwnerPkg will contain information about the package
14310                // which was uninstalled while keeping its data.
14311                PackageParser.Package dataOwnerPkg = installedPkg;
14312                if (dataOwnerPkg  == null) {
14313                    PackageSetting ps = mSettings.mPackages.get(packageName);
14314                    if (ps != null) {
14315                        dataOwnerPkg = ps.pkg;
14316                    }
14317                }
14318
14319                if (dataOwnerPkg != null) {
14320                    // If installed, the package will get access to data left on the device by its
14321                    // predecessor. As a security measure, this is permited only if this is not a
14322                    // version downgrade or if the predecessor package is marked as debuggable and
14323                    // a downgrade is explicitly requested.
14324                    //
14325                    // On debuggable platform builds, downgrades are permitted even for
14326                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14327                    // not offer security guarantees and thus it's OK to disable some security
14328                    // mechanisms to make debugging/testing easier on those builds. However, even on
14329                    // debuggable builds downgrades of packages are permitted only if requested via
14330                    // installFlags. This is because we aim to keep the behavior of debuggable
14331                    // platform builds as close as possible to the behavior of non-debuggable
14332                    // platform builds.
14333                    final boolean downgradeRequested =
14334                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14335                    final boolean packageDebuggable =
14336                                (dataOwnerPkg.applicationInfo.flags
14337                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14338                    final boolean downgradePermitted =
14339                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14340                    if (!downgradePermitted) {
14341                        try {
14342                            checkDowngrade(dataOwnerPkg, pkgLite);
14343                        } catch (PackageManagerException e) {
14344                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14345                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14346                        }
14347                    }
14348                }
14349
14350                if (installedPkg != null) {
14351                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14352                        // Check for updated system application.
14353                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14354                            if (onSd) {
14355                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14356                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14357                            }
14358                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14359                        } else {
14360                            if (onSd) {
14361                                // Install flag overrides everything.
14362                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14363                            }
14364                            // If current upgrade specifies particular preference
14365                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14366                                // Application explicitly specified internal.
14367                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14368                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14369                                // App explictly prefers external. Let policy decide
14370                            } else {
14371                                // Prefer previous location
14372                                if (isExternal(installedPkg)) {
14373                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14374                                }
14375                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14376                            }
14377                        }
14378                    } else {
14379                        // Invalid install. Return error code
14380                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14381                    }
14382                }
14383            }
14384            // All the special cases have been taken care of.
14385            // Return result based on recommended install location.
14386            if (onSd) {
14387                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14388            }
14389            return pkgLite.recommendedInstallLocation;
14390        }
14391
14392        /*
14393         * Invoke remote method to get package information and install
14394         * location values. Override install location based on default
14395         * policy if needed and then create install arguments based
14396         * on the install location.
14397         */
14398        public void handleStartCopy() throws RemoteException {
14399            int ret = PackageManager.INSTALL_SUCCEEDED;
14400
14401            // If we're already staged, we've firmly committed to an install location
14402            if (origin.staged) {
14403                if (origin.file != null) {
14404                    installFlags |= PackageManager.INSTALL_INTERNAL;
14405                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14406                } else if (origin.cid != null) {
14407                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14408                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14409                } else {
14410                    throw new IllegalStateException("Invalid stage location");
14411                }
14412            }
14413
14414            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14415            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14416            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14417            PackageInfoLite pkgLite = null;
14418
14419            if (onInt && onSd) {
14420                // Check if both bits are set.
14421                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14422                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14423            } else if (onSd && ephemeral) {
14424                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14425                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14426            } else {
14427                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14428                        packageAbiOverride);
14429
14430                if (DEBUG_EPHEMERAL && ephemeral) {
14431                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14432                }
14433
14434                /*
14435                 * If we have too little free space, try to free cache
14436                 * before giving up.
14437                 */
14438                if (!origin.staged && pkgLite.recommendedInstallLocation
14439                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14440                    // TODO: focus freeing disk space on the target device
14441                    final StorageManager storage = StorageManager.from(mContext);
14442                    final long lowThreshold = storage.getStorageLowBytes(
14443                            Environment.getDataDirectory());
14444
14445                    final long sizeBytes = mContainerService.calculateInstalledSize(
14446                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14447
14448                    try {
14449                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14450                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14451                                installFlags, packageAbiOverride);
14452                    } catch (InstallerException e) {
14453                        Slog.w(TAG, "Failed to free cache", e);
14454                    }
14455
14456                    /*
14457                     * The cache free must have deleted the file we
14458                     * downloaded to install.
14459                     *
14460                     * TODO: fix the "freeCache" call to not delete
14461                     *       the file we care about.
14462                     */
14463                    if (pkgLite.recommendedInstallLocation
14464                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14465                        pkgLite.recommendedInstallLocation
14466                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14467                    }
14468                }
14469            }
14470
14471            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14472                int loc = pkgLite.recommendedInstallLocation;
14473                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14474                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14475                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14476                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14477                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14478                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14479                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14480                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14481                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14482                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14483                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14484                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14485                } else {
14486                    // Override with defaults if needed.
14487                    loc = installLocationPolicy(pkgLite);
14488                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14489                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14490                    } else if (!onSd && !onInt) {
14491                        // Override install location with flags
14492                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14493                            // Set the flag to install on external media.
14494                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14495                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14496                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14497                            if (DEBUG_EPHEMERAL) {
14498                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14499                            }
14500                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14501                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14502                                    |PackageManager.INSTALL_INTERNAL);
14503                        } else {
14504                            // Make sure the flag for installing on external
14505                            // media is unset
14506                            installFlags |= PackageManager.INSTALL_INTERNAL;
14507                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14508                        }
14509                    }
14510                }
14511            }
14512
14513            final InstallArgs args = createInstallArgs(this);
14514            mArgs = args;
14515
14516            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14517                // TODO: http://b/22976637
14518                // Apps installed for "all" users use the device owner to verify the app
14519                UserHandle verifierUser = getUser();
14520                if (verifierUser == UserHandle.ALL) {
14521                    verifierUser = UserHandle.SYSTEM;
14522                }
14523
14524                /*
14525                 * Determine if we have any installed package verifiers. If we
14526                 * do, then we'll defer to them to verify the packages.
14527                 */
14528                final int requiredUid = mRequiredVerifierPackage == null ? -1
14529                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14530                                verifierUser.getIdentifier());
14531                if (!origin.existing && requiredUid != -1
14532                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14533                    final Intent verification = new Intent(
14534                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14535                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14536                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14537                            PACKAGE_MIME_TYPE);
14538                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14539
14540                    // Query all live verifiers based on current user state
14541                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14542                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14543
14544                    if (DEBUG_VERIFY) {
14545                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14546                                + verification.toString() + " with " + pkgLite.verifiers.length
14547                                + " optional verifiers");
14548                    }
14549
14550                    final int verificationId = mPendingVerificationToken++;
14551
14552                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14553
14554                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14555                            installerPackageName);
14556
14557                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14558                            installFlags);
14559
14560                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14561                            pkgLite.packageName);
14562
14563                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14564                            pkgLite.versionCode);
14565
14566                    if (verificationInfo != null) {
14567                        if (verificationInfo.originatingUri != null) {
14568                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14569                                    verificationInfo.originatingUri);
14570                        }
14571                        if (verificationInfo.referrer != null) {
14572                            verification.putExtra(Intent.EXTRA_REFERRER,
14573                                    verificationInfo.referrer);
14574                        }
14575                        if (verificationInfo.originatingUid >= 0) {
14576                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14577                                    verificationInfo.originatingUid);
14578                        }
14579                        if (verificationInfo.installerUid >= 0) {
14580                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14581                                    verificationInfo.installerUid);
14582                        }
14583                    }
14584
14585                    final PackageVerificationState verificationState = new PackageVerificationState(
14586                            requiredUid, args);
14587
14588                    mPendingVerification.append(verificationId, verificationState);
14589
14590                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14591                            receivers, verificationState);
14592
14593                    /*
14594                     * If any sufficient verifiers were listed in the package
14595                     * manifest, attempt to ask them.
14596                     */
14597                    if (sufficientVerifiers != null) {
14598                        final int N = sufficientVerifiers.size();
14599                        if (N == 0) {
14600                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14601                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14602                        } else {
14603                            for (int i = 0; i < N; i++) {
14604                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14605
14606                                final Intent sufficientIntent = new Intent(verification);
14607                                sufficientIntent.setComponent(verifierComponent);
14608                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14609                            }
14610                        }
14611                    }
14612
14613                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14614                            mRequiredVerifierPackage, receivers);
14615                    if (ret == PackageManager.INSTALL_SUCCEEDED
14616                            && mRequiredVerifierPackage != null) {
14617                        Trace.asyncTraceBegin(
14618                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14619                        /*
14620                         * Send the intent to the required verification agent,
14621                         * but only start the verification timeout after the
14622                         * target BroadcastReceivers have run.
14623                         */
14624                        verification.setComponent(requiredVerifierComponent);
14625                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14626                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14627                                new BroadcastReceiver() {
14628                                    @Override
14629                                    public void onReceive(Context context, Intent intent) {
14630                                        final Message msg = mHandler
14631                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14632                                        msg.arg1 = verificationId;
14633                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14634                                    }
14635                                }, null, 0, null, null);
14636
14637                        /*
14638                         * We don't want the copy to proceed until verification
14639                         * succeeds, so null out this field.
14640                         */
14641                        mArgs = null;
14642                    }
14643                } else {
14644                    /*
14645                     * No package verification is enabled, so immediately start
14646                     * the remote call to initiate copy using temporary file.
14647                     */
14648                    ret = args.copyApk(mContainerService, true);
14649                }
14650            }
14651
14652            mRet = ret;
14653        }
14654
14655        @Override
14656        void handleReturnCode() {
14657            // If mArgs is null, then MCS couldn't be reached. When it
14658            // reconnects, it will try again to install. At that point, this
14659            // will succeed.
14660            if (mArgs != null) {
14661                processPendingInstall(mArgs, mRet);
14662            }
14663        }
14664
14665        @Override
14666        void handleServiceError() {
14667            mArgs = createInstallArgs(this);
14668            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14669        }
14670
14671        public boolean isForwardLocked() {
14672            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14673        }
14674    }
14675
14676    /**
14677     * Used during creation of InstallArgs
14678     *
14679     * @param installFlags package installation flags
14680     * @return true if should be installed on external storage
14681     */
14682    private static boolean installOnExternalAsec(int installFlags) {
14683        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14684            return false;
14685        }
14686        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14687            return true;
14688        }
14689        return false;
14690    }
14691
14692    /**
14693     * Used during creation of InstallArgs
14694     *
14695     * @param installFlags package installation flags
14696     * @return true if should be installed as forward locked
14697     */
14698    private static boolean installForwardLocked(int installFlags) {
14699        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14700    }
14701
14702    private InstallArgs createInstallArgs(InstallParams params) {
14703        if (params.move != null) {
14704            return new MoveInstallArgs(params);
14705        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14706            return new AsecInstallArgs(params);
14707        } else {
14708            return new FileInstallArgs(params);
14709        }
14710    }
14711
14712    /**
14713     * Create args that describe an existing installed package. Typically used
14714     * when cleaning up old installs, or used as a move source.
14715     */
14716    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14717            String resourcePath, String[] instructionSets) {
14718        final boolean isInAsec;
14719        if (installOnExternalAsec(installFlags)) {
14720            /* Apps on SD card are always in ASEC containers. */
14721            isInAsec = true;
14722        } else if (installForwardLocked(installFlags)
14723                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14724            /*
14725             * Forward-locked apps are only in ASEC containers if they're the
14726             * new style
14727             */
14728            isInAsec = true;
14729        } else {
14730            isInAsec = false;
14731        }
14732
14733        if (isInAsec) {
14734            return new AsecInstallArgs(codePath, instructionSets,
14735                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14736        } else {
14737            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14738        }
14739    }
14740
14741    static abstract class InstallArgs {
14742        /** @see InstallParams#origin */
14743        final OriginInfo origin;
14744        /** @see InstallParams#move */
14745        final MoveInfo move;
14746
14747        final IPackageInstallObserver2 observer;
14748        // Always refers to PackageManager flags only
14749        final int installFlags;
14750        final String installerPackageName;
14751        final String volumeUuid;
14752        final UserHandle user;
14753        final String abiOverride;
14754        final String[] installGrantPermissions;
14755        /** If non-null, drop an async trace when the install completes */
14756        final String traceMethod;
14757        final int traceCookie;
14758        final Certificate[][] certificates;
14759        final int installReason;
14760
14761        // The list of instruction sets supported by this app. This is currently
14762        // only used during the rmdex() phase to clean up resources. We can get rid of this
14763        // if we move dex files under the common app path.
14764        /* nullable */ String[] instructionSets;
14765
14766        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14767                int installFlags, String installerPackageName, String volumeUuid,
14768                UserHandle user, String[] instructionSets,
14769                String abiOverride, String[] installGrantPermissions,
14770                String traceMethod, int traceCookie, Certificate[][] certificates,
14771                int installReason) {
14772            this.origin = origin;
14773            this.move = move;
14774            this.installFlags = installFlags;
14775            this.observer = observer;
14776            this.installerPackageName = installerPackageName;
14777            this.volumeUuid = volumeUuid;
14778            this.user = user;
14779            this.instructionSets = instructionSets;
14780            this.abiOverride = abiOverride;
14781            this.installGrantPermissions = installGrantPermissions;
14782            this.traceMethod = traceMethod;
14783            this.traceCookie = traceCookie;
14784            this.certificates = certificates;
14785            this.installReason = installReason;
14786        }
14787
14788        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14789        abstract int doPreInstall(int status);
14790
14791        /**
14792         * Rename package into final resting place. All paths on the given
14793         * scanned package should be updated to reflect the rename.
14794         */
14795        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14796        abstract int doPostInstall(int status, int uid);
14797
14798        /** @see PackageSettingBase#codePathString */
14799        abstract String getCodePath();
14800        /** @see PackageSettingBase#resourcePathString */
14801        abstract String getResourcePath();
14802
14803        // Need installer lock especially for dex file removal.
14804        abstract void cleanUpResourcesLI();
14805        abstract boolean doPostDeleteLI(boolean delete);
14806
14807        /**
14808         * Called before the source arguments are copied. This is used mostly
14809         * for MoveParams when it needs to read the source file to put it in the
14810         * destination.
14811         */
14812        int doPreCopy() {
14813            return PackageManager.INSTALL_SUCCEEDED;
14814        }
14815
14816        /**
14817         * Called after the source arguments are copied. This is used mostly for
14818         * MoveParams when it needs to read the source file to put it in the
14819         * destination.
14820         */
14821        int doPostCopy(int uid) {
14822            return PackageManager.INSTALL_SUCCEEDED;
14823        }
14824
14825        protected boolean isFwdLocked() {
14826            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14827        }
14828
14829        protected boolean isExternalAsec() {
14830            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14831        }
14832
14833        protected boolean isEphemeral() {
14834            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14835        }
14836
14837        UserHandle getUser() {
14838            return user;
14839        }
14840    }
14841
14842    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14843        if (!allCodePaths.isEmpty()) {
14844            if (instructionSets == null) {
14845                throw new IllegalStateException("instructionSet == null");
14846            }
14847            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14848            for (String codePath : allCodePaths) {
14849                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14850                    try {
14851                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14852                    } catch (InstallerException ignored) {
14853                    }
14854                }
14855            }
14856        }
14857    }
14858
14859    /**
14860     * Logic to handle installation of non-ASEC applications, including copying
14861     * and renaming logic.
14862     */
14863    class FileInstallArgs extends InstallArgs {
14864        private File codeFile;
14865        private File resourceFile;
14866
14867        // Example topology:
14868        // /data/app/com.example/base.apk
14869        // /data/app/com.example/split_foo.apk
14870        // /data/app/com.example/lib/arm/libfoo.so
14871        // /data/app/com.example/lib/arm64/libfoo.so
14872        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14873
14874        /** New install */
14875        FileInstallArgs(InstallParams params) {
14876            super(params.origin, params.move, params.observer, params.installFlags,
14877                    params.installerPackageName, params.volumeUuid,
14878                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14879                    params.grantedRuntimePermissions,
14880                    params.traceMethod, params.traceCookie, params.certificates,
14881                    params.installReason);
14882            if (isFwdLocked()) {
14883                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14884            }
14885        }
14886
14887        /** Existing install */
14888        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14889            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14890                    null, null, null, 0, null /*certificates*/,
14891                    PackageManager.INSTALL_REASON_UNKNOWN);
14892            this.codeFile = (codePath != null) ? new File(codePath) : null;
14893            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14894        }
14895
14896        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14897            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14898            try {
14899                return doCopyApk(imcs, temp);
14900            } finally {
14901                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14902            }
14903        }
14904
14905        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14906            if (origin.staged) {
14907                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14908                codeFile = origin.file;
14909                resourceFile = origin.file;
14910                return PackageManager.INSTALL_SUCCEEDED;
14911            }
14912
14913            try {
14914                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14915                final File tempDir =
14916                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14917                codeFile = tempDir;
14918                resourceFile = tempDir;
14919            } catch (IOException e) {
14920                Slog.w(TAG, "Failed to create copy file: " + e);
14921                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14922            }
14923
14924            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14925                @Override
14926                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14927                    if (!FileUtils.isValidExtFilename(name)) {
14928                        throw new IllegalArgumentException("Invalid filename: " + name);
14929                    }
14930                    try {
14931                        final File file = new File(codeFile, name);
14932                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14933                                O_RDWR | O_CREAT, 0644);
14934                        Os.chmod(file.getAbsolutePath(), 0644);
14935                        return new ParcelFileDescriptor(fd);
14936                    } catch (ErrnoException e) {
14937                        throw new RemoteException("Failed to open: " + e.getMessage());
14938                    }
14939                }
14940            };
14941
14942            int ret = PackageManager.INSTALL_SUCCEEDED;
14943            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14944            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14945                Slog.e(TAG, "Failed to copy package");
14946                return ret;
14947            }
14948
14949            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14950            NativeLibraryHelper.Handle handle = null;
14951            try {
14952                handle = NativeLibraryHelper.Handle.create(codeFile);
14953                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14954                        abiOverride);
14955            } catch (IOException e) {
14956                Slog.e(TAG, "Copying native libraries failed", e);
14957                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14958            } finally {
14959                IoUtils.closeQuietly(handle);
14960            }
14961
14962            return ret;
14963        }
14964
14965        int doPreInstall(int status) {
14966            if (status != PackageManager.INSTALL_SUCCEEDED) {
14967                cleanUp();
14968            }
14969            return status;
14970        }
14971
14972        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14973            if (status != PackageManager.INSTALL_SUCCEEDED) {
14974                cleanUp();
14975                return false;
14976            }
14977
14978            final File targetDir = codeFile.getParentFile();
14979            final File beforeCodeFile = codeFile;
14980            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14981
14982            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14983            try {
14984                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14985            } catch (ErrnoException e) {
14986                Slog.w(TAG, "Failed to rename", e);
14987                return false;
14988            }
14989
14990            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14991                Slog.w(TAG, "Failed to restorecon");
14992                return false;
14993            }
14994
14995            // Reflect the rename internally
14996            codeFile = afterCodeFile;
14997            resourceFile = afterCodeFile;
14998
14999            // Reflect the rename in scanned details
15000            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15001            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15002                    afterCodeFile, pkg.baseCodePath));
15003            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15004                    afterCodeFile, pkg.splitCodePaths));
15005
15006            // Reflect the rename in app info
15007            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15008            pkg.setApplicationInfoCodePath(pkg.codePath);
15009            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15010            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15011            pkg.setApplicationInfoResourcePath(pkg.codePath);
15012            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15013            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15014
15015            return true;
15016        }
15017
15018        int doPostInstall(int status, int uid) {
15019            if (status != PackageManager.INSTALL_SUCCEEDED) {
15020                cleanUp();
15021            }
15022            return status;
15023        }
15024
15025        @Override
15026        String getCodePath() {
15027            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15028        }
15029
15030        @Override
15031        String getResourcePath() {
15032            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15033        }
15034
15035        private boolean cleanUp() {
15036            if (codeFile == null || !codeFile.exists()) {
15037                return false;
15038            }
15039
15040            removeCodePathLI(codeFile);
15041
15042            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15043                resourceFile.delete();
15044            }
15045
15046            return true;
15047        }
15048
15049        void cleanUpResourcesLI() {
15050            // Try enumerating all code paths before deleting
15051            List<String> allCodePaths = Collections.EMPTY_LIST;
15052            if (codeFile != null && codeFile.exists()) {
15053                try {
15054                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15055                    allCodePaths = pkg.getAllCodePaths();
15056                } catch (PackageParserException e) {
15057                    // Ignored; we tried our best
15058                }
15059            }
15060
15061            cleanUp();
15062            removeDexFiles(allCodePaths, instructionSets);
15063        }
15064
15065        boolean doPostDeleteLI(boolean delete) {
15066            // XXX err, shouldn't we respect the delete flag?
15067            cleanUpResourcesLI();
15068            return true;
15069        }
15070    }
15071
15072    private boolean isAsecExternal(String cid) {
15073        final String asecPath = PackageHelper.getSdFilesystem(cid);
15074        return !asecPath.startsWith(mAsecInternalPath);
15075    }
15076
15077    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15078            PackageManagerException {
15079        if (copyRet < 0) {
15080            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15081                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15082                throw new PackageManagerException(copyRet, message);
15083            }
15084        }
15085    }
15086
15087    /**
15088     * Extract the StorageManagerService "container ID" from the full code path of an
15089     * .apk.
15090     */
15091    static String cidFromCodePath(String fullCodePath) {
15092        int eidx = fullCodePath.lastIndexOf("/");
15093        String subStr1 = fullCodePath.substring(0, eidx);
15094        int sidx = subStr1.lastIndexOf("/");
15095        return subStr1.substring(sidx+1, eidx);
15096    }
15097
15098    /**
15099     * Logic to handle installation of ASEC applications, including copying and
15100     * renaming logic.
15101     */
15102    class AsecInstallArgs extends InstallArgs {
15103        static final String RES_FILE_NAME = "pkg.apk";
15104        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15105
15106        String cid;
15107        String packagePath;
15108        String resourcePath;
15109
15110        /** New install */
15111        AsecInstallArgs(InstallParams params) {
15112            super(params.origin, params.move, params.observer, params.installFlags,
15113                    params.installerPackageName, params.volumeUuid,
15114                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15115                    params.grantedRuntimePermissions,
15116                    params.traceMethod, params.traceCookie, params.certificates,
15117                    params.installReason);
15118        }
15119
15120        /** Existing install */
15121        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15122                        boolean isExternal, boolean isForwardLocked) {
15123            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15124                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15125                    instructionSets, null, null, null, 0, null /*certificates*/,
15126                    PackageManager.INSTALL_REASON_UNKNOWN);
15127            // Hackily pretend we're still looking at a full code path
15128            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15129                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15130            }
15131
15132            // Extract cid from fullCodePath
15133            int eidx = fullCodePath.lastIndexOf("/");
15134            String subStr1 = fullCodePath.substring(0, eidx);
15135            int sidx = subStr1.lastIndexOf("/");
15136            cid = subStr1.substring(sidx+1, eidx);
15137            setMountPath(subStr1);
15138        }
15139
15140        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15141            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15142                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15143                    instructionSets, null, null, null, 0, null /*certificates*/,
15144                    PackageManager.INSTALL_REASON_UNKNOWN);
15145            this.cid = cid;
15146            setMountPath(PackageHelper.getSdDir(cid));
15147        }
15148
15149        void createCopyFile() {
15150            cid = mInstallerService.allocateExternalStageCidLegacy();
15151        }
15152
15153        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15154            if (origin.staged && origin.cid != null) {
15155                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15156                cid = origin.cid;
15157                setMountPath(PackageHelper.getSdDir(cid));
15158                return PackageManager.INSTALL_SUCCEEDED;
15159            }
15160
15161            if (temp) {
15162                createCopyFile();
15163            } else {
15164                /*
15165                 * Pre-emptively destroy the container since it's destroyed if
15166                 * copying fails due to it existing anyway.
15167                 */
15168                PackageHelper.destroySdDir(cid);
15169            }
15170
15171            final String newMountPath = imcs.copyPackageToContainer(
15172                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15173                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15174
15175            if (newMountPath != null) {
15176                setMountPath(newMountPath);
15177                return PackageManager.INSTALL_SUCCEEDED;
15178            } else {
15179                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15180            }
15181        }
15182
15183        @Override
15184        String getCodePath() {
15185            return packagePath;
15186        }
15187
15188        @Override
15189        String getResourcePath() {
15190            return resourcePath;
15191        }
15192
15193        int doPreInstall(int status) {
15194            if (status != PackageManager.INSTALL_SUCCEEDED) {
15195                // Destroy container
15196                PackageHelper.destroySdDir(cid);
15197            } else {
15198                boolean mounted = PackageHelper.isContainerMounted(cid);
15199                if (!mounted) {
15200                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15201                            Process.SYSTEM_UID);
15202                    if (newMountPath != null) {
15203                        setMountPath(newMountPath);
15204                    } else {
15205                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15206                    }
15207                }
15208            }
15209            return status;
15210        }
15211
15212        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15213            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15214            String newMountPath = null;
15215            if (PackageHelper.isContainerMounted(cid)) {
15216                // Unmount the container
15217                if (!PackageHelper.unMountSdDir(cid)) {
15218                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15219                    return false;
15220                }
15221            }
15222            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15223                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15224                        " which might be stale. Will try to clean up.");
15225                // Clean up the stale container and proceed to recreate.
15226                if (!PackageHelper.destroySdDir(newCacheId)) {
15227                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15228                    return false;
15229                }
15230                // Successfully cleaned up stale container. Try to rename again.
15231                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15232                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15233                            + " inspite of cleaning it up.");
15234                    return false;
15235                }
15236            }
15237            if (!PackageHelper.isContainerMounted(newCacheId)) {
15238                Slog.w(TAG, "Mounting container " + newCacheId);
15239                newMountPath = PackageHelper.mountSdDir(newCacheId,
15240                        getEncryptKey(), Process.SYSTEM_UID);
15241            } else {
15242                newMountPath = PackageHelper.getSdDir(newCacheId);
15243            }
15244            if (newMountPath == null) {
15245                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15246                return false;
15247            }
15248            Log.i(TAG, "Succesfully renamed " + cid +
15249                    " to " + newCacheId +
15250                    " at new path: " + newMountPath);
15251            cid = newCacheId;
15252
15253            final File beforeCodeFile = new File(packagePath);
15254            setMountPath(newMountPath);
15255            final File afterCodeFile = new File(packagePath);
15256
15257            // Reflect the rename in scanned details
15258            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15259            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15260                    afterCodeFile, pkg.baseCodePath));
15261            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15262                    afterCodeFile, pkg.splitCodePaths));
15263
15264            // Reflect the rename in app info
15265            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15266            pkg.setApplicationInfoCodePath(pkg.codePath);
15267            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15268            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15269            pkg.setApplicationInfoResourcePath(pkg.codePath);
15270            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15271            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15272
15273            return true;
15274        }
15275
15276        private void setMountPath(String mountPath) {
15277            final File mountFile = new File(mountPath);
15278
15279            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15280            if (monolithicFile.exists()) {
15281                packagePath = monolithicFile.getAbsolutePath();
15282                if (isFwdLocked()) {
15283                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15284                } else {
15285                    resourcePath = packagePath;
15286                }
15287            } else {
15288                packagePath = mountFile.getAbsolutePath();
15289                resourcePath = packagePath;
15290            }
15291        }
15292
15293        int doPostInstall(int status, int uid) {
15294            if (status != PackageManager.INSTALL_SUCCEEDED) {
15295                cleanUp();
15296            } else {
15297                final int groupOwner;
15298                final String protectedFile;
15299                if (isFwdLocked()) {
15300                    groupOwner = UserHandle.getSharedAppGid(uid);
15301                    protectedFile = RES_FILE_NAME;
15302                } else {
15303                    groupOwner = -1;
15304                    protectedFile = null;
15305                }
15306
15307                if (uid < Process.FIRST_APPLICATION_UID
15308                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15309                    Slog.e(TAG, "Failed to finalize " + cid);
15310                    PackageHelper.destroySdDir(cid);
15311                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15312                }
15313
15314                boolean mounted = PackageHelper.isContainerMounted(cid);
15315                if (!mounted) {
15316                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15317                }
15318            }
15319            return status;
15320        }
15321
15322        private void cleanUp() {
15323            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15324
15325            // Destroy secure container
15326            PackageHelper.destroySdDir(cid);
15327        }
15328
15329        private List<String> getAllCodePaths() {
15330            final File codeFile = new File(getCodePath());
15331            if (codeFile != null && codeFile.exists()) {
15332                try {
15333                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15334                    return pkg.getAllCodePaths();
15335                } catch (PackageParserException e) {
15336                    // Ignored; we tried our best
15337                }
15338            }
15339            return Collections.EMPTY_LIST;
15340        }
15341
15342        void cleanUpResourcesLI() {
15343            // Enumerate all code paths before deleting
15344            cleanUpResourcesLI(getAllCodePaths());
15345        }
15346
15347        private void cleanUpResourcesLI(List<String> allCodePaths) {
15348            cleanUp();
15349            removeDexFiles(allCodePaths, instructionSets);
15350        }
15351
15352        String getPackageName() {
15353            return getAsecPackageName(cid);
15354        }
15355
15356        boolean doPostDeleteLI(boolean delete) {
15357            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15358            final List<String> allCodePaths = getAllCodePaths();
15359            boolean mounted = PackageHelper.isContainerMounted(cid);
15360            if (mounted) {
15361                // Unmount first
15362                if (PackageHelper.unMountSdDir(cid)) {
15363                    mounted = false;
15364                }
15365            }
15366            if (!mounted && delete) {
15367                cleanUpResourcesLI(allCodePaths);
15368            }
15369            return !mounted;
15370        }
15371
15372        @Override
15373        int doPreCopy() {
15374            if (isFwdLocked()) {
15375                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15376                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15377                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15378                }
15379            }
15380
15381            return PackageManager.INSTALL_SUCCEEDED;
15382        }
15383
15384        @Override
15385        int doPostCopy(int uid) {
15386            if (isFwdLocked()) {
15387                if (uid < Process.FIRST_APPLICATION_UID
15388                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15389                                RES_FILE_NAME)) {
15390                    Slog.e(TAG, "Failed to finalize " + cid);
15391                    PackageHelper.destroySdDir(cid);
15392                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15393                }
15394            }
15395
15396            return PackageManager.INSTALL_SUCCEEDED;
15397        }
15398    }
15399
15400    /**
15401     * Logic to handle movement of existing installed applications.
15402     */
15403    class MoveInstallArgs extends InstallArgs {
15404        private File codeFile;
15405        private File resourceFile;
15406
15407        /** New install */
15408        MoveInstallArgs(InstallParams params) {
15409            super(params.origin, params.move, params.observer, params.installFlags,
15410                    params.installerPackageName, params.volumeUuid,
15411                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15412                    params.grantedRuntimePermissions,
15413                    params.traceMethod, params.traceCookie, params.certificates,
15414                    params.installReason);
15415        }
15416
15417        int copyApk(IMediaContainerService imcs, boolean temp) {
15418            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15419                    + move.fromUuid + " to " + move.toUuid);
15420            synchronized (mInstaller) {
15421                try {
15422                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15423                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15424                } catch (InstallerException e) {
15425                    Slog.w(TAG, "Failed to move app", e);
15426                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15427                }
15428            }
15429
15430            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15431            resourceFile = codeFile;
15432            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15433
15434            return PackageManager.INSTALL_SUCCEEDED;
15435        }
15436
15437        int doPreInstall(int status) {
15438            if (status != PackageManager.INSTALL_SUCCEEDED) {
15439                cleanUp(move.toUuid);
15440            }
15441            return status;
15442        }
15443
15444        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15445            if (status != PackageManager.INSTALL_SUCCEEDED) {
15446                cleanUp(move.toUuid);
15447                return false;
15448            }
15449
15450            // Reflect the move in app info
15451            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15452            pkg.setApplicationInfoCodePath(pkg.codePath);
15453            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15454            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15455            pkg.setApplicationInfoResourcePath(pkg.codePath);
15456            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15457            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15458
15459            return true;
15460        }
15461
15462        int doPostInstall(int status, int uid) {
15463            if (status == PackageManager.INSTALL_SUCCEEDED) {
15464                cleanUp(move.fromUuid);
15465            } else {
15466                cleanUp(move.toUuid);
15467            }
15468            return status;
15469        }
15470
15471        @Override
15472        String getCodePath() {
15473            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15474        }
15475
15476        @Override
15477        String getResourcePath() {
15478            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15479        }
15480
15481        private boolean cleanUp(String volumeUuid) {
15482            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15483                    move.dataAppName);
15484            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15485            final int[] userIds = sUserManager.getUserIds();
15486            synchronized (mInstallLock) {
15487                // Clean up both app data and code
15488                // All package moves are frozen until finished
15489                for (int userId : userIds) {
15490                    try {
15491                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15492                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15493                    } catch (InstallerException e) {
15494                        Slog.w(TAG, String.valueOf(e));
15495                    }
15496                }
15497                removeCodePathLI(codeFile);
15498            }
15499            return true;
15500        }
15501
15502        void cleanUpResourcesLI() {
15503            throw new UnsupportedOperationException();
15504        }
15505
15506        boolean doPostDeleteLI(boolean delete) {
15507            throw new UnsupportedOperationException();
15508        }
15509    }
15510
15511    static String getAsecPackageName(String packageCid) {
15512        int idx = packageCid.lastIndexOf("-");
15513        if (idx == -1) {
15514            return packageCid;
15515        }
15516        return packageCid.substring(0, idx);
15517    }
15518
15519    // Utility method used to create code paths based on package name and available index.
15520    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15521        String idxStr = "";
15522        int idx = 1;
15523        // Fall back to default value of idx=1 if prefix is not
15524        // part of oldCodePath
15525        if (oldCodePath != null) {
15526            String subStr = oldCodePath;
15527            // Drop the suffix right away
15528            if (suffix != null && subStr.endsWith(suffix)) {
15529                subStr = subStr.substring(0, subStr.length() - suffix.length());
15530            }
15531            // If oldCodePath already contains prefix find out the
15532            // ending index to either increment or decrement.
15533            int sidx = subStr.lastIndexOf(prefix);
15534            if (sidx != -1) {
15535                subStr = subStr.substring(sidx + prefix.length());
15536                if (subStr != null) {
15537                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15538                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15539                    }
15540                    try {
15541                        idx = Integer.parseInt(subStr);
15542                        if (idx <= 1) {
15543                            idx++;
15544                        } else {
15545                            idx--;
15546                        }
15547                    } catch(NumberFormatException e) {
15548                    }
15549                }
15550            }
15551        }
15552        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15553        return prefix + idxStr;
15554    }
15555
15556    private File getNextCodePath(File targetDir, String packageName) {
15557        File result;
15558        SecureRandom random = new SecureRandom();
15559        byte[] bytes = new byte[16];
15560        do {
15561            random.nextBytes(bytes);
15562            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15563            result = new File(targetDir, packageName + "-" + suffix);
15564        } while (result.exists());
15565        return result;
15566    }
15567
15568    // Utility method that returns the relative package path with respect
15569    // to the installation directory. Like say for /data/data/com.test-1.apk
15570    // string com.test-1 is returned.
15571    static String deriveCodePathName(String codePath) {
15572        if (codePath == null) {
15573            return null;
15574        }
15575        final File codeFile = new File(codePath);
15576        final String name = codeFile.getName();
15577        if (codeFile.isDirectory()) {
15578            return name;
15579        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15580            final int lastDot = name.lastIndexOf('.');
15581            return name.substring(0, lastDot);
15582        } else {
15583            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15584            return null;
15585        }
15586    }
15587
15588    static class PackageInstalledInfo {
15589        String name;
15590        int uid;
15591        // The set of users that originally had this package installed.
15592        int[] origUsers;
15593        // The set of users that now have this package installed.
15594        int[] newUsers;
15595        PackageParser.Package pkg;
15596        int returnCode;
15597        String returnMsg;
15598        PackageRemovedInfo removedInfo;
15599        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15600
15601        public void setError(int code, String msg) {
15602            setReturnCode(code);
15603            setReturnMessage(msg);
15604            Slog.w(TAG, msg);
15605        }
15606
15607        public void setError(String msg, PackageParserException e) {
15608            setReturnCode(e.error);
15609            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15610            Slog.w(TAG, msg, e);
15611        }
15612
15613        public void setError(String msg, PackageManagerException e) {
15614            returnCode = e.error;
15615            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15616            Slog.w(TAG, msg, e);
15617        }
15618
15619        public void setReturnCode(int returnCode) {
15620            this.returnCode = returnCode;
15621            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15622            for (int i = 0; i < childCount; i++) {
15623                addedChildPackages.valueAt(i).returnCode = returnCode;
15624            }
15625        }
15626
15627        private void setReturnMessage(String returnMsg) {
15628            this.returnMsg = returnMsg;
15629            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15630            for (int i = 0; i < childCount; i++) {
15631                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15632            }
15633        }
15634
15635        // In some error cases we want to convey more info back to the observer
15636        String origPackage;
15637        String origPermission;
15638    }
15639
15640    /*
15641     * Install a non-existing package.
15642     */
15643    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15644            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15645            PackageInstalledInfo res, int installReason) {
15646        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15647
15648        // Remember this for later, in case we need to rollback this install
15649        String pkgName = pkg.packageName;
15650
15651        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15652
15653        synchronized(mPackages) {
15654            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15655            if (renamedPackage != null) {
15656                // A package with the same name is already installed, though
15657                // it has been renamed to an older name.  The package we
15658                // are trying to install should be installed as an update to
15659                // the existing one, but that has not been requested, so bail.
15660                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15661                        + " without first uninstalling package running as "
15662                        + renamedPackage);
15663                return;
15664            }
15665            if (mPackages.containsKey(pkgName)) {
15666                // Don't allow installation over an existing package with the same name.
15667                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15668                        + " without first uninstalling.");
15669                return;
15670            }
15671        }
15672
15673        try {
15674            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15675                    System.currentTimeMillis(), user);
15676
15677            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15678
15679            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15680                prepareAppDataAfterInstallLIF(newPackage);
15681
15682            } else {
15683                // Remove package from internal structures, but keep around any
15684                // data that might have already existed
15685                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15686                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15687            }
15688        } catch (PackageManagerException e) {
15689            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15690        }
15691
15692        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15693    }
15694
15695    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15696        // Can't rotate keys during boot or if sharedUser.
15697        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15698                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15699            return false;
15700        }
15701        // app is using upgradeKeySets; make sure all are valid
15702        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15703        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15704        for (int i = 0; i < upgradeKeySets.length; i++) {
15705            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15706                Slog.wtf(TAG, "Package "
15707                         + (oldPs.name != null ? oldPs.name : "<null>")
15708                         + " contains upgrade-key-set reference to unknown key-set: "
15709                         + upgradeKeySets[i]
15710                         + " reverting to signatures check.");
15711                return false;
15712            }
15713        }
15714        return true;
15715    }
15716
15717    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15718        // Upgrade keysets are being used.  Determine if new package has a superset of the
15719        // required keys.
15720        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15721        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15722        for (int i = 0; i < upgradeKeySets.length; i++) {
15723            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15724            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15725                return true;
15726            }
15727        }
15728        return false;
15729    }
15730
15731    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15732        try (DigestInputStream digestStream =
15733                new DigestInputStream(new FileInputStream(file), digest)) {
15734            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15735        }
15736    }
15737
15738    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15739            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15740            int installReason) {
15741        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15742
15743        final PackageParser.Package oldPackage;
15744        final String pkgName = pkg.packageName;
15745        final int[] allUsers;
15746        final int[] installedUsers;
15747
15748        synchronized(mPackages) {
15749            oldPackage = mPackages.get(pkgName);
15750            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15751
15752            // don't allow upgrade to target a release SDK from a pre-release SDK
15753            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15754                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15755            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15756                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15757            if (oldTargetsPreRelease
15758                    && !newTargetsPreRelease
15759                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15760                Slog.w(TAG, "Can't install package targeting released sdk");
15761                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15762                return;
15763            }
15764
15765            // don't allow an upgrade from full to ephemeral
15766            final boolean oldIsEphemeral = oldPackage.applicationInfo.isInstantApp();
15767            if (isEphemeral && !oldIsEphemeral) {
15768                // can't downgrade from full to ephemeral
15769                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15770                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15771                return;
15772            }
15773
15774            // verify signatures are valid
15775            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15776            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15777                if (!checkUpgradeKeySetLP(ps, pkg)) {
15778                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15779                            "New package not signed by keys specified by upgrade-keysets: "
15780                                    + pkgName);
15781                    return;
15782                }
15783            } else {
15784                // default to original signature matching
15785                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15786                        != PackageManager.SIGNATURE_MATCH) {
15787                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15788                            "New package has a different signature: " + pkgName);
15789                    return;
15790                }
15791            }
15792
15793            // don't allow a system upgrade unless the upgrade hash matches
15794            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15795                byte[] digestBytes = null;
15796                try {
15797                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15798                    updateDigest(digest, new File(pkg.baseCodePath));
15799                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15800                        for (String path : pkg.splitCodePaths) {
15801                            updateDigest(digest, new File(path));
15802                        }
15803                    }
15804                    digestBytes = digest.digest();
15805                } catch (NoSuchAlgorithmException | IOException e) {
15806                    res.setError(INSTALL_FAILED_INVALID_APK,
15807                            "Could not compute hash: " + pkgName);
15808                    return;
15809                }
15810                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15811                    res.setError(INSTALL_FAILED_INVALID_APK,
15812                            "New package fails restrict-update check: " + pkgName);
15813                    return;
15814                }
15815                // retain upgrade restriction
15816                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15817            }
15818
15819            // Check for shared user id changes
15820            String invalidPackageName =
15821                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15822            if (invalidPackageName != null) {
15823                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15824                        "Package " + invalidPackageName + " tried to change user "
15825                                + oldPackage.mSharedUserId);
15826                return;
15827            }
15828
15829            // In case of rollback, remember per-user/profile install state
15830            allUsers = sUserManager.getUserIds();
15831            installedUsers = ps.queryInstalledUsers(allUsers, true);
15832        }
15833
15834        // Update what is removed
15835        res.removedInfo = new PackageRemovedInfo();
15836        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15837        res.removedInfo.removedPackage = oldPackage.packageName;
15838        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15839        res.removedInfo.isUpdate = true;
15840        res.removedInfo.origUsers = installedUsers;
15841        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15842        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15843        for (int i = 0; i < installedUsers.length; i++) {
15844            final int userId = installedUsers[i];
15845            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15846        }
15847
15848        final int childCount = (oldPackage.childPackages != null)
15849                ? oldPackage.childPackages.size() : 0;
15850        for (int i = 0; i < childCount; i++) {
15851            boolean childPackageUpdated = false;
15852            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15853            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15854            if (res.addedChildPackages != null) {
15855                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15856                if (childRes != null) {
15857                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15858                    childRes.removedInfo.removedPackage = childPkg.packageName;
15859                    childRes.removedInfo.isUpdate = true;
15860                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15861                    childPackageUpdated = true;
15862                }
15863            }
15864            if (!childPackageUpdated) {
15865                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15866                childRemovedRes.removedPackage = childPkg.packageName;
15867                childRemovedRes.isUpdate = false;
15868                childRemovedRes.dataRemoved = true;
15869                synchronized (mPackages) {
15870                    if (childPs != null) {
15871                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15872                    }
15873                }
15874                if (res.removedInfo.removedChildPackages == null) {
15875                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15876                }
15877                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15878            }
15879        }
15880
15881        boolean sysPkg = (isSystemApp(oldPackage));
15882        if (sysPkg) {
15883            // Set the system/privileged flags as needed
15884            final boolean privileged =
15885                    (oldPackage.applicationInfo.privateFlags
15886                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15887            final int systemPolicyFlags = policyFlags
15888                    | PackageParser.PARSE_IS_SYSTEM
15889                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15890
15891            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15892                    user, allUsers, installerPackageName, res, installReason);
15893        } else {
15894            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15895                    user, allUsers, installerPackageName, res, installReason);
15896        }
15897    }
15898
15899    public List<String> getPreviousCodePaths(String packageName) {
15900        final PackageSetting ps = mSettings.mPackages.get(packageName);
15901        final List<String> result = new ArrayList<String>();
15902        if (ps != null && ps.oldCodePaths != null) {
15903            result.addAll(ps.oldCodePaths);
15904        }
15905        return result;
15906    }
15907
15908    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15909            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15910            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15911            int installReason) {
15912        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15913                + deletedPackage);
15914
15915        String pkgName = deletedPackage.packageName;
15916        boolean deletedPkg = true;
15917        boolean addedPkg = false;
15918        boolean updatedSettings = false;
15919        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15920        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15921                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15922
15923        final long origUpdateTime = (pkg.mExtras != null)
15924                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15925
15926        // First delete the existing package while retaining the data directory
15927        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15928                res.removedInfo, true, pkg)) {
15929            // If the existing package wasn't successfully deleted
15930            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15931            deletedPkg = false;
15932        } else {
15933            // Successfully deleted the old package; proceed with replace.
15934
15935            // If deleted package lived in a container, give users a chance to
15936            // relinquish resources before killing.
15937            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15938                if (DEBUG_INSTALL) {
15939                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15940                }
15941                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15942                final ArrayList<String> pkgList = new ArrayList<String>(1);
15943                pkgList.add(deletedPackage.applicationInfo.packageName);
15944                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15945            }
15946
15947            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15948                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15949            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15950
15951            try {
15952                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15953                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15954                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15955                        installReason);
15956
15957                // Update the in-memory copy of the previous code paths.
15958                PackageSetting ps = mSettings.mPackages.get(pkgName);
15959                if (!killApp) {
15960                    if (ps.oldCodePaths == null) {
15961                        ps.oldCodePaths = new ArraySet<>();
15962                    }
15963                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15964                    if (deletedPackage.splitCodePaths != null) {
15965                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15966                    }
15967                } else {
15968                    ps.oldCodePaths = null;
15969                }
15970                if (ps.childPackageNames != null) {
15971                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15972                        final String childPkgName = ps.childPackageNames.get(i);
15973                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15974                        childPs.oldCodePaths = ps.oldCodePaths;
15975                    }
15976                }
15977                prepareAppDataAfterInstallLIF(newPackage);
15978                addedPkg = true;
15979            } catch (PackageManagerException e) {
15980                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15981            }
15982        }
15983
15984        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15985            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15986
15987            // Revert all internal state mutations and added folders for the failed install
15988            if (addedPkg) {
15989                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15990                        res.removedInfo, true, null);
15991            }
15992
15993            // Restore the old package
15994            if (deletedPkg) {
15995                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15996                File restoreFile = new File(deletedPackage.codePath);
15997                // Parse old package
15998                boolean oldExternal = isExternal(deletedPackage);
15999                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16000                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16001                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16002                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16003                try {
16004                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16005                            null);
16006                } catch (PackageManagerException e) {
16007                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16008                            + e.getMessage());
16009                    return;
16010                }
16011
16012                synchronized (mPackages) {
16013                    // Ensure the installer package name up to date
16014                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16015
16016                    // Update permissions for restored package
16017                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16018
16019                    mSettings.writeLPr();
16020                }
16021
16022                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16023            }
16024        } else {
16025            synchronized (mPackages) {
16026                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16027                if (ps != null) {
16028                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16029                    if (res.removedInfo.removedChildPackages != null) {
16030                        final int childCount = res.removedInfo.removedChildPackages.size();
16031                        // Iterate in reverse as we may modify the collection
16032                        for (int i = childCount - 1; i >= 0; i--) {
16033                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16034                            if (res.addedChildPackages.containsKey(childPackageName)) {
16035                                res.removedInfo.removedChildPackages.removeAt(i);
16036                            } else {
16037                                PackageRemovedInfo childInfo = res.removedInfo
16038                                        .removedChildPackages.valueAt(i);
16039                                childInfo.removedForAllUsers = mPackages.get(
16040                                        childInfo.removedPackage) == null;
16041                            }
16042                        }
16043                    }
16044                }
16045            }
16046        }
16047    }
16048
16049    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16050            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16051            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16052            int installReason) {
16053        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16054                + ", old=" + deletedPackage);
16055
16056        final boolean disabledSystem;
16057
16058        // Remove existing system package
16059        removePackageLI(deletedPackage, true);
16060
16061        synchronized (mPackages) {
16062            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16063        }
16064        if (!disabledSystem) {
16065            // We didn't need to disable the .apk as a current system package,
16066            // which means we are replacing another update that is already
16067            // installed.  We need to make sure to delete the older one's .apk.
16068            res.removedInfo.args = createInstallArgsForExisting(0,
16069                    deletedPackage.applicationInfo.getCodePath(),
16070                    deletedPackage.applicationInfo.getResourcePath(),
16071                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16072        } else {
16073            res.removedInfo.args = null;
16074        }
16075
16076        // Successfully disabled the old package. Now proceed with re-installation
16077        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16078                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16079        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16080
16081        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16082        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16083                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16084
16085        PackageParser.Package newPackage = null;
16086        try {
16087            // Add the package to the internal data structures
16088            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16089
16090            // Set the update and install times
16091            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16092            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16093                    System.currentTimeMillis());
16094
16095            // Update the package dynamic state if succeeded
16096            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16097                // Now that the install succeeded make sure we remove data
16098                // directories for any child package the update removed.
16099                final int deletedChildCount = (deletedPackage.childPackages != null)
16100                        ? deletedPackage.childPackages.size() : 0;
16101                final int newChildCount = (newPackage.childPackages != null)
16102                        ? newPackage.childPackages.size() : 0;
16103                for (int i = 0; i < deletedChildCount; i++) {
16104                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16105                    boolean childPackageDeleted = true;
16106                    for (int j = 0; j < newChildCount; j++) {
16107                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16108                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16109                            childPackageDeleted = false;
16110                            break;
16111                        }
16112                    }
16113                    if (childPackageDeleted) {
16114                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16115                                deletedChildPkg.packageName);
16116                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16117                            PackageRemovedInfo removedChildRes = res.removedInfo
16118                                    .removedChildPackages.get(deletedChildPkg.packageName);
16119                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16120                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16121                        }
16122                    }
16123                }
16124
16125                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16126                        installReason);
16127                prepareAppDataAfterInstallLIF(newPackage);
16128            }
16129        } catch (PackageManagerException e) {
16130            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16131            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16132        }
16133
16134        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16135            // Re installation failed. Restore old information
16136            // Remove new pkg information
16137            if (newPackage != null) {
16138                removeInstalledPackageLI(newPackage, true);
16139            }
16140            // Add back the old system package
16141            try {
16142                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16143            } catch (PackageManagerException e) {
16144                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16145            }
16146
16147            synchronized (mPackages) {
16148                if (disabledSystem) {
16149                    enableSystemPackageLPw(deletedPackage);
16150                }
16151
16152                // Ensure the installer package name up to date
16153                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16154
16155                // Update permissions for restored package
16156                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16157
16158                mSettings.writeLPr();
16159            }
16160
16161            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16162                    + " after failed upgrade");
16163        }
16164    }
16165
16166    /**
16167     * Checks whether the parent or any of the child packages have a change shared
16168     * user. For a package to be a valid update the shred users of the parent and
16169     * the children should match. We may later support changing child shared users.
16170     * @param oldPkg The updated package.
16171     * @param newPkg The update package.
16172     * @return The shared user that change between the versions.
16173     */
16174    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16175            PackageParser.Package newPkg) {
16176        // Check parent shared user
16177        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16178            return newPkg.packageName;
16179        }
16180        // Check child shared users
16181        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16182        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16183        for (int i = 0; i < newChildCount; i++) {
16184            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16185            // If this child was present, did it have the same shared user?
16186            for (int j = 0; j < oldChildCount; j++) {
16187                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16188                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16189                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16190                    return newChildPkg.packageName;
16191                }
16192            }
16193        }
16194        return null;
16195    }
16196
16197    private void removeNativeBinariesLI(PackageSetting ps) {
16198        // Remove the lib path for the parent package
16199        if (ps != null) {
16200            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16201            // Remove the lib path for the child packages
16202            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16203            for (int i = 0; i < childCount; i++) {
16204                PackageSetting childPs = null;
16205                synchronized (mPackages) {
16206                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16207                }
16208                if (childPs != null) {
16209                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16210                            .legacyNativeLibraryPathString);
16211                }
16212            }
16213        }
16214    }
16215
16216    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16217        // Enable the parent package
16218        mSettings.enableSystemPackageLPw(pkg.packageName);
16219        // Enable the child packages
16220        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16221        for (int i = 0; i < childCount; i++) {
16222            PackageParser.Package childPkg = pkg.childPackages.get(i);
16223            mSettings.enableSystemPackageLPw(childPkg.packageName);
16224        }
16225    }
16226
16227    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16228            PackageParser.Package newPkg) {
16229        // Disable the parent package (parent always replaced)
16230        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16231        // Disable the child packages
16232        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16233        for (int i = 0; i < childCount; i++) {
16234            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16235            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16236            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16237        }
16238        return disabled;
16239    }
16240
16241    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16242            String installerPackageName) {
16243        // Enable the parent package
16244        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16245        // Enable the child packages
16246        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16247        for (int i = 0; i < childCount; i++) {
16248            PackageParser.Package childPkg = pkg.childPackages.get(i);
16249            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16250        }
16251    }
16252
16253    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16254        // Collect all used permissions in the UID
16255        ArraySet<String> usedPermissions = new ArraySet<>();
16256        final int packageCount = su.packages.size();
16257        for (int i = 0; i < packageCount; i++) {
16258            PackageSetting ps = su.packages.valueAt(i);
16259            if (ps.pkg == null) {
16260                continue;
16261            }
16262            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16263            for (int j = 0; j < requestedPermCount; j++) {
16264                String permission = ps.pkg.requestedPermissions.get(j);
16265                BasePermission bp = mSettings.mPermissions.get(permission);
16266                if (bp != null) {
16267                    usedPermissions.add(permission);
16268                }
16269            }
16270        }
16271
16272        PermissionsState permissionsState = su.getPermissionsState();
16273        // Prune install permissions
16274        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16275        final int installPermCount = installPermStates.size();
16276        for (int i = installPermCount - 1; i >= 0;  i--) {
16277            PermissionState permissionState = installPermStates.get(i);
16278            if (!usedPermissions.contains(permissionState.getName())) {
16279                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16280                if (bp != null) {
16281                    permissionsState.revokeInstallPermission(bp);
16282                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16283                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16284                }
16285            }
16286        }
16287
16288        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16289
16290        // Prune runtime permissions
16291        for (int userId : allUserIds) {
16292            List<PermissionState> runtimePermStates = permissionsState
16293                    .getRuntimePermissionStates(userId);
16294            final int runtimePermCount = runtimePermStates.size();
16295            for (int i = runtimePermCount - 1; i >= 0; i--) {
16296                PermissionState permissionState = runtimePermStates.get(i);
16297                if (!usedPermissions.contains(permissionState.getName())) {
16298                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16299                    if (bp != null) {
16300                        permissionsState.revokeRuntimePermission(bp, userId);
16301                        permissionsState.updatePermissionFlags(bp, userId,
16302                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16303                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16304                                runtimePermissionChangedUserIds, userId);
16305                    }
16306                }
16307            }
16308        }
16309
16310        return runtimePermissionChangedUserIds;
16311    }
16312
16313    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16314            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16315        // Update the parent package setting
16316        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16317                res, user, installReason);
16318        // Update the child packages setting
16319        final int childCount = (newPackage.childPackages != null)
16320                ? newPackage.childPackages.size() : 0;
16321        for (int i = 0; i < childCount; i++) {
16322            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16323            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16324            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16325                    childRes.origUsers, childRes, user, installReason);
16326        }
16327    }
16328
16329    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16330            String installerPackageName, int[] allUsers, int[] installedForUsers,
16331            PackageInstalledInfo res, UserHandle user, int installReason) {
16332        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16333
16334        String pkgName = newPackage.packageName;
16335        synchronized (mPackages) {
16336            //write settings. the installStatus will be incomplete at this stage.
16337            //note that the new package setting would have already been
16338            //added to mPackages. It hasn't been persisted yet.
16339            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16340            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16341            mSettings.writeLPr();
16342            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16343        }
16344
16345        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16346        synchronized (mPackages) {
16347            updatePermissionsLPw(newPackage.packageName, newPackage,
16348                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16349                            ? UPDATE_PERMISSIONS_ALL : 0));
16350            // For system-bundled packages, we assume that installing an upgraded version
16351            // of the package implies that the user actually wants to run that new code,
16352            // so we enable the package.
16353            PackageSetting ps = mSettings.mPackages.get(pkgName);
16354            final int userId = user.getIdentifier();
16355            if (ps != null) {
16356                if (isSystemApp(newPackage)) {
16357                    if (DEBUG_INSTALL) {
16358                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16359                    }
16360                    // Enable system package for requested users
16361                    if (res.origUsers != null) {
16362                        for (int origUserId : res.origUsers) {
16363                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16364                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16365                                        origUserId, installerPackageName);
16366                            }
16367                        }
16368                    }
16369                    // Also convey the prior install/uninstall state
16370                    if (allUsers != null && installedForUsers != null) {
16371                        for (int currentUserId : allUsers) {
16372                            final boolean installed = ArrayUtils.contains(
16373                                    installedForUsers, currentUserId);
16374                            if (DEBUG_INSTALL) {
16375                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16376                            }
16377                            ps.setInstalled(installed, currentUserId);
16378                        }
16379                        // these install state changes will be persisted in the
16380                        // upcoming call to mSettings.writeLPr().
16381                    }
16382                }
16383                // It's implied that when a user requests installation, they want the app to be
16384                // installed and enabled.
16385                if (userId != UserHandle.USER_ALL) {
16386                    ps.setInstalled(true, userId);
16387                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16388                }
16389
16390                // When replacing an existing package, preserve the original install reason for all
16391                // users that had the package installed before.
16392                final Set<Integer> previousUserIds = new ArraySet<>();
16393                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16394                    final int installReasonCount = res.removedInfo.installReasons.size();
16395                    for (int i = 0; i < installReasonCount; i++) {
16396                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16397                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16398                        ps.setInstallReason(previousInstallReason, previousUserId);
16399                        previousUserIds.add(previousUserId);
16400                    }
16401                }
16402
16403                // Set install reason for users that are having the package newly installed.
16404                if (userId == UserHandle.USER_ALL) {
16405                    for (int currentUserId : sUserManager.getUserIds()) {
16406                        if (!previousUserIds.contains(currentUserId)) {
16407                            ps.setInstallReason(installReason, currentUserId);
16408                        }
16409                    }
16410                } else if (!previousUserIds.contains(userId)) {
16411                    ps.setInstallReason(installReason, userId);
16412                }
16413            }
16414            res.name = pkgName;
16415            res.uid = newPackage.applicationInfo.uid;
16416            res.pkg = newPackage;
16417            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16418            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16419            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16420            //to update install status
16421            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16422            mSettings.writeLPr();
16423            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16424        }
16425
16426        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16427    }
16428
16429    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16430        try {
16431            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16432            installPackageLI(args, res);
16433        } finally {
16434            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16435        }
16436    }
16437
16438    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16439        final int installFlags = args.installFlags;
16440        final String installerPackageName = args.installerPackageName;
16441        final String volumeUuid = args.volumeUuid;
16442        final File tmpPackageFile = new File(args.getCodePath());
16443        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16444        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16445                || (args.volumeUuid != null));
16446        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
16447        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16448        boolean replace = false;
16449        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16450        if (args.move != null) {
16451            // moving a complete application; perform an initial scan on the new install location
16452            scanFlags |= SCAN_INITIAL;
16453        }
16454        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16455            scanFlags |= SCAN_DONT_KILL_APP;
16456        }
16457
16458        // Result object to be returned
16459        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16460
16461        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16462
16463        // Sanity check
16464        if (ephemeral && (forwardLocked || onExternal)) {
16465            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16466                    + " external=" + onExternal);
16467            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
16468            return;
16469        }
16470
16471        // Retrieve PackageSettings and parse package
16472        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16473                | PackageParser.PARSE_ENFORCE_CODE
16474                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16475                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16476                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16477                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16478        PackageParser pp = new PackageParser();
16479        pp.setSeparateProcesses(mSeparateProcesses);
16480        pp.setDisplayMetrics(mMetrics);
16481
16482        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16483        final PackageParser.Package pkg;
16484        try {
16485            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16486        } catch (PackageParserException e) {
16487            res.setError("Failed parse during installPackageLI", e);
16488            return;
16489        } finally {
16490            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16491        }
16492
16493//        // Ephemeral apps must have target SDK >= O.
16494//        // TODO: Update conditional and error message when O gets locked down
16495//        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16496//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16497//                    "Ephemeral apps must have target SDK version of at least O");
16498//            return;
16499//        }
16500
16501        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16502            // Static shared libraries have synthetic package names
16503            renameStaticSharedLibraryPackage(pkg);
16504
16505            // No static shared libs on external storage
16506            if (onExternal) {
16507                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16508                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16509                        "Packages declaring static-shared libs cannot be updated");
16510                return;
16511            }
16512        }
16513
16514        // If we are installing a clustered package add results for the children
16515        if (pkg.childPackages != null) {
16516            synchronized (mPackages) {
16517                final int childCount = pkg.childPackages.size();
16518                for (int i = 0; i < childCount; i++) {
16519                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16520                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16521                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16522                    childRes.pkg = childPkg;
16523                    childRes.name = childPkg.packageName;
16524                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16525                    if (childPs != null) {
16526                        childRes.origUsers = childPs.queryInstalledUsers(
16527                                sUserManager.getUserIds(), true);
16528                    }
16529                    if ((mPackages.containsKey(childPkg.packageName))) {
16530                        childRes.removedInfo = new PackageRemovedInfo();
16531                        childRes.removedInfo.removedPackage = childPkg.packageName;
16532                    }
16533                    if (res.addedChildPackages == null) {
16534                        res.addedChildPackages = new ArrayMap<>();
16535                    }
16536                    res.addedChildPackages.put(childPkg.packageName, childRes);
16537                }
16538            }
16539        }
16540
16541        // If package doesn't declare API override, mark that we have an install
16542        // time CPU ABI override.
16543        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16544            pkg.cpuAbiOverride = args.abiOverride;
16545        }
16546
16547        String pkgName = res.name = pkg.packageName;
16548        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16549            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16550                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16551                return;
16552            }
16553        }
16554
16555        try {
16556            // either use what we've been given or parse directly from the APK
16557            if (args.certificates != null) {
16558                try {
16559                    PackageParser.populateCertificates(pkg, args.certificates);
16560                } catch (PackageParserException e) {
16561                    // there was something wrong with the certificates we were given;
16562                    // try to pull them from the APK
16563                    PackageParser.collectCertificates(pkg, parseFlags);
16564                }
16565            } else {
16566                PackageParser.collectCertificates(pkg, parseFlags);
16567            }
16568        } catch (PackageParserException e) {
16569            res.setError("Failed collect during installPackageLI", e);
16570            return;
16571        }
16572
16573        // Get rid of all references to package scan path via parser.
16574        pp = null;
16575        String oldCodePath = null;
16576        boolean systemApp = false;
16577        synchronized (mPackages) {
16578            // Check if installing already existing package
16579            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16580                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16581                if (pkg.mOriginalPackages != null
16582                        && pkg.mOriginalPackages.contains(oldName)
16583                        && mPackages.containsKey(oldName)) {
16584                    // This package is derived from an original package,
16585                    // and this device has been updating from that original
16586                    // name.  We must continue using the original name, so
16587                    // rename the new package here.
16588                    pkg.setPackageName(oldName);
16589                    pkgName = pkg.packageName;
16590                    replace = true;
16591                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16592                            + oldName + " pkgName=" + pkgName);
16593                } else if (mPackages.containsKey(pkgName)) {
16594                    // This package, under its official name, already exists
16595                    // on the device; we should replace it.
16596                    replace = true;
16597                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16598                }
16599
16600                // Child packages are installed through the parent package
16601                if (pkg.parentPackage != null) {
16602                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16603                            "Package " + pkg.packageName + " is child of package "
16604                                    + pkg.parentPackage.parentPackage + ". Child packages "
16605                                    + "can be updated only through the parent package.");
16606                    return;
16607                }
16608
16609                if (replace) {
16610                    // Prevent apps opting out from runtime permissions
16611                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16612                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16613                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16614                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16615                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16616                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16617                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16618                                        + " doesn't support runtime permissions but the old"
16619                                        + " target SDK " + oldTargetSdk + " does.");
16620                        return;
16621                    }
16622
16623                    // Prevent installing of child packages
16624                    if (oldPackage.parentPackage != null) {
16625                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16626                                "Package " + pkg.packageName + " is child of package "
16627                                        + oldPackage.parentPackage + ". Child packages "
16628                                        + "can be updated only through the parent package.");
16629                        return;
16630                    }
16631                }
16632            }
16633
16634            PackageSetting ps = mSettings.mPackages.get(pkgName);
16635            if (ps != null) {
16636                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16637
16638                // Static shared libs have same package with different versions where
16639                // we internally use a synthetic package name to allow multiple versions
16640                // of the same package, therefore we need to compare signatures against
16641                // the package setting for the latest library version.
16642                PackageSetting signatureCheckPs = ps;
16643                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16644                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16645                    if (libraryEntry != null) {
16646                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16647                    }
16648                }
16649
16650                // Quick sanity check that we're signed correctly if updating;
16651                // we'll check this again later when scanning, but we want to
16652                // bail early here before tripping over redefined permissions.
16653                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16654                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16655                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16656                                + pkg.packageName + " upgrade keys do not match the "
16657                                + "previously installed version");
16658                        return;
16659                    }
16660                } else {
16661                    try {
16662                        verifySignaturesLP(signatureCheckPs, pkg);
16663                    } catch (PackageManagerException e) {
16664                        res.setError(e.error, e.getMessage());
16665                        return;
16666                    }
16667                }
16668
16669                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16670                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16671                    systemApp = (ps.pkg.applicationInfo.flags &
16672                            ApplicationInfo.FLAG_SYSTEM) != 0;
16673                }
16674                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16675            }
16676
16677            // Check whether the newly-scanned package wants to define an already-defined perm
16678            int N = pkg.permissions.size();
16679            for (int i = N-1; i >= 0; i--) {
16680                PackageParser.Permission perm = pkg.permissions.get(i);
16681                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16682                if (bp != null) {
16683                    // If the defining package is signed with our cert, it's okay.  This
16684                    // also includes the "updating the same package" case, of course.
16685                    // "updating same package" could also involve key-rotation.
16686                    final boolean sigsOk;
16687                    if (bp.sourcePackage.equals(pkg.packageName)
16688                            && (bp.packageSetting instanceof PackageSetting)
16689                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16690                                    scanFlags))) {
16691                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16692                    } else {
16693                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16694                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16695                    }
16696                    if (!sigsOk) {
16697                        // If the owning package is the system itself, we log but allow
16698                        // install to proceed; we fail the install on all other permission
16699                        // redefinitions.
16700                        if (!bp.sourcePackage.equals("android")) {
16701                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16702                                    + pkg.packageName + " attempting to redeclare permission "
16703                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16704                            res.origPermission = perm.info.name;
16705                            res.origPackage = bp.sourcePackage;
16706                            return;
16707                        } else {
16708                            Slog.w(TAG, "Package " + pkg.packageName
16709                                    + " attempting to redeclare system permission "
16710                                    + perm.info.name + "; ignoring new declaration");
16711                            pkg.permissions.remove(i);
16712                        }
16713                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16714                        // Prevent apps to change protection level to dangerous from any other
16715                        // type as this would allow a privilege escalation where an app adds a
16716                        // normal/signature permission in other app's group and later redefines
16717                        // it as dangerous leading to the group auto-grant.
16718                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16719                                == PermissionInfo.PROTECTION_DANGEROUS) {
16720                            if (bp != null && !bp.isRuntime()) {
16721                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16722                                        + "non-runtime permission " + perm.info.name
16723                                        + " to runtime; keeping old protection level");
16724                                perm.info.protectionLevel = bp.protectionLevel;
16725                            }
16726                        }
16727                    }
16728                }
16729            }
16730        }
16731
16732        if (systemApp) {
16733            if (onExternal) {
16734                // Abort update; system app can't be replaced with app on sdcard
16735                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16736                        "Cannot install updates to system apps on sdcard");
16737                return;
16738            } else if (ephemeral) {
16739                // Abort update; system app can't be replaced with an ephemeral app
16740                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
16741                        "Cannot update a system app with an ephemeral app");
16742                return;
16743            }
16744        }
16745
16746        if (args.move != null) {
16747            // We did an in-place move, so dex is ready to roll
16748            scanFlags |= SCAN_NO_DEX;
16749            scanFlags |= SCAN_MOVE;
16750
16751            synchronized (mPackages) {
16752                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16753                if (ps == null) {
16754                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16755                            "Missing settings for moved package " + pkgName);
16756                }
16757
16758                // We moved the entire application as-is, so bring over the
16759                // previously derived ABI information.
16760                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16761                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16762            }
16763
16764        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16765            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16766            scanFlags |= SCAN_NO_DEX;
16767
16768            try {
16769                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16770                    args.abiOverride : pkg.cpuAbiOverride);
16771                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16772                        true /*extractLibs*/, mAppLib32InstallDir);
16773            } catch (PackageManagerException pme) {
16774                Slog.e(TAG, "Error deriving application ABI", pme);
16775                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16776                return;
16777            }
16778
16779            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16780            // Do not run PackageDexOptimizer through the local performDexOpt
16781            // method because `pkg` may not be in `mPackages` yet.
16782            //
16783            // Also, don't fail application installs if the dexopt step fails.
16784            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16785                    null /* instructionSets */, false /* checkProfiles */,
16786                    getCompilerFilterForReason(REASON_INSTALL),
16787                    getOrCreateCompilerPackageStats(pkg));
16788            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16789
16790            // Notify BackgroundDexOptJobService that the package has been changed.
16791            // If this is an update of a package which used to fail to compile,
16792            // BDOS will remove it from its blacklist.
16793            // TODO: Layering violation
16794            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16795        }
16796
16797        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16798            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16799            return;
16800        }
16801
16802        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16803
16804        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16805                "installPackageLI")) {
16806            if (replace) {
16807                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16808                    // Static libs have a synthetic package name containing the version
16809                    // and cannot be updated as an update would get a new package name,
16810                    // unless this is the exact same version code which is useful for
16811                    // development.
16812                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16813                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16814                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16815                                + "static-shared libs cannot be updated");
16816                        return;
16817                    }
16818                }
16819                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16820                        installerPackageName, res, args.installReason);
16821            } else {
16822                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16823                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16824            }
16825        }
16826        synchronized (mPackages) {
16827            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16828            if (ps != null) {
16829                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16830            }
16831
16832            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16833            for (int i = 0; i < childCount; i++) {
16834                PackageParser.Package childPkg = pkg.childPackages.get(i);
16835                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16836                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16837                if (childPs != null) {
16838                    childRes.newUsers = childPs.queryInstalledUsers(
16839                            sUserManager.getUserIds(), true);
16840                }
16841            }
16842        }
16843    }
16844
16845    private void startIntentFilterVerifications(int userId, boolean replacing,
16846            PackageParser.Package pkg) {
16847        if (mIntentFilterVerifierComponent == null) {
16848            Slog.w(TAG, "No IntentFilter verification will not be done as "
16849                    + "there is no IntentFilterVerifier available!");
16850            return;
16851        }
16852
16853        final int verifierUid = getPackageUid(
16854                mIntentFilterVerifierComponent.getPackageName(),
16855                MATCH_DEBUG_TRIAGED_MISSING,
16856                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16857
16858        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16859        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16860        mHandler.sendMessage(msg);
16861
16862        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16863        for (int i = 0; i < childCount; i++) {
16864            PackageParser.Package childPkg = pkg.childPackages.get(i);
16865            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16866            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16867            mHandler.sendMessage(msg);
16868        }
16869    }
16870
16871    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16872            PackageParser.Package pkg) {
16873        int size = pkg.activities.size();
16874        if (size == 0) {
16875            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16876                    "No activity, so no need to verify any IntentFilter!");
16877            return;
16878        }
16879
16880        final boolean hasDomainURLs = hasDomainURLs(pkg);
16881        if (!hasDomainURLs) {
16882            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16883                    "No domain URLs, so no need to verify any IntentFilter!");
16884            return;
16885        }
16886
16887        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16888                + " if any IntentFilter from the " + size
16889                + " Activities needs verification ...");
16890
16891        int count = 0;
16892        final String packageName = pkg.packageName;
16893
16894        synchronized (mPackages) {
16895            // If this is a new install and we see that we've already run verification for this
16896            // package, we have nothing to do: it means the state was restored from backup.
16897            if (!replacing) {
16898                IntentFilterVerificationInfo ivi =
16899                        mSettings.getIntentFilterVerificationLPr(packageName);
16900                if (ivi != null) {
16901                    if (DEBUG_DOMAIN_VERIFICATION) {
16902                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16903                                + ivi.getStatusString());
16904                    }
16905                    return;
16906                }
16907            }
16908
16909            // If any filters need to be verified, then all need to be.
16910            boolean needToVerify = false;
16911            for (PackageParser.Activity a : pkg.activities) {
16912                for (ActivityIntentInfo filter : a.intents) {
16913                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16914                        if (DEBUG_DOMAIN_VERIFICATION) {
16915                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16916                        }
16917                        needToVerify = true;
16918                        break;
16919                    }
16920                }
16921            }
16922
16923            if (needToVerify) {
16924                final int verificationId = mIntentFilterVerificationToken++;
16925                for (PackageParser.Activity a : pkg.activities) {
16926                    for (ActivityIntentInfo filter : a.intents) {
16927                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16928                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16929                                    "Verification needed for IntentFilter:" + filter.toString());
16930                            mIntentFilterVerifier.addOneIntentFilterVerification(
16931                                    verifierUid, userId, verificationId, filter, packageName);
16932                            count++;
16933                        }
16934                    }
16935                }
16936            }
16937        }
16938
16939        if (count > 0) {
16940            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16941                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16942                    +  " for userId:" + userId);
16943            mIntentFilterVerifier.startVerifications(userId);
16944        } else {
16945            if (DEBUG_DOMAIN_VERIFICATION) {
16946                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16947            }
16948        }
16949    }
16950
16951    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16952        final ComponentName cn  = filter.activity.getComponentName();
16953        final String packageName = cn.getPackageName();
16954
16955        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16956                packageName);
16957        if (ivi == null) {
16958            return true;
16959        }
16960        int status = ivi.getStatus();
16961        switch (status) {
16962            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16963            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16964                return true;
16965
16966            default:
16967                // Nothing to do
16968                return false;
16969        }
16970    }
16971
16972    private static boolean isMultiArch(ApplicationInfo info) {
16973        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16974    }
16975
16976    private static boolean isExternal(PackageParser.Package pkg) {
16977        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16978    }
16979
16980    private static boolean isExternal(PackageSetting ps) {
16981        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16982    }
16983
16984    private static boolean isEphemeral(PackageParser.Package pkg) {
16985        return pkg.applicationInfo.isInstantApp();
16986    }
16987
16988    private static boolean isEphemeral(PackageSetting ps) {
16989        return ps.pkg != null && isEphemeral(ps.pkg);
16990    }
16991
16992    private static boolean isSystemApp(PackageParser.Package pkg) {
16993        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16994    }
16995
16996    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16997        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16998    }
16999
17000    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17001        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17002    }
17003
17004    private static boolean isSystemApp(PackageSetting ps) {
17005        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17006    }
17007
17008    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17009        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17010    }
17011
17012    private int packageFlagsToInstallFlags(PackageSetting ps) {
17013        int installFlags = 0;
17014        if (isEphemeral(ps)) {
17015            installFlags |= PackageManager.INSTALL_EPHEMERAL;
17016        }
17017        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17018            // This existing package was an external ASEC install when we have
17019            // the external flag without a UUID
17020            installFlags |= PackageManager.INSTALL_EXTERNAL;
17021        }
17022        if (ps.isForwardLocked()) {
17023            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17024        }
17025        return installFlags;
17026    }
17027
17028    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17029        if (isExternal(pkg)) {
17030            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17031                return StorageManager.UUID_PRIMARY_PHYSICAL;
17032            } else {
17033                return pkg.volumeUuid;
17034            }
17035        } else {
17036            return StorageManager.UUID_PRIVATE_INTERNAL;
17037        }
17038    }
17039
17040    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17041        if (isExternal(pkg)) {
17042            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17043                return mSettings.getExternalVersion();
17044            } else {
17045                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17046            }
17047        } else {
17048            return mSettings.getInternalVersion();
17049        }
17050    }
17051
17052    private void deleteTempPackageFiles() {
17053        final FilenameFilter filter = new FilenameFilter() {
17054            public boolean accept(File dir, String name) {
17055                return name.startsWith("vmdl") && name.endsWith(".tmp");
17056            }
17057        };
17058        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17059            file.delete();
17060        }
17061    }
17062
17063    @Override
17064    public void deletePackageAsUser(String packageName, int versionCode,
17065            IPackageDeleteObserver observer, int userId, int flags) {
17066        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17067                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17068    }
17069
17070    @Override
17071    public void deletePackageVersioned(VersionedPackage versionedPackage,
17072            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17073        mContext.enforceCallingOrSelfPermission(
17074                android.Manifest.permission.DELETE_PACKAGES, null);
17075        Preconditions.checkNotNull(versionedPackage);
17076        Preconditions.checkNotNull(observer);
17077        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17078                PackageManager.VERSION_CODE_HIGHEST,
17079                Integer.MAX_VALUE, "versionCode must be >= -1");
17080
17081        final String packageName = versionedPackage.getPackageName();
17082        // TODO: We will change version code to long, so in the new API it is long
17083        final int versionCode = (int) versionedPackage.getVersionCode();
17084        final String internalPackageName;
17085        synchronized (mPackages) {
17086            // Normalize package name to handle renamed packages and static libs
17087            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17088                    // TODO: We will change version code to long, so in the new API it is long
17089                    (int) versionedPackage.getVersionCode());
17090        }
17091
17092        final int uid = Binder.getCallingUid();
17093        if (!isOrphaned(internalPackageName)
17094                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17095            try {
17096                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17097                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17098                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17099                observer.onUserActionRequired(intent);
17100            } catch (RemoteException re) {
17101            }
17102            return;
17103        }
17104        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17105        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17106        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17107            mContext.enforceCallingOrSelfPermission(
17108                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17109                    "deletePackage for user " + userId);
17110        }
17111
17112        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17113            try {
17114                observer.onPackageDeleted(packageName,
17115                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17116            } catch (RemoteException re) {
17117            }
17118            return;
17119        }
17120
17121        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17122            try {
17123                observer.onPackageDeleted(packageName,
17124                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17125            } catch (RemoteException re) {
17126            }
17127            return;
17128        }
17129
17130        if (DEBUG_REMOVE) {
17131            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17132                    + " deleteAllUsers: " + deleteAllUsers + " version="
17133                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17134                    ? "VERSION_CODE_HIGHEST" : versionCode));
17135        }
17136        // Queue up an async operation since the package deletion may take a little while.
17137        mHandler.post(new Runnable() {
17138            public void run() {
17139                mHandler.removeCallbacks(this);
17140                int returnCode;
17141                if (!deleteAllUsers) {
17142                    returnCode = deletePackageX(internalPackageName, versionCode,
17143                            userId, deleteFlags);
17144                } else {
17145                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17146                            internalPackageName, users);
17147                    // If nobody is blocking uninstall, proceed with delete for all users
17148                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17149                        returnCode = deletePackageX(internalPackageName, versionCode,
17150                                userId, deleteFlags);
17151                    } else {
17152                        // Otherwise uninstall individually for users with blockUninstalls=false
17153                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17154                        for (int userId : users) {
17155                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17156                                returnCode = deletePackageX(internalPackageName, versionCode,
17157                                        userId, userFlags);
17158                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17159                                    Slog.w(TAG, "Package delete failed for user " + userId
17160                                            + ", returnCode " + returnCode);
17161                                }
17162                            }
17163                        }
17164                        // The app has only been marked uninstalled for certain users.
17165                        // We still need to report that delete was blocked
17166                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17167                    }
17168                }
17169                try {
17170                    observer.onPackageDeleted(packageName, returnCode, null);
17171                } catch (RemoteException e) {
17172                    Log.i(TAG, "Observer no longer exists.");
17173                } //end catch
17174            } //end run
17175        });
17176    }
17177
17178    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17179        if (pkg.staticSharedLibName != null) {
17180            return pkg.manifestPackageName;
17181        }
17182        return pkg.packageName;
17183    }
17184
17185    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17186        // Handle renamed packages
17187        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17188        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17189
17190        // Is this a static library?
17191        SparseArray<SharedLibraryEntry> versionedLib =
17192                mStaticLibsByDeclaringPackage.get(packageName);
17193        if (versionedLib == null || versionedLib.size() <= 0) {
17194            return packageName;
17195        }
17196
17197        // Figure out which lib versions the caller can see
17198        SparseIntArray versionsCallerCanSee = null;
17199        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17200        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17201                && callingAppId != Process.ROOT_UID) {
17202            versionsCallerCanSee = new SparseIntArray();
17203            String libName = versionedLib.valueAt(0).info.getName();
17204            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17205            if (uidPackages != null) {
17206                for (String uidPackage : uidPackages) {
17207                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17208                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17209                    if (libIdx >= 0) {
17210                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17211                        versionsCallerCanSee.append(libVersion, libVersion);
17212                    }
17213                }
17214            }
17215        }
17216
17217        // Caller can see nothing - done
17218        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17219            return packageName;
17220        }
17221
17222        // Find the version the caller can see and the app version code
17223        SharedLibraryEntry highestVersion = null;
17224        final int versionCount = versionedLib.size();
17225        for (int i = 0; i < versionCount; i++) {
17226            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17227            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17228                    libEntry.info.getVersion()) < 0) {
17229                continue;
17230            }
17231            // TODO: We will change version code to long, so in the new API it is long
17232            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17233            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17234                if (libVersionCode == versionCode) {
17235                    return libEntry.apk;
17236                }
17237            } else if (highestVersion == null) {
17238                highestVersion = libEntry;
17239            } else if (libVersionCode  > highestVersion.info
17240                    .getDeclaringPackage().getVersionCode()) {
17241                highestVersion = libEntry;
17242            }
17243        }
17244
17245        if (highestVersion != null) {
17246            return highestVersion.apk;
17247        }
17248
17249        return packageName;
17250    }
17251
17252    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17253        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17254              || callingUid == Process.SYSTEM_UID) {
17255            return true;
17256        }
17257        final int callingUserId = UserHandle.getUserId(callingUid);
17258        // If the caller installed the pkgName, then allow it to silently uninstall.
17259        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17260            return true;
17261        }
17262
17263        // Allow package verifier to silently uninstall.
17264        if (mRequiredVerifierPackage != null &&
17265                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17266            return true;
17267        }
17268
17269        // Allow package uninstaller to silently uninstall.
17270        if (mRequiredUninstallerPackage != null &&
17271                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17272            return true;
17273        }
17274
17275        // Allow storage manager to silently uninstall.
17276        if (mStorageManagerPackage != null &&
17277                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17278            return true;
17279        }
17280        return false;
17281    }
17282
17283    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17284        int[] result = EMPTY_INT_ARRAY;
17285        for (int userId : userIds) {
17286            if (getBlockUninstallForUser(packageName, userId)) {
17287                result = ArrayUtils.appendInt(result, userId);
17288            }
17289        }
17290        return result;
17291    }
17292
17293    @Override
17294    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17295        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17296    }
17297
17298    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17299        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17300                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17301        try {
17302            if (dpm != null) {
17303                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17304                        /* callingUserOnly =*/ false);
17305                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17306                        : deviceOwnerComponentName.getPackageName();
17307                // Does the package contains the device owner?
17308                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17309                // this check is probably not needed, since DO should be registered as a device
17310                // admin on some user too. (Original bug for this: b/17657954)
17311                if (packageName.equals(deviceOwnerPackageName)) {
17312                    return true;
17313                }
17314                // Does it contain a device admin for any user?
17315                int[] users;
17316                if (userId == UserHandle.USER_ALL) {
17317                    users = sUserManager.getUserIds();
17318                } else {
17319                    users = new int[]{userId};
17320                }
17321                for (int i = 0; i < users.length; ++i) {
17322                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17323                        return true;
17324                    }
17325                }
17326            }
17327        } catch (RemoteException e) {
17328        }
17329        return false;
17330    }
17331
17332    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17333        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17334    }
17335
17336    /**
17337     *  This method is an internal method that could be get invoked either
17338     *  to delete an installed package or to clean up a failed installation.
17339     *  After deleting an installed package, a broadcast is sent to notify any
17340     *  listeners that the package has been removed. For cleaning up a failed
17341     *  installation, the broadcast is not necessary since the package's
17342     *  installation wouldn't have sent the initial broadcast either
17343     *  The key steps in deleting a package are
17344     *  deleting the package information in internal structures like mPackages,
17345     *  deleting the packages base directories through installd
17346     *  updating mSettings to reflect current status
17347     *  persisting settings for later use
17348     *  sending a broadcast if necessary
17349     */
17350    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17351        final PackageRemovedInfo info = new PackageRemovedInfo();
17352        final boolean res;
17353
17354        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17355                ? UserHandle.USER_ALL : userId;
17356
17357        if (isPackageDeviceAdmin(packageName, removeUser)) {
17358            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17359            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17360        }
17361
17362        PackageSetting uninstalledPs = null;
17363
17364        // for the uninstall-updates case and restricted profiles, remember the per-
17365        // user handle installed state
17366        int[] allUsers;
17367        synchronized (mPackages) {
17368            uninstalledPs = mSettings.mPackages.get(packageName);
17369            if (uninstalledPs == null) {
17370                Slog.w(TAG, "Not removing non-existent package " + packageName);
17371                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17372            }
17373
17374            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17375                    && uninstalledPs.versionCode != versionCode) {
17376                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17377                        + uninstalledPs.versionCode + " != " + versionCode);
17378                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17379            }
17380
17381            // Static shared libs can be declared by any package, so let us not
17382            // allow removing a package if it provides a lib others depend on.
17383            PackageParser.Package pkg = mPackages.get(packageName);
17384            if (pkg != null && pkg.staticSharedLibName != null) {
17385                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17386                        pkg.staticSharedLibVersion);
17387                if (libEntry != null) {
17388                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17389                            libEntry.info, 0, userId);
17390                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17391                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17392                                + " hosting lib " + libEntry.info.getName() + " version "
17393                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17394                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17395                    }
17396                }
17397            }
17398
17399            allUsers = sUserManager.getUserIds();
17400            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17401        }
17402
17403        final int freezeUser;
17404        if (isUpdatedSystemApp(uninstalledPs)
17405                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17406            // We're downgrading a system app, which will apply to all users, so
17407            // freeze them all during the downgrade
17408            freezeUser = UserHandle.USER_ALL;
17409        } else {
17410            freezeUser = removeUser;
17411        }
17412
17413        synchronized (mInstallLock) {
17414            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17415            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17416                    deleteFlags, "deletePackageX")) {
17417                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17418                        deleteFlags | REMOVE_CHATTY, info, true, null);
17419            }
17420            synchronized (mPackages) {
17421                if (res) {
17422                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17423                            info.removedUsers);
17424                }
17425            }
17426        }
17427
17428        if (res) {
17429            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17430            info.sendPackageRemovedBroadcasts(killApp);
17431            info.sendSystemPackageUpdatedBroadcasts();
17432            info.sendSystemPackageAppearedBroadcasts();
17433        }
17434        // Force a gc here.
17435        Runtime.getRuntime().gc();
17436        // Delete the resources here after sending the broadcast to let
17437        // other processes clean up before deleting resources.
17438        if (info.args != null) {
17439            synchronized (mInstallLock) {
17440                info.args.doPostDeleteLI(true);
17441            }
17442        }
17443
17444        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17445    }
17446
17447    class PackageRemovedInfo {
17448        String removedPackage;
17449        int uid = -1;
17450        int removedAppId = -1;
17451        int[] origUsers;
17452        int[] removedUsers = null;
17453        SparseArray<Integer> installReasons;
17454        boolean isRemovedPackageSystemUpdate = false;
17455        boolean isUpdate;
17456        boolean dataRemoved;
17457        boolean removedForAllUsers;
17458        boolean isStaticSharedLib;
17459        // Clean up resources deleted packages.
17460        InstallArgs args = null;
17461        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17462        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17463
17464        void sendPackageRemovedBroadcasts(boolean killApp) {
17465            sendPackageRemovedBroadcastInternal(killApp);
17466            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17467            for (int i = 0; i < childCount; i++) {
17468                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17469                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17470            }
17471        }
17472
17473        void sendSystemPackageUpdatedBroadcasts() {
17474            if (isRemovedPackageSystemUpdate) {
17475                sendSystemPackageUpdatedBroadcastsInternal();
17476                final int childCount = (removedChildPackages != null)
17477                        ? removedChildPackages.size() : 0;
17478                for (int i = 0; i < childCount; i++) {
17479                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17480                    if (childInfo.isRemovedPackageSystemUpdate) {
17481                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17482                    }
17483                }
17484            }
17485        }
17486
17487        void sendSystemPackageAppearedBroadcasts() {
17488            final int packageCount = (appearedChildPackages != null)
17489                    ? appearedChildPackages.size() : 0;
17490            for (int i = 0; i < packageCount; i++) {
17491                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17492                sendPackageAddedForNewUsers(installedInfo.name, true,
17493                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17494            }
17495        }
17496
17497        private void sendSystemPackageUpdatedBroadcastsInternal() {
17498            Bundle extras = new Bundle(2);
17499            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17500            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17501            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17502                    extras, 0, null, null, null);
17503            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17504                    extras, 0, null, null, null);
17505            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17506                    null, 0, removedPackage, null, null);
17507        }
17508
17509        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17510            // Don't send static shared library removal broadcasts as these
17511            // libs are visible only the the apps that depend on them an one
17512            // cannot remove the library if it has a dependency.
17513            if (isStaticSharedLib) {
17514                return;
17515            }
17516            Bundle extras = new Bundle(2);
17517            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17518            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17519            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17520            if (isUpdate || isRemovedPackageSystemUpdate) {
17521                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17522            }
17523            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17524            if (removedPackage != null) {
17525                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17526                        extras, 0, null, null, removedUsers);
17527                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17528                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17529                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17530                            null, null, removedUsers);
17531                }
17532            }
17533            if (removedAppId >= 0) {
17534                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17535                        removedUsers);
17536            }
17537        }
17538    }
17539
17540    /*
17541     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17542     * flag is not set, the data directory is removed as well.
17543     * make sure this flag is set for partially installed apps. If not its meaningless to
17544     * delete a partially installed application.
17545     */
17546    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17547            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17548        String packageName = ps.name;
17549        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17550        // Retrieve object to delete permissions for shared user later on
17551        final PackageParser.Package deletedPkg;
17552        final PackageSetting deletedPs;
17553        // reader
17554        synchronized (mPackages) {
17555            deletedPkg = mPackages.get(packageName);
17556            deletedPs = mSettings.mPackages.get(packageName);
17557            if (outInfo != null) {
17558                outInfo.removedPackage = packageName;
17559                outInfo.isStaticSharedLib = deletedPkg != null
17560                        && deletedPkg.staticSharedLibName != null;
17561                outInfo.removedUsers = deletedPs != null
17562                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17563                        : null;
17564            }
17565        }
17566
17567        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
17568
17569        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17570            final PackageParser.Package resolvedPkg;
17571            if (deletedPkg != null) {
17572                resolvedPkg = deletedPkg;
17573            } else {
17574                // We don't have a parsed package when it lives on an ejected
17575                // adopted storage device, so fake something together
17576                resolvedPkg = new PackageParser.Package(ps.name);
17577                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17578            }
17579            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17580                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17581            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17582            if (outInfo != null) {
17583                outInfo.dataRemoved = true;
17584            }
17585            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17586        }
17587
17588        int removedAppId = -1;
17589
17590        // writer
17591        synchronized (mPackages) {
17592            if (deletedPs != null) {
17593                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17594                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17595                    clearDefaultBrowserIfNeeded(packageName);
17596                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17597                    removedAppId = mSettings.removePackageLPw(packageName);
17598                    if (outInfo != null) {
17599                        outInfo.removedAppId = removedAppId;
17600                    }
17601                    updatePermissionsLPw(deletedPs.name, null, 0);
17602                    if (deletedPs.sharedUser != null) {
17603                        // Remove permissions associated with package. Since runtime
17604                        // permissions are per user we have to kill the removed package
17605                        // or packages running under the shared user of the removed
17606                        // package if revoking the permissions requested only by the removed
17607                        // package is successful and this causes a change in gids.
17608                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17609                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17610                                    userId);
17611                            if (userIdToKill == UserHandle.USER_ALL
17612                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17613                                // If gids changed for this user, kill all affected packages.
17614                                mHandler.post(new Runnable() {
17615                                    @Override
17616                                    public void run() {
17617                                        // This has to happen with no lock held.
17618                                        killApplication(deletedPs.name, deletedPs.appId,
17619                                                KILL_APP_REASON_GIDS_CHANGED);
17620                                    }
17621                                });
17622                                break;
17623                            }
17624                        }
17625                    }
17626                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17627                }
17628                // make sure to preserve per-user disabled state if this removal was just
17629                // a downgrade of a system app to the factory package
17630                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17631                    if (DEBUG_REMOVE) {
17632                        Slog.d(TAG, "Propagating install state across downgrade");
17633                    }
17634                    for (int userId : allUserHandles) {
17635                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17636                        if (DEBUG_REMOVE) {
17637                            Slog.d(TAG, "    user " + userId + " => " + installed);
17638                        }
17639                        ps.setInstalled(installed, userId);
17640                    }
17641                }
17642            }
17643            // can downgrade to reader
17644            if (writeSettings) {
17645                // Save settings now
17646                mSettings.writeLPr();
17647            }
17648        }
17649        if (removedAppId != -1) {
17650            // A user ID was deleted here. Go through all users and remove it
17651            // from KeyStore.
17652            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17653        }
17654    }
17655
17656    static boolean locationIsPrivileged(File path) {
17657        try {
17658            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17659                    .getCanonicalPath();
17660            return path.getCanonicalPath().startsWith(privilegedAppDir);
17661        } catch (IOException e) {
17662            Slog.e(TAG, "Unable to access code path " + path);
17663        }
17664        return false;
17665    }
17666
17667    /*
17668     * Tries to delete system package.
17669     */
17670    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17671            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17672            boolean writeSettings) {
17673        if (deletedPs.parentPackageName != null) {
17674            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17675            return false;
17676        }
17677
17678        final boolean applyUserRestrictions
17679                = (allUserHandles != null) && (outInfo.origUsers != null);
17680        final PackageSetting disabledPs;
17681        // Confirm if the system package has been updated
17682        // An updated system app can be deleted. This will also have to restore
17683        // the system pkg from system partition
17684        // reader
17685        synchronized (mPackages) {
17686            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17687        }
17688
17689        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17690                + " disabledPs=" + disabledPs);
17691
17692        if (disabledPs == null) {
17693            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17694            return false;
17695        } else if (DEBUG_REMOVE) {
17696            Slog.d(TAG, "Deleting system pkg from data partition");
17697        }
17698
17699        if (DEBUG_REMOVE) {
17700            if (applyUserRestrictions) {
17701                Slog.d(TAG, "Remembering install states:");
17702                for (int userId : allUserHandles) {
17703                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17704                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17705                }
17706            }
17707        }
17708
17709        // Delete the updated package
17710        outInfo.isRemovedPackageSystemUpdate = true;
17711        if (outInfo.removedChildPackages != null) {
17712            final int childCount = (deletedPs.childPackageNames != null)
17713                    ? deletedPs.childPackageNames.size() : 0;
17714            for (int i = 0; i < childCount; i++) {
17715                String childPackageName = deletedPs.childPackageNames.get(i);
17716                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17717                        .contains(childPackageName)) {
17718                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17719                            childPackageName);
17720                    if (childInfo != null) {
17721                        childInfo.isRemovedPackageSystemUpdate = true;
17722                    }
17723                }
17724            }
17725        }
17726
17727        if (disabledPs.versionCode < deletedPs.versionCode) {
17728            // Delete data for downgrades
17729            flags &= ~PackageManager.DELETE_KEEP_DATA;
17730        } else {
17731            // Preserve data by setting flag
17732            flags |= PackageManager.DELETE_KEEP_DATA;
17733        }
17734
17735        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17736                outInfo, writeSettings, disabledPs.pkg);
17737        if (!ret) {
17738            return false;
17739        }
17740
17741        // writer
17742        synchronized (mPackages) {
17743            // Reinstate the old system package
17744            enableSystemPackageLPw(disabledPs.pkg);
17745            // Remove any native libraries from the upgraded package.
17746            removeNativeBinariesLI(deletedPs);
17747        }
17748
17749        // Install the system package
17750        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17751        int parseFlags = mDefParseFlags
17752                | PackageParser.PARSE_MUST_BE_APK
17753                | PackageParser.PARSE_IS_SYSTEM
17754                | PackageParser.PARSE_IS_SYSTEM_DIR;
17755        if (locationIsPrivileged(disabledPs.codePath)) {
17756            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17757        }
17758
17759        final PackageParser.Package newPkg;
17760        try {
17761            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17762                0 /* currentTime */, null);
17763        } catch (PackageManagerException e) {
17764            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17765                    + e.getMessage());
17766            return false;
17767        }
17768
17769        try {
17770            // update shared libraries for the newly re-installed system package
17771            updateSharedLibrariesLPr(newPkg, null);
17772        } catch (PackageManagerException e) {
17773            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17774        }
17775
17776        prepareAppDataAfterInstallLIF(newPkg);
17777
17778        // writer
17779        synchronized (mPackages) {
17780            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17781
17782            // Propagate the permissions state as we do not want to drop on the floor
17783            // runtime permissions. The update permissions method below will take
17784            // care of removing obsolete permissions and grant install permissions.
17785            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17786            updatePermissionsLPw(newPkg.packageName, newPkg,
17787                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17788
17789            if (applyUserRestrictions) {
17790                if (DEBUG_REMOVE) {
17791                    Slog.d(TAG, "Propagating install state across reinstall");
17792                }
17793                for (int userId : allUserHandles) {
17794                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17795                    if (DEBUG_REMOVE) {
17796                        Slog.d(TAG, "    user " + userId + " => " + installed);
17797                    }
17798                    ps.setInstalled(installed, userId);
17799
17800                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17801                }
17802                // Regardless of writeSettings we need to ensure that this restriction
17803                // state propagation is persisted
17804                mSettings.writeAllUsersPackageRestrictionsLPr();
17805            }
17806            // can downgrade to reader here
17807            if (writeSettings) {
17808                mSettings.writeLPr();
17809            }
17810        }
17811        return true;
17812    }
17813
17814    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17815            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17816            PackageRemovedInfo outInfo, boolean writeSettings,
17817            PackageParser.Package replacingPackage) {
17818        synchronized (mPackages) {
17819            if (outInfo != null) {
17820                outInfo.uid = ps.appId;
17821            }
17822
17823            if (outInfo != null && outInfo.removedChildPackages != null) {
17824                final int childCount = (ps.childPackageNames != null)
17825                        ? ps.childPackageNames.size() : 0;
17826                for (int i = 0; i < childCount; i++) {
17827                    String childPackageName = ps.childPackageNames.get(i);
17828                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17829                    if (childPs == null) {
17830                        return false;
17831                    }
17832                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17833                            childPackageName);
17834                    if (childInfo != null) {
17835                        childInfo.uid = childPs.appId;
17836                    }
17837                }
17838            }
17839        }
17840
17841        // Delete package data from internal structures and also remove data if flag is set
17842        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17843
17844        // Delete the child packages data
17845        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17846        for (int i = 0; i < childCount; i++) {
17847            PackageSetting childPs;
17848            synchronized (mPackages) {
17849                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17850            }
17851            if (childPs != null) {
17852                PackageRemovedInfo childOutInfo = (outInfo != null
17853                        && outInfo.removedChildPackages != null)
17854                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17855                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17856                        && (replacingPackage != null
17857                        && !replacingPackage.hasChildPackage(childPs.name))
17858                        ? flags & ~DELETE_KEEP_DATA : flags;
17859                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17860                        deleteFlags, writeSettings);
17861            }
17862        }
17863
17864        // Delete application code and resources only for parent packages
17865        if (ps.parentPackageName == null) {
17866            if (deleteCodeAndResources && (outInfo != null)) {
17867                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17868                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17869                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17870            }
17871        }
17872
17873        return true;
17874    }
17875
17876    @Override
17877    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17878            int userId) {
17879        mContext.enforceCallingOrSelfPermission(
17880                android.Manifest.permission.DELETE_PACKAGES, null);
17881        synchronized (mPackages) {
17882            PackageSetting ps = mSettings.mPackages.get(packageName);
17883            if (ps == null) {
17884                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17885                return false;
17886            }
17887            // Cannot block uninstall of static shared libs as they are
17888            // considered a part of the using app (emulating static linking).
17889            // Also static libs are installed always on internal storage.
17890            PackageParser.Package pkg = mPackages.get(packageName);
17891            if (pkg != null && pkg.staticSharedLibName != null) {
17892                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17893                        + " providing static shared library: " + pkg.staticSharedLibName);
17894                return false;
17895            }
17896            if (!ps.getInstalled(userId)) {
17897                // Can't block uninstall for an app that is not installed or enabled.
17898                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17899                return false;
17900            }
17901            ps.setBlockUninstall(blockUninstall, userId);
17902            mSettings.writePackageRestrictionsLPr(userId);
17903        }
17904        return true;
17905    }
17906
17907    @Override
17908    public boolean getBlockUninstallForUser(String packageName, int userId) {
17909        synchronized (mPackages) {
17910            PackageSetting ps = mSettings.mPackages.get(packageName);
17911            if (ps == null) {
17912                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17913                return false;
17914            }
17915            return ps.getBlockUninstall(userId);
17916        }
17917    }
17918
17919    @Override
17920    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17921        int callingUid = Binder.getCallingUid();
17922        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17923            throw new SecurityException(
17924                    "setRequiredForSystemUser can only be run by the system or root");
17925        }
17926        synchronized (mPackages) {
17927            PackageSetting ps = mSettings.mPackages.get(packageName);
17928            if (ps == null) {
17929                Log.w(TAG, "Package doesn't exist: " + packageName);
17930                return false;
17931            }
17932            if (systemUserApp) {
17933                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17934            } else {
17935                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17936            }
17937            mSettings.writeLPr();
17938        }
17939        return true;
17940    }
17941
17942    /*
17943     * This method handles package deletion in general
17944     */
17945    private boolean deletePackageLIF(String packageName, UserHandle user,
17946            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17947            PackageRemovedInfo outInfo, boolean writeSettings,
17948            PackageParser.Package replacingPackage) {
17949        if (packageName == null) {
17950            Slog.w(TAG, "Attempt to delete null packageName.");
17951            return false;
17952        }
17953
17954        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17955
17956        PackageSetting ps;
17957        synchronized (mPackages) {
17958            ps = mSettings.mPackages.get(packageName);
17959            if (ps == null) {
17960                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17961                return false;
17962            }
17963
17964            if (ps.parentPackageName != null && (!isSystemApp(ps)
17965                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17966                if (DEBUG_REMOVE) {
17967                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17968                            + ((user == null) ? UserHandle.USER_ALL : user));
17969                }
17970                final int removedUserId = (user != null) ? user.getIdentifier()
17971                        : UserHandle.USER_ALL;
17972                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17973                    return false;
17974                }
17975                markPackageUninstalledForUserLPw(ps, user);
17976                scheduleWritePackageRestrictionsLocked(user);
17977                return true;
17978            }
17979        }
17980
17981        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17982                && user.getIdentifier() != UserHandle.USER_ALL)) {
17983            // The caller is asking that the package only be deleted for a single
17984            // user.  To do this, we just mark its uninstalled state and delete
17985            // its data. If this is a system app, we only allow this to happen if
17986            // they have set the special DELETE_SYSTEM_APP which requests different
17987            // semantics than normal for uninstalling system apps.
17988            markPackageUninstalledForUserLPw(ps, user);
17989
17990            if (!isSystemApp(ps)) {
17991                // Do not uninstall the APK if an app should be cached
17992                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17993                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17994                    // Other user still have this package installed, so all
17995                    // we need to do is clear this user's data and save that
17996                    // it is uninstalled.
17997                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17998                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17999                        return false;
18000                    }
18001                    scheduleWritePackageRestrictionsLocked(user);
18002                    return true;
18003                } else {
18004                    // We need to set it back to 'installed' so the uninstall
18005                    // broadcasts will be sent correctly.
18006                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18007                    ps.setInstalled(true, user.getIdentifier());
18008                }
18009            } else {
18010                // This is a system app, so we assume that the
18011                // other users still have this package installed, so all
18012                // we need to do is clear this user's data and save that
18013                // it is uninstalled.
18014                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18015                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18016                    return false;
18017                }
18018                scheduleWritePackageRestrictionsLocked(user);
18019                return true;
18020            }
18021        }
18022
18023        // If we are deleting a composite package for all users, keep track
18024        // of result for each child.
18025        if (ps.childPackageNames != null && outInfo != null) {
18026            synchronized (mPackages) {
18027                final int childCount = ps.childPackageNames.size();
18028                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18029                for (int i = 0; i < childCount; i++) {
18030                    String childPackageName = ps.childPackageNames.get(i);
18031                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18032                    childInfo.removedPackage = childPackageName;
18033                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18034                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18035                    if (childPs != null) {
18036                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18037                    }
18038                }
18039            }
18040        }
18041
18042        boolean ret = false;
18043        if (isSystemApp(ps)) {
18044            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18045            // When an updated system application is deleted we delete the existing resources
18046            // as well and fall back to existing code in system partition
18047            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18048        } else {
18049            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18050            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18051                    outInfo, writeSettings, replacingPackage);
18052        }
18053
18054        // Take a note whether we deleted the package for all users
18055        if (outInfo != null) {
18056            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18057            if (outInfo.removedChildPackages != null) {
18058                synchronized (mPackages) {
18059                    final int childCount = outInfo.removedChildPackages.size();
18060                    for (int i = 0; i < childCount; i++) {
18061                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18062                        if (childInfo != null) {
18063                            childInfo.removedForAllUsers = mPackages.get(
18064                                    childInfo.removedPackage) == null;
18065                        }
18066                    }
18067                }
18068            }
18069            // If we uninstalled an update to a system app there may be some
18070            // child packages that appeared as they are declared in the system
18071            // app but were not declared in the update.
18072            if (isSystemApp(ps)) {
18073                synchronized (mPackages) {
18074                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18075                    final int childCount = (updatedPs.childPackageNames != null)
18076                            ? updatedPs.childPackageNames.size() : 0;
18077                    for (int i = 0; i < childCount; i++) {
18078                        String childPackageName = updatedPs.childPackageNames.get(i);
18079                        if (outInfo.removedChildPackages == null
18080                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18081                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18082                            if (childPs == null) {
18083                                continue;
18084                            }
18085                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18086                            installRes.name = childPackageName;
18087                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18088                            installRes.pkg = mPackages.get(childPackageName);
18089                            installRes.uid = childPs.pkg.applicationInfo.uid;
18090                            if (outInfo.appearedChildPackages == null) {
18091                                outInfo.appearedChildPackages = new ArrayMap<>();
18092                            }
18093                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18094                        }
18095                    }
18096                }
18097            }
18098        }
18099
18100        return ret;
18101    }
18102
18103    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18104        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18105                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18106        for (int nextUserId : userIds) {
18107            if (DEBUG_REMOVE) {
18108                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18109            }
18110            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18111                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
18112                    false /*hidden*/, false /*suspended*/, null, null, null,
18113                    false /*blockUninstall*/,
18114                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
18115                    PackageManager.INSTALL_REASON_UNKNOWN);
18116        }
18117    }
18118
18119    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18120            PackageRemovedInfo outInfo) {
18121        final PackageParser.Package pkg;
18122        synchronized (mPackages) {
18123            pkg = mPackages.get(ps.name);
18124        }
18125
18126        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18127                : new int[] {userId};
18128        for (int nextUserId : userIds) {
18129            if (DEBUG_REMOVE) {
18130                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18131                        + nextUserId);
18132            }
18133
18134            destroyAppDataLIF(pkg, userId,
18135                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18136            destroyAppProfilesLIF(pkg, userId);
18137            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18138            schedulePackageCleaning(ps.name, nextUserId, false);
18139            synchronized (mPackages) {
18140                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18141                    scheduleWritePackageRestrictionsLocked(nextUserId);
18142                }
18143                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18144            }
18145        }
18146
18147        if (outInfo != null) {
18148            outInfo.removedPackage = ps.name;
18149            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18150            outInfo.removedAppId = ps.appId;
18151            outInfo.removedUsers = userIds;
18152        }
18153
18154        return true;
18155    }
18156
18157    private final class ClearStorageConnection implements ServiceConnection {
18158        IMediaContainerService mContainerService;
18159
18160        @Override
18161        public void onServiceConnected(ComponentName name, IBinder service) {
18162            synchronized (this) {
18163                mContainerService = IMediaContainerService.Stub
18164                        .asInterface(Binder.allowBlocking(service));
18165                notifyAll();
18166            }
18167        }
18168
18169        @Override
18170        public void onServiceDisconnected(ComponentName name) {
18171        }
18172    }
18173
18174    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18175        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18176
18177        final boolean mounted;
18178        if (Environment.isExternalStorageEmulated()) {
18179            mounted = true;
18180        } else {
18181            final String status = Environment.getExternalStorageState();
18182
18183            mounted = status.equals(Environment.MEDIA_MOUNTED)
18184                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18185        }
18186
18187        if (!mounted) {
18188            return;
18189        }
18190
18191        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18192        int[] users;
18193        if (userId == UserHandle.USER_ALL) {
18194            users = sUserManager.getUserIds();
18195        } else {
18196            users = new int[] { userId };
18197        }
18198        final ClearStorageConnection conn = new ClearStorageConnection();
18199        if (mContext.bindServiceAsUser(
18200                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18201            try {
18202                for (int curUser : users) {
18203                    long timeout = SystemClock.uptimeMillis() + 5000;
18204                    synchronized (conn) {
18205                        long now;
18206                        while (conn.mContainerService == null &&
18207                                (now = SystemClock.uptimeMillis()) < timeout) {
18208                            try {
18209                                conn.wait(timeout - now);
18210                            } catch (InterruptedException e) {
18211                            }
18212                        }
18213                    }
18214                    if (conn.mContainerService == null) {
18215                        return;
18216                    }
18217
18218                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18219                    clearDirectory(conn.mContainerService,
18220                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18221                    if (allData) {
18222                        clearDirectory(conn.mContainerService,
18223                                userEnv.buildExternalStorageAppDataDirs(packageName));
18224                        clearDirectory(conn.mContainerService,
18225                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18226                    }
18227                }
18228            } finally {
18229                mContext.unbindService(conn);
18230            }
18231        }
18232    }
18233
18234    @Override
18235    public void clearApplicationProfileData(String packageName) {
18236        enforceSystemOrRoot("Only the system can clear all profile data");
18237
18238        final PackageParser.Package pkg;
18239        synchronized (mPackages) {
18240            pkg = mPackages.get(packageName);
18241        }
18242
18243        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18244            synchronized (mInstallLock) {
18245                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18246                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18247                        true /* removeBaseMarker */);
18248            }
18249        }
18250    }
18251
18252    @Override
18253    public void clearApplicationUserData(final String packageName,
18254            final IPackageDataObserver observer, final int userId) {
18255        mContext.enforceCallingOrSelfPermission(
18256                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18257
18258        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18259                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18260
18261        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18262            throw new SecurityException("Cannot clear data for a protected package: "
18263                    + packageName);
18264        }
18265        // Queue up an async operation since the package deletion may take a little while.
18266        mHandler.post(new Runnable() {
18267            public void run() {
18268                mHandler.removeCallbacks(this);
18269                final boolean succeeded;
18270                try (PackageFreezer freezer = freezePackage(packageName,
18271                        "clearApplicationUserData")) {
18272                    synchronized (mInstallLock) {
18273                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18274                    }
18275                    clearExternalStorageDataSync(packageName, userId, true);
18276                    synchronized (mPackages) {
18277                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18278                                packageName, userId);
18279                    }
18280                }
18281                if (succeeded) {
18282                    // invoke DeviceStorageMonitor's update method to clear any notifications
18283                    DeviceStorageMonitorInternal dsm = LocalServices
18284                            .getService(DeviceStorageMonitorInternal.class);
18285                    if (dsm != null) {
18286                        dsm.checkMemory();
18287                    }
18288                }
18289                if(observer != null) {
18290                    try {
18291                        observer.onRemoveCompleted(packageName, succeeded);
18292                    } catch (RemoteException e) {
18293                        Log.i(TAG, "Observer no longer exists.");
18294                    }
18295                } //end if observer
18296            } //end run
18297        });
18298    }
18299
18300    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18301        if (packageName == null) {
18302            Slog.w(TAG, "Attempt to delete null packageName.");
18303            return false;
18304        }
18305
18306        // Try finding details about the requested package
18307        PackageParser.Package pkg;
18308        synchronized (mPackages) {
18309            pkg = mPackages.get(packageName);
18310            if (pkg == null) {
18311                final PackageSetting ps = mSettings.mPackages.get(packageName);
18312                if (ps != null) {
18313                    pkg = ps.pkg;
18314                }
18315            }
18316
18317            if (pkg == null) {
18318                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18319                return false;
18320            }
18321
18322            PackageSetting ps = (PackageSetting) pkg.mExtras;
18323            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18324        }
18325
18326        clearAppDataLIF(pkg, userId,
18327                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18328
18329        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18330        removeKeystoreDataIfNeeded(userId, appId);
18331
18332        UserManagerInternal umInternal = getUserManagerInternal();
18333        final int flags;
18334        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18335            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18336        } else if (umInternal.isUserRunning(userId)) {
18337            flags = StorageManager.FLAG_STORAGE_DE;
18338        } else {
18339            flags = 0;
18340        }
18341        prepareAppDataContentsLIF(pkg, userId, flags);
18342
18343        return true;
18344    }
18345
18346    /**
18347     * Reverts user permission state changes (permissions and flags) in
18348     * all packages for a given user.
18349     *
18350     * @param userId The device user for which to do a reset.
18351     */
18352    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18353        final int packageCount = mPackages.size();
18354        for (int i = 0; i < packageCount; i++) {
18355            PackageParser.Package pkg = mPackages.valueAt(i);
18356            PackageSetting ps = (PackageSetting) pkg.mExtras;
18357            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18358        }
18359    }
18360
18361    private void resetNetworkPolicies(int userId) {
18362        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18363    }
18364
18365    /**
18366     * Reverts user permission state changes (permissions and flags).
18367     *
18368     * @param ps The package for which to reset.
18369     * @param userId The device user for which to do a reset.
18370     */
18371    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18372            final PackageSetting ps, final int userId) {
18373        if (ps.pkg == null) {
18374            return;
18375        }
18376
18377        // These are flags that can change base on user actions.
18378        final int userSettableMask = FLAG_PERMISSION_USER_SET
18379                | FLAG_PERMISSION_USER_FIXED
18380                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18381                | FLAG_PERMISSION_REVIEW_REQUIRED;
18382
18383        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18384                | FLAG_PERMISSION_POLICY_FIXED;
18385
18386        boolean writeInstallPermissions = false;
18387        boolean writeRuntimePermissions = false;
18388
18389        final int permissionCount = ps.pkg.requestedPermissions.size();
18390        for (int i = 0; i < permissionCount; i++) {
18391            String permission = ps.pkg.requestedPermissions.get(i);
18392
18393            BasePermission bp = mSettings.mPermissions.get(permission);
18394            if (bp == null) {
18395                continue;
18396            }
18397
18398            // If shared user we just reset the state to which only this app contributed.
18399            if (ps.sharedUser != null) {
18400                boolean used = false;
18401                final int packageCount = ps.sharedUser.packages.size();
18402                for (int j = 0; j < packageCount; j++) {
18403                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18404                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18405                            && pkg.pkg.requestedPermissions.contains(permission)) {
18406                        used = true;
18407                        break;
18408                    }
18409                }
18410                if (used) {
18411                    continue;
18412                }
18413            }
18414
18415            PermissionsState permissionsState = ps.getPermissionsState();
18416
18417            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18418
18419            // Always clear the user settable flags.
18420            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18421                    bp.name) != null;
18422            // If permission review is enabled and this is a legacy app, mark the
18423            // permission as requiring a review as this is the initial state.
18424            int flags = 0;
18425            if (mPermissionReviewRequired
18426                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18427                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18428            }
18429            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18430                if (hasInstallState) {
18431                    writeInstallPermissions = true;
18432                } else {
18433                    writeRuntimePermissions = true;
18434                }
18435            }
18436
18437            // Below is only runtime permission handling.
18438            if (!bp.isRuntime()) {
18439                continue;
18440            }
18441
18442            // Never clobber system or policy.
18443            if ((oldFlags & policyOrSystemFlags) != 0) {
18444                continue;
18445            }
18446
18447            // If this permission was granted by default, make sure it is.
18448            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18449                if (permissionsState.grantRuntimePermission(bp, userId)
18450                        != PERMISSION_OPERATION_FAILURE) {
18451                    writeRuntimePermissions = true;
18452                }
18453            // If permission review is enabled the permissions for a legacy apps
18454            // are represented as constantly granted runtime ones, so don't revoke.
18455            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18456                // Otherwise, reset the permission.
18457                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18458                switch (revokeResult) {
18459                    case PERMISSION_OPERATION_SUCCESS:
18460                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18461                        writeRuntimePermissions = true;
18462                        final int appId = ps.appId;
18463                        mHandler.post(new Runnable() {
18464                            @Override
18465                            public void run() {
18466                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18467                            }
18468                        });
18469                    } break;
18470                }
18471            }
18472        }
18473
18474        // Synchronously write as we are taking permissions away.
18475        if (writeRuntimePermissions) {
18476            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18477        }
18478
18479        // Synchronously write as we are taking permissions away.
18480        if (writeInstallPermissions) {
18481            mSettings.writeLPr();
18482        }
18483    }
18484
18485    /**
18486     * Remove entries from the keystore daemon. Will only remove it if the
18487     * {@code appId} is valid.
18488     */
18489    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18490        if (appId < 0) {
18491            return;
18492        }
18493
18494        final KeyStore keyStore = KeyStore.getInstance();
18495        if (keyStore != null) {
18496            if (userId == UserHandle.USER_ALL) {
18497                for (final int individual : sUserManager.getUserIds()) {
18498                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18499                }
18500            } else {
18501                keyStore.clearUid(UserHandle.getUid(userId, appId));
18502            }
18503        } else {
18504            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18505        }
18506    }
18507
18508    @Override
18509    public void deleteApplicationCacheFiles(final String packageName,
18510            final IPackageDataObserver observer) {
18511        final int userId = UserHandle.getCallingUserId();
18512        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18513    }
18514
18515    @Override
18516    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18517            final IPackageDataObserver observer) {
18518        mContext.enforceCallingOrSelfPermission(
18519                android.Manifest.permission.DELETE_CACHE_FILES, null);
18520        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18521                /* requireFullPermission= */ true, /* checkShell= */ false,
18522                "delete application cache files");
18523
18524        final PackageParser.Package pkg;
18525        synchronized (mPackages) {
18526            pkg = mPackages.get(packageName);
18527        }
18528
18529        // Queue up an async operation since the package deletion may take a little while.
18530        mHandler.post(new Runnable() {
18531            public void run() {
18532                synchronized (mInstallLock) {
18533                    final int flags = StorageManager.FLAG_STORAGE_DE
18534                            | StorageManager.FLAG_STORAGE_CE;
18535                    // We're only clearing cache files, so we don't care if the
18536                    // app is unfrozen and still able to run
18537                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18538                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18539                }
18540                clearExternalStorageDataSync(packageName, userId, false);
18541                if (observer != null) {
18542                    try {
18543                        observer.onRemoveCompleted(packageName, true);
18544                    } catch (RemoteException e) {
18545                        Log.i(TAG, "Observer no longer exists.");
18546                    }
18547                }
18548            }
18549        });
18550    }
18551
18552    @Override
18553    public void getPackageSizeInfo(final String packageName, int userHandle,
18554            final IPackageStatsObserver observer) {
18555        mContext.enforceCallingOrSelfPermission(
18556                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18557        if (packageName == null) {
18558            throw new IllegalArgumentException("Attempt to get size of null packageName");
18559        }
18560
18561        PackageStats stats = new PackageStats(packageName, userHandle);
18562
18563        /*
18564         * Queue up an async operation since the package measurement may take a
18565         * little while.
18566         */
18567        Message msg = mHandler.obtainMessage(INIT_COPY);
18568        msg.obj = new MeasureParams(stats, observer);
18569        mHandler.sendMessage(msg);
18570    }
18571
18572    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18573        final PackageSetting ps;
18574        synchronized (mPackages) {
18575            ps = mSettings.mPackages.get(packageName);
18576            if (ps == null) {
18577                Slog.w(TAG, "Failed to find settings for " + packageName);
18578                return false;
18579            }
18580        }
18581
18582        final String[] packageNames = { packageName };
18583        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18584        final String[] codePaths = { ps.codePathString };
18585
18586        try {
18587            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18588                    ps.appId, ceDataInodes, codePaths, stats);
18589
18590            // For now, ignore code size of packages on system partition
18591            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18592                stats.codeSize = 0;
18593            }
18594
18595            // External clients expect these to be tracked separately
18596            stats.dataSize -= stats.cacheSize;
18597
18598        } catch (InstallerException e) {
18599            Slog.w(TAG, String.valueOf(e));
18600            return false;
18601        }
18602
18603        return true;
18604    }
18605
18606    private int getUidTargetSdkVersionLockedLPr(int uid) {
18607        Object obj = mSettings.getUserIdLPr(uid);
18608        if (obj instanceof SharedUserSetting) {
18609            final SharedUserSetting sus = (SharedUserSetting) obj;
18610            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18611            final Iterator<PackageSetting> it = sus.packages.iterator();
18612            while (it.hasNext()) {
18613                final PackageSetting ps = it.next();
18614                if (ps.pkg != null) {
18615                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18616                    if (v < vers) vers = v;
18617                }
18618            }
18619            return vers;
18620        } else if (obj instanceof PackageSetting) {
18621            final PackageSetting ps = (PackageSetting) obj;
18622            if (ps.pkg != null) {
18623                return ps.pkg.applicationInfo.targetSdkVersion;
18624            }
18625        }
18626        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18627    }
18628
18629    @Override
18630    public void addPreferredActivity(IntentFilter filter, int match,
18631            ComponentName[] set, ComponentName activity, int userId) {
18632        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18633                "Adding preferred");
18634    }
18635
18636    private void addPreferredActivityInternal(IntentFilter filter, int match,
18637            ComponentName[] set, ComponentName activity, boolean always, int userId,
18638            String opname) {
18639        // writer
18640        int callingUid = Binder.getCallingUid();
18641        enforceCrossUserPermission(callingUid, userId,
18642                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18643        if (filter.countActions() == 0) {
18644            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18645            return;
18646        }
18647        synchronized (mPackages) {
18648            if (mContext.checkCallingOrSelfPermission(
18649                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18650                    != PackageManager.PERMISSION_GRANTED) {
18651                if (getUidTargetSdkVersionLockedLPr(callingUid)
18652                        < Build.VERSION_CODES.FROYO) {
18653                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18654                            + callingUid);
18655                    return;
18656                }
18657                mContext.enforceCallingOrSelfPermission(
18658                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18659            }
18660
18661            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18662            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18663                    + userId + ":");
18664            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18665            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18666            scheduleWritePackageRestrictionsLocked(userId);
18667            postPreferredActivityChangedBroadcast(userId);
18668        }
18669    }
18670
18671    private void postPreferredActivityChangedBroadcast(int userId) {
18672        mHandler.post(() -> {
18673            final IActivityManager am = ActivityManager.getService();
18674            if (am == null) {
18675                return;
18676            }
18677
18678            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18679            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18680            try {
18681                am.broadcastIntent(null, intent, null, null,
18682                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18683                        null, false, false, userId);
18684            } catch (RemoteException e) {
18685            }
18686        });
18687    }
18688
18689    @Override
18690    public void replacePreferredActivity(IntentFilter filter, int match,
18691            ComponentName[] set, ComponentName activity, int userId) {
18692        if (filter.countActions() != 1) {
18693            throw new IllegalArgumentException(
18694                    "replacePreferredActivity expects filter to have only 1 action.");
18695        }
18696        if (filter.countDataAuthorities() != 0
18697                || filter.countDataPaths() != 0
18698                || filter.countDataSchemes() > 1
18699                || filter.countDataTypes() != 0) {
18700            throw new IllegalArgumentException(
18701                    "replacePreferredActivity expects filter to have no data authorities, " +
18702                    "paths, or types; and at most one scheme.");
18703        }
18704
18705        final int callingUid = Binder.getCallingUid();
18706        enforceCrossUserPermission(callingUid, userId,
18707                true /* requireFullPermission */, false /* checkShell */,
18708                "replace preferred activity");
18709        synchronized (mPackages) {
18710            if (mContext.checkCallingOrSelfPermission(
18711                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18712                    != PackageManager.PERMISSION_GRANTED) {
18713                if (getUidTargetSdkVersionLockedLPr(callingUid)
18714                        < Build.VERSION_CODES.FROYO) {
18715                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18716                            + Binder.getCallingUid());
18717                    return;
18718                }
18719                mContext.enforceCallingOrSelfPermission(
18720                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18721            }
18722
18723            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18724            if (pir != null) {
18725                // Get all of the existing entries that exactly match this filter.
18726                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18727                if (existing != null && existing.size() == 1) {
18728                    PreferredActivity cur = existing.get(0);
18729                    if (DEBUG_PREFERRED) {
18730                        Slog.i(TAG, "Checking replace of preferred:");
18731                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18732                        if (!cur.mPref.mAlways) {
18733                            Slog.i(TAG, "  -- CUR; not mAlways!");
18734                        } else {
18735                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18736                            Slog.i(TAG, "  -- CUR: mSet="
18737                                    + Arrays.toString(cur.mPref.mSetComponents));
18738                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18739                            Slog.i(TAG, "  -- NEW: mMatch="
18740                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18741                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18742                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18743                        }
18744                    }
18745                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18746                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18747                            && cur.mPref.sameSet(set)) {
18748                        // Setting the preferred activity to what it happens to be already
18749                        if (DEBUG_PREFERRED) {
18750                            Slog.i(TAG, "Replacing with same preferred activity "
18751                                    + cur.mPref.mShortComponent + " for user "
18752                                    + userId + ":");
18753                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18754                        }
18755                        return;
18756                    }
18757                }
18758
18759                if (existing != null) {
18760                    if (DEBUG_PREFERRED) {
18761                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18762                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18763                    }
18764                    for (int i = 0; i < existing.size(); i++) {
18765                        PreferredActivity pa = existing.get(i);
18766                        if (DEBUG_PREFERRED) {
18767                            Slog.i(TAG, "Removing existing preferred activity "
18768                                    + pa.mPref.mComponent + ":");
18769                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18770                        }
18771                        pir.removeFilter(pa);
18772                    }
18773                }
18774            }
18775            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18776                    "Replacing preferred");
18777        }
18778    }
18779
18780    @Override
18781    public void clearPackagePreferredActivities(String packageName) {
18782        final int uid = Binder.getCallingUid();
18783        // writer
18784        synchronized (mPackages) {
18785            PackageParser.Package pkg = mPackages.get(packageName);
18786            if (pkg == null || pkg.applicationInfo.uid != uid) {
18787                if (mContext.checkCallingOrSelfPermission(
18788                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18789                        != PackageManager.PERMISSION_GRANTED) {
18790                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18791                            < Build.VERSION_CODES.FROYO) {
18792                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18793                                + Binder.getCallingUid());
18794                        return;
18795                    }
18796                    mContext.enforceCallingOrSelfPermission(
18797                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18798                }
18799            }
18800
18801            int user = UserHandle.getCallingUserId();
18802            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18803                scheduleWritePackageRestrictionsLocked(user);
18804            }
18805        }
18806    }
18807
18808    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18809    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18810        ArrayList<PreferredActivity> removed = null;
18811        boolean changed = false;
18812        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18813            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18814            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18815            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18816                continue;
18817            }
18818            Iterator<PreferredActivity> it = pir.filterIterator();
18819            while (it.hasNext()) {
18820                PreferredActivity pa = it.next();
18821                // Mark entry for removal only if it matches the package name
18822                // and the entry is of type "always".
18823                if (packageName == null ||
18824                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18825                                && pa.mPref.mAlways)) {
18826                    if (removed == null) {
18827                        removed = new ArrayList<PreferredActivity>();
18828                    }
18829                    removed.add(pa);
18830                }
18831            }
18832            if (removed != null) {
18833                for (int j=0; j<removed.size(); j++) {
18834                    PreferredActivity pa = removed.get(j);
18835                    pir.removeFilter(pa);
18836                }
18837                changed = true;
18838            }
18839        }
18840        if (changed) {
18841            postPreferredActivityChangedBroadcast(userId);
18842        }
18843        return changed;
18844    }
18845
18846    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18847    private void clearIntentFilterVerificationsLPw(int userId) {
18848        final int packageCount = mPackages.size();
18849        for (int i = 0; i < packageCount; i++) {
18850            PackageParser.Package pkg = mPackages.valueAt(i);
18851            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18852        }
18853    }
18854
18855    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18856    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18857        if (userId == UserHandle.USER_ALL) {
18858            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18859                    sUserManager.getUserIds())) {
18860                for (int oneUserId : sUserManager.getUserIds()) {
18861                    scheduleWritePackageRestrictionsLocked(oneUserId);
18862                }
18863            }
18864        } else {
18865            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18866                scheduleWritePackageRestrictionsLocked(userId);
18867            }
18868        }
18869    }
18870
18871    void clearDefaultBrowserIfNeeded(String packageName) {
18872        for (int oneUserId : sUserManager.getUserIds()) {
18873            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18874            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18875            if (packageName.equals(defaultBrowserPackageName)) {
18876                setDefaultBrowserPackageName(null, oneUserId);
18877            }
18878        }
18879    }
18880
18881    @Override
18882    public void resetApplicationPreferences(int userId) {
18883        mContext.enforceCallingOrSelfPermission(
18884                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18885        final long identity = Binder.clearCallingIdentity();
18886        // writer
18887        try {
18888            synchronized (mPackages) {
18889                clearPackagePreferredActivitiesLPw(null, userId);
18890                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18891                // TODO: We have to reset the default SMS and Phone. This requires
18892                // significant refactoring to keep all default apps in the package
18893                // manager (cleaner but more work) or have the services provide
18894                // callbacks to the package manager to request a default app reset.
18895                applyFactoryDefaultBrowserLPw(userId);
18896                clearIntentFilterVerificationsLPw(userId);
18897                primeDomainVerificationsLPw(userId);
18898                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18899                scheduleWritePackageRestrictionsLocked(userId);
18900            }
18901            resetNetworkPolicies(userId);
18902        } finally {
18903            Binder.restoreCallingIdentity(identity);
18904        }
18905    }
18906
18907    @Override
18908    public int getPreferredActivities(List<IntentFilter> outFilters,
18909            List<ComponentName> outActivities, String packageName) {
18910
18911        int num = 0;
18912        final int userId = UserHandle.getCallingUserId();
18913        // reader
18914        synchronized (mPackages) {
18915            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18916            if (pir != null) {
18917                final Iterator<PreferredActivity> it = pir.filterIterator();
18918                while (it.hasNext()) {
18919                    final PreferredActivity pa = it.next();
18920                    if (packageName == null
18921                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18922                                    && pa.mPref.mAlways)) {
18923                        if (outFilters != null) {
18924                            outFilters.add(new IntentFilter(pa));
18925                        }
18926                        if (outActivities != null) {
18927                            outActivities.add(pa.mPref.mComponent);
18928                        }
18929                    }
18930                }
18931            }
18932        }
18933
18934        return num;
18935    }
18936
18937    @Override
18938    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18939            int userId) {
18940        int callingUid = Binder.getCallingUid();
18941        if (callingUid != Process.SYSTEM_UID) {
18942            throw new SecurityException(
18943                    "addPersistentPreferredActivity can only be run by the system");
18944        }
18945        if (filter.countActions() == 0) {
18946            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18947            return;
18948        }
18949        synchronized (mPackages) {
18950            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18951                    ":");
18952            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18953            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18954                    new PersistentPreferredActivity(filter, activity));
18955            scheduleWritePackageRestrictionsLocked(userId);
18956            postPreferredActivityChangedBroadcast(userId);
18957        }
18958    }
18959
18960    @Override
18961    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18962        int callingUid = Binder.getCallingUid();
18963        if (callingUid != Process.SYSTEM_UID) {
18964            throw new SecurityException(
18965                    "clearPackagePersistentPreferredActivities can only be run by the system");
18966        }
18967        ArrayList<PersistentPreferredActivity> removed = null;
18968        boolean changed = false;
18969        synchronized (mPackages) {
18970            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18971                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18972                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18973                        .valueAt(i);
18974                if (userId != thisUserId) {
18975                    continue;
18976                }
18977                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18978                while (it.hasNext()) {
18979                    PersistentPreferredActivity ppa = it.next();
18980                    // Mark entry for removal only if it matches the package name.
18981                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18982                        if (removed == null) {
18983                            removed = new ArrayList<PersistentPreferredActivity>();
18984                        }
18985                        removed.add(ppa);
18986                    }
18987                }
18988                if (removed != null) {
18989                    for (int j=0; j<removed.size(); j++) {
18990                        PersistentPreferredActivity ppa = removed.get(j);
18991                        ppir.removeFilter(ppa);
18992                    }
18993                    changed = true;
18994                }
18995            }
18996
18997            if (changed) {
18998                scheduleWritePackageRestrictionsLocked(userId);
18999                postPreferredActivityChangedBroadcast(userId);
19000            }
19001        }
19002    }
19003
19004    /**
19005     * Common machinery for picking apart a restored XML blob and passing
19006     * it to a caller-supplied functor to be applied to the running system.
19007     */
19008    private void restoreFromXml(XmlPullParser parser, int userId,
19009            String expectedStartTag, BlobXmlRestorer functor)
19010            throws IOException, XmlPullParserException {
19011        int type;
19012        while ((type = parser.next()) != XmlPullParser.START_TAG
19013                && type != XmlPullParser.END_DOCUMENT) {
19014        }
19015        if (type != XmlPullParser.START_TAG) {
19016            // oops didn't find a start tag?!
19017            if (DEBUG_BACKUP) {
19018                Slog.e(TAG, "Didn't find start tag during restore");
19019            }
19020            return;
19021        }
19022Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19023        // this is supposed to be TAG_PREFERRED_BACKUP
19024        if (!expectedStartTag.equals(parser.getName())) {
19025            if (DEBUG_BACKUP) {
19026                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19027            }
19028            return;
19029        }
19030
19031        // skip interfering stuff, then we're aligned with the backing implementation
19032        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19033Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19034        functor.apply(parser, userId);
19035    }
19036
19037    private interface BlobXmlRestorer {
19038        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19039    }
19040
19041    /**
19042     * Non-Binder method, support for the backup/restore mechanism: write the
19043     * full set of preferred activities in its canonical XML format.  Returns the
19044     * XML output as a byte array, or null if there is none.
19045     */
19046    @Override
19047    public byte[] getPreferredActivityBackup(int userId) {
19048        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19049            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19050        }
19051
19052        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19053        try {
19054            final XmlSerializer serializer = new FastXmlSerializer();
19055            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19056            serializer.startDocument(null, true);
19057            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19058
19059            synchronized (mPackages) {
19060                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19061            }
19062
19063            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19064            serializer.endDocument();
19065            serializer.flush();
19066        } catch (Exception e) {
19067            if (DEBUG_BACKUP) {
19068                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19069            }
19070            return null;
19071        }
19072
19073        return dataStream.toByteArray();
19074    }
19075
19076    @Override
19077    public void restorePreferredActivities(byte[] backup, int userId) {
19078        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19079            throw new SecurityException("Only the system may call restorePreferredActivities()");
19080        }
19081
19082        try {
19083            final XmlPullParser parser = Xml.newPullParser();
19084            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19085            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19086                    new BlobXmlRestorer() {
19087                        @Override
19088                        public void apply(XmlPullParser parser, int userId)
19089                                throws XmlPullParserException, IOException {
19090                            synchronized (mPackages) {
19091                                mSettings.readPreferredActivitiesLPw(parser, userId);
19092                            }
19093                        }
19094                    } );
19095        } catch (Exception e) {
19096            if (DEBUG_BACKUP) {
19097                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19098            }
19099        }
19100    }
19101
19102    /**
19103     * Non-Binder method, support for the backup/restore mechanism: write the
19104     * default browser (etc) settings in its canonical XML format.  Returns the default
19105     * browser XML representation as a byte array, or null if there is none.
19106     */
19107    @Override
19108    public byte[] getDefaultAppsBackup(int userId) {
19109        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19110            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19111        }
19112
19113        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19114        try {
19115            final XmlSerializer serializer = new FastXmlSerializer();
19116            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19117            serializer.startDocument(null, true);
19118            serializer.startTag(null, TAG_DEFAULT_APPS);
19119
19120            synchronized (mPackages) {
19121                mSettings.writeDefaultAppsLPr(serializer, userId);
19122            }
19123
19124            serializer.endTag(null, TAG_DEFAULT_APPS);
19125            serializer.endDocument();
19126            serializer.flush();
19127        } catch (Exception e) {
19128            if (DEBUG_BACKUP) {
19129                Slog.e(TAG, "Unable to write default apps for backup", e);
19130            }
19131            return null;
19132        }
19133
19134        return dataStream.toByteArray();
19135    }
19136
19137    @Override
19138    public void restoreDefaultApps(byte[] backup, int userId) {
19139        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19140            throw new SecurityException("Only the system may call restoreDefaultApps()");
19141        }
19142
19143        try {
19144            final XmlPullParser parser = Xml.newPullParser();
19145            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19146            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19147                    new BlobXmlRestorer() {
19148                        @Override
19149                        public void apply(XmlPullParser parser, int userId)
19150                                throws XmlPullParserException, IOException {
19151                            synchronized (mPackages) {
19152                                mSettings.readDefaultAppsLPw(parser, userId);
19153                            }
19154                        }
19155                    } );
19156        } catch (Exception e) {
19157            if (DEBUG_BACKUP) {
19158                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19159            }
19160        }
19161    }
19162
19163    @Override
19164    public byte[] getIntentFilterVerificationBackup(int userId) {
19165        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19166            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19167        }
19168
19169        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19170        try {
19171            final XmlSerializer serializer = new FastXmlSerializer();
19172            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19173            serializer.startDocument(null, true);
19174            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19175
19176            synchronized (mPackages) {
19177                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19178            }
19179
19180            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19181            serializer.endDocument();
19182            serializer.flush();
19183        } catch (Exception e) {
19184            if (DEBUG_BACKUP) {
19185                Slog.e(TAG, "Unable to write default apps for backup", e);
19186            }
19187            return null;
19188        }
19189
19190        return dataStream.toByteArray();
19191    }
19192
19193    @Override
19194    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19195        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19196            throw new SecurityException("Only the system may call restorePreferredActivities()");
19197        }
19198
19199        try {
19200            final XmlPullParser parser = Xml.newPullParser();
19201            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19202            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19203                    new BlobXmlRestorer() {
19204                        @Override
19205                        public void apply(XmlPullParser parser, int userId)
19206                                throws XmlPullParserException, IOException {
19207                            synchronized (mPackages) {
19208                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19209                                mSettings.writeLPr();
19210                            }
19211                        }
19212                    } );
19213        } catch (Exception e) {
19214            if (DEBUG_BACKUP) {
19215                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19216            }
19217        }
19218    }
19219
19220    @Override
19221    public byte[] getPermissionGrantBackup(int userId) {
19222        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19223            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19224        }
19225
19226        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19227        try {
19228            final XmlSerializer serializer = new FastXmlSerializer();
19229            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19230            serializer.startDocument(null, true);
19231            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19232
19233            synchronized (mPackages) {
19234                serializeRuntimePermissionGrantsLPr(serializer, userId);
19235            }
19236
19237            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19238            serializer.endDocument();
19239            serializer.flush();
19240        } catch (Exception e) {
19241            if (DEBUG_BACKUP) {
19242                Slog.e(TAG, "Unable to write default apps for backup", e);
19243            }
19244            return null;
19245        }
19246
19247        return dataStream.toByteArray();
19248    }
19249
19250    @Override
19251    public void restorePermissionGrants(byte[] backup, int userId) {
19252        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19253            throw new SecurityException("Only the system may call restorePermissionGrants()");
19254        }
19255
19256        try {
19257            final XmlPullParser parser = Xml.newPullParser();
19258            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19259            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19260                    new BlobXmlRestorer() {
19261                        @Override
19262                        public void apply(XmlPullParser parser, int userId)
19263                                throws XmlPullParserException, IOException {
19264                            synchronized (mPackages) {
19265                                processRestoredPermissionGrantsLPr(parser, userId);
19266                            }
19267                        }
19268                    } );
19269        } catch (Exception e) {
19270            if (DEBUG_BACKUP) {
19271                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19272            }
19273        }
19274    }
19275
19276    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19277            throws IOException {
19278        serializer.startTag(null, TAG_ALL_GRANTS);
19279
19280        final int N = mSettings.mPackages.size();
19281        for (int i = 0; i < N; i++) {
19282            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19283            boolean pkgGrantsKnown = false;
19284
19285            PermissionsState packagePerms = ps.getPermissionsState();
19286
19287            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19288                final int grantFlags = state.getFlags();
19289                // only look at grants that are not system/policy fixed
19290                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19291                    final boolean isGranted = state.isGranted();
19292                    // And only back up the user-twiddled state bits
19293                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19294                        final String packageName = mSettings.mPackages.keyAt(i);
19295                        if (!pkgGrantsKnown) {
19296                            serializer.startTag(null, TAG_GRANT);
19297                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19298                            pkgGrantsKnown = true;
19299                        }
19300
19301                        final boolean userSet =
19302                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19303                        final boolean userFixed =
19304                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19305                        final boolean revoke =
19306                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19307
19308                        serializer.startTag(null, TAG_PERMISSION);
19309                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19310                        if (isGranted) {
19311                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19312                        }
19313                        if (userSet) {
19314                            serializer.attribute(null, ATTR_USER_SET, "true");
19315                        }
19316                        if (userFixed) {
19317                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19318                        }
19319                        if (revoke) {
19320                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19321                        }
19322                        serializer.endTag(null, TAG_PERMISSION);
19323                    }
19324                }
19325            }
19326
19327            if (pkgGrantsKnown) {
19328                serializer.endTag(null, TAG_GRANT);
19329            }
19330        }
19331
19332        serializer.endTag(null, TAG_ALL_GRANTS);
19333    }
19334
19335    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19336            throws XmlPullParserException, IOException {
19337        String pkgName = null;
19338        int outerDepth = parser.getDepth();
19339        int type;
19340        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19341                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19342            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19343                continue;
19344            }
19345
19346            final String tagName = parser.getName();
19347            if (tagName.equals(TAG_GRANT)) {
19348                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19349                if (DEBUG_BACKUP) {
19350                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19351                }
19352            } else if (tagName.equals(TAG_PERMISSION)) {
19353
19354                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19355                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19356
19357                int newFlagSet = 0;
19358                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19359                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19360                }
19361                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19362                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19363                }
19364                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19365                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19366                }
19367                if (DEBUG_BACKUP) {
19368                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19369                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19370                }
19371                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19372                if (ps != null) {
19373                    // Already installed so we apply the grant immediately
19374                    if (DEBUG_BACKUP) {
19375                        Slog.v(TAG, "        + already installed; applying");
19376                    }
19377                    PermissionsState perms = ps.getPermissionsState();
19378                    BasePermission bp = mSettings.mPermissions.get(permName);
19379                    if (bp != null) {
19380                        if (isGranted) {
19381                            perms.grantRuntimePermission(bp, userId);
19382                        }
19383                        if (newFlagSet != 0) {
19384                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19385                        }
19386                    }
19387                } else {
19388                    // Need to wait for post-restore install to apply the grant
19389                    if (DEBUG_BACKUP) {
19390                        Slog.v(TAG, "        - not yet installed; saving for later");
19391                    }
19392                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19393                            isGranted, newFlagSet, userId);
19394                }
19395            } else {
19396                PackageManagerService.reportSettingsProblem(Log.WARN,
19397                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19398                XmlUtils.skipCurrentTag(parser);
19399            }
19400        }
19401
19402        scheduleWriteSettingsLocked();
19403        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19404    }
19405
19406    @Override
19407    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19408            int sourceUserId, int targetUserId, int flags) {
19409        mContext.enforceCallingOrSelfPermission(
19410                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19411        int callingUid = Binder.getCallingUid();
19412        enforceOwnerRights(ownerPackage, callingUid);
19413        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19414        if (intentFilter.countActions() == 0) {
19415            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19416            return;
19417        }
19418        synchronized (mPackages) {
19419            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19420                    ownerPackage, targetUserId, flags);
19421            CrossProfileIntentResolver resolver =
19422                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19423            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19424            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19425            if (existing != null) {
19426                int size = existing.size();
19427                for (int i = 0; i < size; i++) {
19428                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19429                        return;
19430                    }
19431                }
19432            }
19433            resolver.addFilter(newFilter);
19434            scheduleWritePackageRestrictionsLocked(sourceUserId);
19435        }
19436    }
19437
19438    @Override
19439    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19440        mContext.enforceCallingOrSelfPermission(
19441                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19442        int callingUid = Binder.getCallingUid();
19443        enforceOwnerRights(ownerPackage, callingUid);
19444        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19445        synchronized (mPackages) {
19446            CrossProfileIntentResolver resolver =
19447                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19448            ArraySet<CrossProfileIntentFilter> set =
19449                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19450            for (CrossProfileIntentFilter filter : set) {
19451                if (filter.getOwnerPackage().equals(ownerPackage)) {
19452                    resolver.removeFilter(filter);
19453                }
19454            }
19455            scheduleWritePackageRestrictionsLocked(sourceUserId);
19456        }
19457    }
19458
19459    // Enforcing that callingUid is owning pkg on userId
19460    private void enforceOwnerRights(String pkg, int callingUid) {
19461        // The system owns everything.
19462        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19463            return;
19464        }
19465        int callingUserId = UserHandle.getUserId(callingUid);
19466        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19467        if (pi == null) {
19468            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19469                    + callingUserId);
19470        }
19471        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19472            throw new SecurityException("Calling uid " + callingUid
19473                    + " does not own package " + pkg);
19474        }
19475    }
19476
19477    @Override
19478    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19479        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19480    }
19481
19482    private Intent getHomeIntent() {
19483        Intent intent = new Intent(Intent.ACTION_MAIN);
19484        intent.addCategory(Intent.CATEGORY_HOME);
19485        intent.addCategory(Intent.CATEGORY_DEFAULT);
19486        return intent;
19487    }
19488
19489    private IntentFilter getHomeFilter() {
19490        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19491        filter.addCategory(Intent.CATEGORY_HOME);
19492        filter.addCategory(Intent.CATEGORY_DEFAULT);
19493        return filter;
19494    }
19495
19496    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19497            int userId) {
19498        Intent intent  = getHomeIntent();
19499        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19500                PackageManager.GET_META_DATA, userId);
19501        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19502                true, false, false, userId);
19503
19504        allHomeCandidates.clear();
19505        if (list != null) {
19506            for (ResolveInfo ri : list) {
19507                allHomeCandidates.add(ri);
19508            }
19509        }
19510        return (preferred == null || preferred.activityInfo == null)
19511                ? null
19512                : new ComponentName(preferred.activityInfo.packageName,
19513                        preferred.activityInfo.name);
19514    }
19515
19516    @Override
19517    public void setHomeActivity(ComponentName comp, int userId) {
19518        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19519        getHomeActivitiesAsUser(homeActivities, userId);
19520
19521        boolean found = false;
19522
19523        final int size = homeActivities.size();
19524        final ComponentName[] set = new ComponentName[size];
19525        for (int i = 0; i < size; i++) {
19526            final ResolveInfo candidate = homeActivities.get(i);
19527            final ActivityInfo info = candidate.activityInfo;
19528            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19529            set[i] = activityName;
19530            if (!found && activityName.equals(comp)) {
19531                found = true;
19532            }
19533        }
19534        if (!found) {
19535            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19536                    + userId);
19537        }
19538        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19539                set, comp, userId);
19540    }
19541
19542    private @Nullable String getSetupWizardPackageName() {
19543        final Intent intent = new Intent(Intent.ACTION_MAIN);
19544        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19545
19546        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19547                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19548                        | MATCH_DISABLED_COMPONENTS,
19549                UserHandle.myUserId());
19550        if (matches.size() == 1) {
19551            return matches.get(0).getComponentInfo().packageName;
19552        } else {
19553            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19554                    + ": matches=" + matches);
19555            return null;
19556        }
19557    }
19558
19559    private @Nullable String getStorageManagerPackageName() {
19560        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19561
19562        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19563                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19564                        | MATCH_DISABLED_COMPONENTS,
19565                UserHandle.myUserId());
19566        if (matches.size() == 1) {
19567            return matches.get(0).getComponentInfo().packageName;
19568        } else {
19569            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19570                    + matches.size() + ": matches=" + matches);
19571            return null;
19572        }
19573    }
19574
19575    @Override
19576    public void setApplicationEnabledSetting(String appPackageName,
19577            int newState, int flags, int userId, String callingPackage) {
19578        if (!sUserManager.exists(userId)) return;
19579        if (callingPackage == null) {
19580            callingPackage = Integer.toString(Binder.getCallingUid());
19581        }
19582        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19583    }
19584
19585    @Override
19586    public void setComponentEnabledSetting(ComponentName componentName,
19587            int newState, int flags, int userId) {
19588        if (!sUserManager.exists(userId)) return;
19589        setEnabledSetting(componentName.getPackageName(),
19590                componentName.getClassName(), newState, flags, userId, null);
19591    }
19592
19593    private void setEnabledSetting(final String packageName, String className, int newState,
19594            final int flags, int userId, String callingPackage) {
19595        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19596              || newState == COMPONENT_ENABLED_STATE_ENABLED
19597              || newState == COMPONENT_ENABLED_STATE_DISABLED
19598              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19599              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19600            throw new IllegalArgumentException("Invalid new component state: "
19601                    + newState);
19602        }
19603        PackageSetting pkgSetting;
19604        final int uid = Binder.getCallingUid();
19605        final int permission;
19606        if (uid == Process.SYSTEM_UID) {
19607            permission = PackageManager.PERMISSION_GRANTED;
19608        } else {
19609            permission = mContext.checkCallingOrSelfPermission(
19610                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19611        }
19612        enforceCrossUserPermission(uid, userId,
19613                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19614        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19615        boolean sendNow = false;
19616        boolean isApp = (className == null);
19617        String componentName = isApp ? packageName : className;
19618        int packageUid = -1;
19619        ArrayList<String> components;
19620
19621        // writer
19622        synchronized (mPackages) {
19623            pkgSetting = mSettings.mPackages.get(packageName);
19624            if (pkgSetting == null) {
19625                if (className == null) {
19626                    throw new IllegalArgumentException("Unknown package: " + packageName);
19627                }
19628                throw new IllegalArgumentException(
19629                        "Unknown component: " + packageName + "/" + className);
19630            }
19631        }
19632
19633        // Limit who can change which apps
19634        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19635            // Don't allow apps that don't have permission to modify other apps
19636            if (!allowedByPermission) {
19637                throw new SecurityException(
19638                        "Permission Denial: attempt to change component state from pid="
19639                        + Binder.getCallingPid()
19640                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19641            }
19642            // Don't allow changing protected packages.
19643            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19644                throw new SecurityException("Cannot disable a protected package: " + packageName);
19645            }
19646        }
19647
19648        synchronized (mPackages) {
19649            if (uid == Process.SHELL_UID
19650                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19651                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19652                // unless it is a test package.
19653                int oldState = pkgSetting.getEnabled(userId);
19654                if (className == null
19655                    &&
19656                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19657                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19658                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19659                    &&
19660                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19661                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19662                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19663                    // ok
19664                } else {
19665                    throw new SecurityException(
19666                            "Shell cannot change component state for " + packageName + "/"
19667                            + className + " to " + newState);
19668                }
19669            }
19670            if (className == null) {
19671                // We're dealing with an application/package level state change
19672                if (pkgSetting.getEnabled(userId) == newState) {
19673                    // Nothing to do
19674                    return;
19675                }
19676                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19677                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19678                    // Don't care about who enables an app.
19679                    callingPackage = null;
19680                }
19681                pkgSetting.setEnabled(newState, userId, callingPackage);
19682                // pkgSetting.pkg.mSetEnabled = newState;
19683            } else {
19684                // We're dealing with a component level state change
19685                // First, verify that this is a valid class name.
19686                PackageParser.Package pkg = pkgSetting.pkg;
19687                if (pkg == null || !pkg.hasComponentClassName(className)) {
19688                    if (pkg != null &&
19689                            pkg.applicationInfo.targetSdkVersion >=
19690                                    Build.VERSION_CODES.JELLY_BEAN) {
19691                        throw new IllegalArgumentException("Component class " + className
19692                                + " does not exist in " + packageName);
19693                    } else {
19694                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19695                                + className + " does not exist in " + packageName);
19696                    }
19697                }
19698                switch (newState) {
19699                case COMPONENT_ENABLED_STATE_ENABLED:
19700                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19701                        return;
19702                    }
19703                    break;
19704                case COMPONENT_ENABLED_STATE_DISABLED:
19705                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19706                        return;
19707                    }
19708                    break;
19709                case COMPONENT_ENABLED_STATE_DEFAULT:
19710                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19711                        return;
19712                    }
19713                    break;
19714                default:
19715                    Slog.e(TAG, "Invalid new component state: " + newState);
19716                    return;
19717                }
19718            }
19719            scheduleWritePackageRestrictionsLocked(userId);
19720            components = mPendingBroadcasts.get(userId, packageName);
19721            final boolean newPackage = components == null;
19722            if (newPackage) {
19723                components = new ArrayList<String>();
19724            }
19725            if (!components.contains(componentName)) {
19726                components.add(componentName);
19727            }
19728            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19729                sendNow = true;
19730                // Purge entry from pending broadcast list if another one exists already
19731                // since we are sending one right away.
19732                mPendingBroadcasts.remove(userId, packageName);
19733            } else {
19734                if (newPackage) {
19735                    mPendingBroadcasts.put(userId, packageName, components);
19736                }
19737                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19738                    // Schedule a message
19739                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19740                }
19741            }
19742        }
19743
19744        long callingId = Binder.clearCallingIdentity();
19745        try {
19746            if (sendNow) {
19747                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19748                sendPackageChangedBroadcast(packageName,
19749                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19750            }
19751        } finally {
19752            Binder.restoreCallingIdentity(callingId);
19753        }
19754    }
19755
19756    @Override
19757    public void flushPackageRestrictionsAsUser(int userId) {
19758        if (!sUserManager.exists(userId)) {
19759            return;
19760        }
19761        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19762                false /* checkShell */, "flushPackageRestrictions");
19763        synchronized (mPackages) {
19764            mSettings.writePackageRestrictionsLPr(userId);
19765            mDirtyUsers.remove(userId);
19766            if (mDirtyUsers.isEmpty()) {
19767                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19768            }
19769        }
19770    }
19771
19772    private void sendPackageChangedBroadcast(String packageName,
19773            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19774        if (DEBUG_INSTALL)
19775            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19776                    + componentNames);
19777        Bundle extras = new Bundle(4);
19778        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19779        String nameList[] = new String[componentNames.size()];
19780        componentNames.toArray(nameList);
19781        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19782        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19783        extras.putInt(Intent.EXTRA_UID, packageUid);
19784        // If this is not reporting a change of the overall package, then only send it
19785        // to registered receivers.  We don't want to launch a swath of apps for every
19786        // little component state change.
19787        final int flags = !componentNames.contains(packageName)
19788                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19789        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19790                new int[] {UserHandle.getUserId(packageUid)});
19791    }
19792
19793    @Override
19794    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19795        if (!sUserManager.exists(userId)) return;
19796        final int uid = Binder.getCallingUid();
19797        final int permission = mContext.checkCallingOrSelfPermission(
19798                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19799        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19800        enforceCrossUserPermission(uid, userId,
19801                true /* requireFullPermission */, true /* checkShell */, "stop package");
19802        // writer
19803        synchronized (mPackages) {
19804            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19805                    allowedByPermission, uid, userId)) {
19806                scheduleWritePackageRestrictionsLocked(userId);
19807            }
19808        }
19809    }
19810
19811    @Override
19812    public String getInstallerPackageName(String packageName) {
19813        // reader
19814        synchronized (mPackages) {
19815            return mSettings.getInstallerPackageNameLPr(packageName);
19816        }
19817    }
19818
19819    public boolean isOrphaned(String packageName) {
19820        // reader
19821        synchronized (mPackages) {
19822            return mSettings.isOrphaned(packageName);
19823        }
19824    }
19825
19826    @Override
19827    public int getApplicationEnabledSetting(String packageName, int userId) {
19828        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19829        int uid = Binder.getCallingUid();
19830        enforceCrossUserPermission(uid, userId,
19831                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19832        // reader
19833        synchronized (mPackages) {
19834            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19835        }
19836    }
19837
19838    @Override
19839    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19840        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19841        int uid = Binder.getCallingUid();
19842        enforceCrossUserPermission(uid, userId,
19843                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19844        // reader
19845        synchronized (mPackages) {
19846            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19847        }
19848    }
19849
19850    @Override
19851    public void enterSafeMode() {
19852        enforceSystemOrRoot("Only the system can request entering safe mode");
19853
19854        if (!mSystemReady) {
19855            mSafeMode = true;
19856        }
19857    }
19858
19859    @Override
19860    public void systemReady() {
19861        mSystemReady = true;
19862
19863        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19864        // disabled after already being started.
19865        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19866                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19867
19868        // Read the compatibilty setting when the system is ready.
19869        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19870                mContext.getContentResolver(),
19871                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19872        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19873        if (DEBUG_SETTINGS) {
19874            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19875        }
19876
19877        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19878
19879        synchronized (mPackages) {
19880            // Verify that all of the preferred activity components actually
19881            // exist.  It is possible for applications to be updated and at
19882            // that point remove a previously declared activity component that
19883            // had been set as a preferred activity.  We try to clean this up
19884            // the next time we encounter that preferred activity, but it is
19885            // possible for the user flow to never be able to return to that
19886            // situation so here we do a sanity check to make sure we haven't
19887            // left any junk around.
19888            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19889            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19890                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19891                removed.clear();
19892                for (PreferredActivity pa : pir.filterSet()) {
19893                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19894                        removed.add(pa);
19895                    }
19896                }
19897                if (removed.size() > 0) {
19898                    for (int r=0; r<removed.size(); r++) {
19899                        PreferredActivity pa = removed.get(r);
19900                        Slog.w(TAG, "Removing dangling preferred activity: "
19901                                + pa.mPref.mComponent);
19902                        pir.removeFilter(pa);
19903                    }
19904                    mSettings.writePackageRestrictionsLPr(
19905                            mSettings.mPreferredActivities.keyAt(i));
19906                }
19907            }
19908
19909            for (int userId : UserManagerService.getInstance().getUserIds()) {
19910                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19911                    grantPermissionsUserIds = ArrayUtils.appendInt(
19912                            grantPermissionsUserIds, userId);
19913                }
19914            }
19915        }
19916        sUserManager.systemReady();
19917
19918        // If we upgraded grant all default permissions before kicking off.
19919        for (int userId : grantPermissionsUserIds) {
19920            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
19921        }
19922
19923        // If we did not grant default permissions, we preload from this the
19924        // default permission exceptions lazily to ensure we don't hit the
19925        // disk on a new user creation.
19926        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19927            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19928        }
19929
19930        // Kick off any messages waiting for system ready
19931        if (mPostSystemReadyMessages != null) {
19932            for (Message msg : mPostSystemReadyMessages) {
19933                msg.sendToTarget();
19934            }
19935            mPostSystemReadyMessages = null;
19936        }
19937
19938        // Watch for external volumes that come and go over time
19939        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19940        storage.registerListener(mStorageListener);
19941
19942        mInstallerService.systemReady();
19943        mPackageDexOptimizer.systemReady();
19944
19945        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
19946                StorageManagerInternal.class);
19947        StorageManagerInternal.addExternalStoragePolicy(
19948                new StorageManagerInternal.ExternalStorageMountPolicy() {
19949            @Override
19950            public int getMountMode(int uid, String packageName) {
19951                if (Process.isIsolated(uid)) {
19952                    return Zygote.MOUNT_EXTERNAL_NONE;
19953                }
19954                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
19955                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19956                }
19957                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19958                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19959                }
19960                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19961                    return Zygote.MOUNT_EXTERNAL_READ;
19962                }
19963                return Zygote.MOUNT_EXTERNAL_WRITE;
19964            }
19965
19966            @Override
19967            public boolean hasExternalStorage(int uid, String packageName) {
19968                return true;
19969            }
19970        });
19971
19972        // Now that we're mostly running, clean up stale users and apps
19973        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
19974        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
19975    }
19976
19977    @Override
19978    public boolean isSafeMode() {
19979        return mSafeMode;
19980    }
19981
19982    @Override
19983    public boolean hasSystemUidErrors() {
19984        return mHasSystemUidErrors;
19985    }
19986
19987    static String arrayToString(int[] array) {
19988        StringBuffer buf = new StringBuffer(128);
19989        buf.append('[');
19990        if (array != null) {
19991            for (int i=0; i<array.length; i++) {
19992                if (i > 0) buf.append(", ");
19993                buf.append(array[i]);
19994            }
19995        }
19996        buf.append(']');
19997        return buf.toString();
19998    }
19999
20000    static class DumpState {
20001        public static final int DUMP_LIBS = 1 << 0;
20002        public static final int DUMP_FEATURES = 1 << 1;
20003        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20004        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20005        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20006        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20007        public static final int DUMP_PERMISSIONS = 1 << 6;
20008        public static final int DUMP_PACKAGES = 1 << 7;
20009        public static final int DUMP_SHARED_USERS = 1 << 8;
20010        public static final int DUMP_MESSAGES = 1 << 9;
20011        public static final int DUMP_PROVIDERS = 1 << 10;
20012        public static final int DUMP_VERIFIERS = 1 << 11;
20013        public static final int DUMP_PREFERRED = 1 << 12;
20014        public static final int DUMP_PREFERRED_XML = 1 << 13;
20015        public static final int DUMP_KEYSETS = 1 << 14;
20016        public static final int DUMP_VERSION = 1 << 15;
20017        public static final int DUMP_INSTALLS = 1 << 16;
20018        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20019        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20020        public static final int DUMP_FROZEN = 1 << 19;
20021        public static final int DUMP_DEXOPT = 1 << 20;
20022        public static final int DUMP_COMPILER_STATS = 1 << 21;
20023
20024        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20025
20026        private int mTypes;
20027
20028        private int mOptions;
20029
20030        private boolean mTitlePrinted;
20031
20032        private SharedUserSetting mSharedUser;
20033
20034        public boolean isDumping(int type) {
20035            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20036                return true;
20037            }
20038
20039            return (mTypes & type) != 0;
20040        }
20041
20042        public void setDump(int type) {
20043            mTypes |= type;
20044        }
20045
20046        public boolean isOptionEnabled(int option) {
20047            return (mOptions & option) != 0;
20048        }
20049
20050        public void setOptionEnabled(int option) {
20051            mOptions |= option;
20052        }
20053
20054        public boolean onTitlePrinted() {
20055            final boolean printed = mTitlePrinted;
20056            mTitlePrinted = true;
20057            return printed;
20058        }
20059
20060        public boolean getTitlePrinted() {
20061            return mTitlePrinted;
20062        }
20063
20064        public void setTitlePrinted(boolean enabled) {
20065            mTitlePrinted = enabled;
20066        }
20067
20068        public SharedUserSetting getSharedUser() {
20069            return mSharedUser;
20070        }
20071
20072        public void setSharedUser(SharedUserSetting user) {
20073            mSharedUser = user;
20074        }
20075    }
20076
20077    @Override
20078    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20079            FileDescriptor err, String[] args, ShellCallback callback,
20080            ResultReceiver resultReceiver) {
20081        (new PackageManagerShellCommand(this)).exec(
20082                this, in, out, err, args, callback, resultReceiver);
20083    }
20084
20085    @Override
20086    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20087        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20088                != PackageManager.PERMISSION_GRANTED) {
20089            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20090                    + Binder.getCallingPid()
20091                    + ", uid=" + Binder.getCallingUid()
20092                    + " without permission "
20093                    + android.Manifest.permission.DUMP);
20094            return;
20095        }
20096
20097        DumpState dumpState = new DumpState();
20098        boolean fullPreferred = false;
20099        boolean checkin = false;
20100
20101        String packageName = null;
20102        ArraySet<String> permissionNames = null;
20103
20104        int opti = 0;
20105        while (opti < args.length) {
20106            String opt = args[opti];
20107            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20108                break;
20109            }
20110            opti++;
20111
20112            if ("-a".equals(opt)) {
20113                // Right now we only know how to print all.
20114            } else if ("-h".equals(opt)) {
20115                pw.println("Package manager dump options:");
20116                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20117                pw.println("    --checkin: dump for a checkin");
20118                pw.println("    -f: print details of intent filters");
20119                pw.println("    -h: print this help");
20120                pw.println("  cmd may be one of:");
20121                pw.println("    l[ibraries]: list known shared libraries");
20122                pw.println("    f[eatures]: list device features");
20123                pw.println("    k[eysets]: print known keysets");
20124                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20125                pw.println("    perm[issions]: dump permissions");
20126                pw.println("    permission [name ...]: dump declaration and use of given permission");
20127                pw.println("    pref[erred]: print preferred package settings");
20128                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20129                pw.println("    prov[iders]: dump content providers");
20130                pw.println("    p[ackages]: dump installed packages");
20131                pw.println("    s[hared-users]: dump shared user IDs");
20132                pw.println("    m[essages]: print collected runtime messages");
20133                pw.println("    v[erifiers]: print package verifier info");
20134                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20135                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20136                pw.println("    version: print database version info");
20137                pw.println("    write: write current settings now");
20138                pw.println("    installs: details about install sessions");
20139                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20140                pw.println("    dexopt: dump dexopt state");
20141                pw.println("    compiler-stats: dump compiler statistics");
20142                pw.println("    <package.name>: info about given package");
20143                return;
20144            } else if ("--checkin".equals(opt)) {
20145                checkin = true;
20146            } else if ("-f".equals(opt)) {
20147                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20148            } else {
20149                pw.println("Unknown argument: " + opt + "; use -h for help");
20150            }
20151        }
20152
20153        // Is the caller requesting to dump a particular piece of data?
20154        if (opti < args.length) {
20155            String cmd = args[opti];
20156            opti++;
20157            // Is this a package name?
20158            if ("android".equals(cmd) || cmd.contains(".")) {
20159                packageName = cmd;
20160                // When dumping a single package, we always dump all of its
20161                // filter information since the amount of data will be reasonable.
20162                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20163            } else if ("check-permission".equals(cmd)) {
20164                if (opti >= args.length) {
20165                    pw.println("Error: check-permission missing permission argument");
20166                    return;
20167                }
20168                String perm = args[opti];
20169                opti++;
20170                if (opti >= args.length) {
20171                    pw.println("Error: check-permission missing package argument");
20172                    return;
20173                }
20174
20175                String pkg = args[opti];
20176                opti++;
20177                int user = UserHandle.getUserId(Binder.getCallingUid());
20178                if (opti < args.length) {
20179                    try {
20180                        user = Integer.parseInt(args[opti]);
20181                    } catch (NumberFormatException e) {
20182                        pw.println("Error: check-permission user argument is not a number: "
20183                                + args[opti]);
20184                        return;
20185                    }
20186                }
20187
20188                // Normalize package name to handle renamed packages and static libs
20189                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20190
20191                pw.println(checkPermission(perm, pkg, user));
20192                return;
20193            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20194                dumpState.setDump(DumpState.DUMP_LIBS);
20195            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20196                dumpState.setDump(DumpState.DUMP_FEATURES);
20197            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20198                if (opti >= args.length) {
20199                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20200                            | DumpState.DUMP_SERVICE_RESOLVERS
20201                            | DumpState.DUMP_RECEIVER_RESOLVERS
20202                            | DumpState.DUMP_CONTENT_RESOLVERS);
20203                } else {
20204                    while (opti < args.length) {
20205                        String name = args[opti];
20206                        if ("a".equals(name) || "activity".equals(name)) {
20207                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20208                        } else if ("s".equals(name) || "service".equals(name)) {
20209                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20210                        } else if ("r".equals(name) || "receiver".equals(name)) {
20211                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20212                        } else if ("c".equals(name) || "content".equals(name)) {
20213                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20214                        } else {
20215                            pw.println("Error: unknown resolver table type: " + name);
20216                            return;
20217                        }
20218                        opti++;
20219                    }
20220                }
20221            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20222                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20223            } else if ("permission".equals(cmd)) {
20224                if (opti >= args.length) {
20225                    pw.println("Error: permission requires permission name");
20226                    return;
20227                }
20228                permissionNames = new ArraySet<>();
20229                while (opti < args.length) {
20230                    permissionNames.add(args[opti]);
20231                    opti++;
20232                }
20233                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20234                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20235            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20236                dumpState.setDump(DumpState.DUMP_PREFERRED);
20237            } else if ("preferred-xml".equals(cmd)) {
20238                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20239                if (opti < args.length && "--full".equals(args[opti])) {
20240                    fullPreferred = true;
20241                    opti++;
20242                }
20243            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20244                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20245            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20246                dumpState.setDump(DumpState.DUMP_PACKAGES);
20247            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20248                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20249            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20250                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20251            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20252                dumpState.setDump(DumpState.DUMP_MESSAGES);
20253            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20254                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20255            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20256                    || "intent-filter-verifiers".equals(cmd)) {
20257                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20258            } else if ("version".equals(cmd)) {
20259                dumpState.setDump(DumpState.DUMP_VERSION);
20260            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20261                dumpState.setDump(DumpState.DUMP_KEYSETS);
20262            } else if ("installs".equals(cmd)) {
20263                dumpState.setDump(DumpState.DUMP_INSTALLS);
20264            } else if ("frozen".equals(cmd)) {
20265                dumpState.setDump(DumpState.DUMP_FROZEN);
20266            } else if ("dexopt".equals(cmd)) {
20267                dumpState.setDump(DumpState.DUMP_DEXOPT);
20268            } else if ("compiler-stats".equals(cmd)) {
20269                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20270            } else if ("write".equals(cmd)) {
20271                synchronized (mPackages) {
20272                    mSettings.writeLPr();
20273                    pw.println("Settings written.");
20274                    return;
20275                }
20276            }
20277        }
20278
20279        if (checkin) {
20280            pw.println("vers,1");
20281        }
20282
20283        // reader
20284        synchronized (mPackages) {
20285            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20286                if (!checkin) {
20287                    if (dumpState.onTitlePrinted())
20288                        pw.println();
20289                    pw.println("Database versions:");
20290                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20291                }
20292            }
20293
20294            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20295                if (!checkin) {
20296                    if (dumpState.onTitlePrinted())
20297                        pw.println();
20298                    pw.println("Verifiers:");
20299                    pw.print("  Required: ");
20300                    pw.print(mRequiredVerifierPackage);
20301                    pw.print(" (uid=");
20302                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20303                            UserHandle.USER_SYSTEM));
20304                    pw.println(")");
20305                } else if (mRequiredVerifierPackage != null) {
20306                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20307                    pw.print(",");
20308                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20309                            UserHandle.USER_SYSTEM));
20310                }
20311            }
20312
20313            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20314                    packageName == null) {
20315                if (mIntentFilterVerifierComponent != null) {
20316                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20317                    if (!checkin) {
20318                        if (dumpState.onTitlePrinted())
20319                            pw.println();
20320                        pw.println("Intent Filter Verifier:");
20321                        pw.print("  Using: ");
20322                        pw.print(verifierPackageName);
20323                        pw.print(" (uid=");
20324                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20325                                UserHandle.USER_SYSTEM));
20326                        pw.println(")");
20327                    } else if (verifierPackageName != null) {
20328                        pw.print("ifv,"); pw.print(verifierPackageName);
20329                        pw.print(",");
20330                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20331                                UserHandle.USER_SYSTEM));
20332                    }
20333                } else {
20334                    pw.println();
20335                    pw.println("No Intent Filter Verifier available!");
20336                }
20337            }
20338
20339            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20340                boolean printedHeader = false;
20341                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20342                while (it.hasNext()) {
20343                    String libName = it.next();
20344                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20345                    if (versionedLib == null) {
20346                        continue;
20347                    }
20348                    final int versionCount = versionedLib.size();
20349                    for (int i = 0; i < versionCount; i++) {
20350                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20351                        if (!checkin) {
20352                            if (!printedHeader) {
20353                                if (dumpState.onTitlePrinted())
20354                                    pw.println();
20355                                pw.println("Libraries:");
20356                                printedHeader = true;
20357                            }
20358                            pw.print("  ");
20359                        } else {
20360                            pw.print("lib,");
20361                        }
20362                        pw.print(libEntry.info.getName());
20363                        if (libEntry.info.isStatic()) {
20364                            pw.print(" version=" + libEntry.info.getVersion());
20365                        }
20366                        if (!checkin) {
20367                            pw.print(" -> ");
20368                        }
20369                        if (libEntry.path != null) {
20370                            pw.print(" (jar) ");
20371                            pw.print(libEntry.path);
20372                        } else {
20373                            pw.print(" (apk) ");
20374                            pw.print(libEntry.apk);
20375                        }
20376                        pw.println();
20377                    }
20378                }
20379            }
20380
20381            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20382                if (dumpState.onTitlePrinted())
20383                    pw.println();
20384                if (!checkin) {
20385                    pw.println("Features:");
20386                }
20387
20388                synchronized (mAvailableFeatures) {
20389                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20390                        if (checkin) {
20391                            pw.print("feat,");
20392                            pw.print(feat.name);
20393                            pw.print(",");
20394                            pw.println(feat.version);
20395                        } else {
20396                            pw.print("  ");
20397                            pw.print(feat.name);
20398                            if (feat.version > 0) {
20399                                pw.print(" version=");
20400                                pw.print(feat.version);
20401                            }
20402                            pw.println();
20403                        }
20404                    }
20405                }
20406            }
20407
20408            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20409                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20410                        : "Activity Resolver Table:", "  ", packageName,
20411                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20412                    dumpState.setTitlePrinted(true);
20413                }
20414            }
20415            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20416                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20417                        : "Receiver Resolver Table:", "  ", packageName,
20418                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20419                    dumpState.setTitlePrinted(true);
20420                }
20421            }
20422            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20423                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20424                        : "Service Resolver Table:", "  ", packageName,
20425                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20426                    dumpState.setTitlePrinted(true);
20427                }
20428            }
20429            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20430                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20431                        : "Provider Resolver Table:", "  ", packageName,
20432                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20433                    dumpState.setTitlePrinted(true);
20434                }
20435            }
20436
20437            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20438                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20439                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20440                    int user = mSettings.mPreferredActivities.keyAt(i);
20441                    if (pir.dump(pw,
20442                            dumpState.getTitlePrinted()
20443                                ? "\nPreferred Activities User " + user + ":"
20444                                : "Preferred Activities User " + user + ":", "  ",
20445                            packageName, true, false)) {
20446                        dumpState.setTitlePrinted(true);
20447                    }
20448                }
20449            }
20450
20451            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20452                pw.flush();
20453                FileOutputStream fout = new FileOutputStream(fd);
20454                BufferedOutputStream str = new BufferedOutputStream(fout);
20455                XmlSerializer serializer = new FastXmlSerializer();
20456                try {
20457                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20458                    serializer.startDocument(null, true);
20459                    serializer.setFeature(
20460                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20461                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20462                    serializer.endDocument();
20463                    serializer.flush();
20464                } catch (IllegalArgumentException e) {
20465                    pw.println("Failed writing: " + e);
20466                } catch (IllegalStateException e) {
20467                    pw.println("Failed writing: " + e);
20468                } catch (IOException e) {
20469                    pw.println("Failed writing: " + e);
20470                }
20471            }
20472
20473            if (!checkin
20474                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20475                    && packageName == null) {
20476                pw.println();
20477                int count = mSettings.mPackages.size();
20478                if (count == 0) {
20479                    pw.println("No applications!");
20480                    pw.println();
20481                } else {
20482                    final String prefix = "  ";
20483                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20484                    if (allPackageSettings.size() == 0) {
20485                        pw.println("No domain preferred apps!");
20486                        pw.println();
20487                    } else {
20488                        pw.println("App verification status:");
20489                        pw.println();
20490                        count = 0;
20491                        for (PackageSetting ps : allPackageSettings) {
20492                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20493                            if (ivi == null || ivi.getPackageName() == null) continue;
20494                            pw.println(prefix + "Package: " + ivi.getPackageName());
20495                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20496                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20497                            pw.println();
20498                            count++;
20499                        }
20500                        if (count == 0) {
20501                            pw.println(prefix + "No app verification established.");
20502                            pw.println();
20503                        }
20504                        for (int userId : sUserManager.getUserIds()) {
20505                            pw.println("App linkages for user " + userId + ":");
20506                            pw.println();
20507                            count = 0;
20508                            for (PackageSetting ps : allPackageSettings) {
20509                                final long status = ps.getDomainVerificationStatusForUser(userId);
20510                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20511                                        && !DEBUG_DOMAIN_VERIFICATION) {
20512                                    continue;
20513                                }
20514                                pw.println(prefix + "Package: " + ps.name);
20515                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20516                                String statusStr = IntentFilterVerificationInfo.
20517                                        getStatusStringFromValue(status);
20518                                pw.println(prefix + "Status:  " + statusStr);
20519                                pw.println();
20520                                count++;
20521                            }
20522                            if (count == 0) {
20523                                pw.println(prefix + "No configured app linkages.");
20524                                pw.println();
20525                            }
20526                        }
20527                    }
20528                }
20529            }
20530
20531            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20532                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20533                if (packageName == null && permissionNames == null) {
20534                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20535                        if (iperm == 0) {
20536                            if (dumpState.onTitlePrinted())
20537                                pw.println();
20538                            pw.println("AppOp Permissions:");
20539                        }
20540                        pw.print("  AppOp Permission ");
20541                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20542                        pw.println(":");
20543                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20544                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20545                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20546                        }
20547                    }
20548                }
20549            }
20550
20551            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20552                boolean printedSomething = false;
20553                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20554                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20555                        continue;
20556                    }
20557                    if (!printedSomething) {
20558                        if (dumpState.onTitlePrinted())
20559                            pw.println();
20560                        pw.println("Registered ContentProviders:");
20561                        printedSomething = true;
20562                    }
20563                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20564                    pw.print("    "); pw.println(p.toString());
20565                }
20566                printedSomething = false;
20567                for (Map.Entry<String, PackageParser.Provider> entry :
20568                        mProvidersByAuthority.entrySet()) {
20569                    PackageParser.Provider p = entry.getValue();
20570                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20571                        continue;
20572                    }
20573                    if (!printedSomething) {
20574                        if (dumpState.onTitlePrinted())
20575                            pw.println();
20576                        pw.println("ContentProvider Authorities:");
20577                        printedSomething = true;
20578                    }
20579                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20580                    pw.print("    "); pw.println(p.toString());
20581                    if (p.info != null && p.info.applicationInfo != null) {
20582                        final String appInfo = p.info.applicationInfo.toString();
20583                        pw.print("      applicationInfo="); pw.println(appInfo);
20584                    }
20585                }
20586            }
20587
20588            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20589                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20590            }
20591
20592            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20593                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20594            }
20595
20596            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20597                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20598            }
20599
20600            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20601                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20602            }
20603
20604            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20605                // XXX should handle packageName != null by dumping only install data that
20606                // the given package is involved with.
20607                if (dumpState.onTitlePrinted()) pw.println();
20608                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20609            }
20610
20611            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20612                // XXX should handle packageName != null by dumping only install data that
20613                // the given package is involved with.
20614                if (dumpState.onTitlePrinted()) pw.println();
20615
20616                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20617                ipw.println();
20618                ipw.println("Frozen packages:");
20619                ipw.increaseIndent();
20620                if (mFrozenPackages.size() == 0) {
20621                    ipw.println("(none)");
20622                } else {
20623                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20624                        ipw.println(mFrozenPackages.valueAt(i));
20625                    }
20626                }
20627                ipw.decreaseIndent();
20628            }
20629
20630            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20631                if (dumpState.onTitlePrinted()) pw.println();
20632                dumpDexoptStateLPr(pw, packageName);
20633            }
20634
20635            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20636                if (dumpState.onTitlePrinted()) pw.println();
20637                dumpCompilerStatsLPr(pw, packageName);
20638            }
20639
20640            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20641                if (dumpState.onTitlePrinted()) pw.println();
20642                mSettings.dumpReadMessagesLPr(pw, dumpState);
20643
20644                pw.println();
20645                pw.println("Package warning messages:");
20646                BufferedReader in = null;
20647                String line = null;
20648                try {
20649                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20650                    while ((line = in.readLine()) != null) {
20651                        if (line.contains("ignored: updated version")) continue;
20652                        pw.println(line);
20653                    }
20654                } catch (IOException ignored) {
20655                } finally {
20656                    IoUtils.closeQuietly(in);
20657                }
20658            }
20659
20660            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20661                BufferedReader in = null;
20662                String line = null;
20663                try {
20664                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20665                    while ((line = in.readLine()) != null) {
20666                        if (line.contains("ignored: updated version")) continue;
20667                        pw.print("msg,");
20668                        pw.println(line);
20669                    }
20670                } catch (IOException ignored) {
20671                } finally {
20672                    IoUtils.closeQuietly(in);
20673                }
20674            }
20675        }
20676    }
20677
20678    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20679        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20680        ipw.println();
20681        ipw.println("Dexopt state:");
20682        ipw.increaseIndent();
20683        Collection<PackageParser.Package> packages = null;
20684        if (packageName != null) {
20685            PackageParser.Package targetPackage = mPackages.get(packageName);
20686            if (targetPackage != null) {
20687                packages = Collections.singletonList(targetPackage);
20688            } else {
20689                ipw.println("Unable to find package: " + packageName);
20690                return;
20691            }
20692        } else {
20693            packages = mPackages.values();
20694        }
20695
20696        for (PackageParser.Package pkg : packages) {
20697            ipw.println("[" + pkg.packageName + "]");
20698            ipw.increaseIndent();
20699            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20700            ipw.decreaseIndent();
20701        }
20702    }
20703
20704    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20705        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20706        ipw.println();
20707        ipw.println("Compiler stats:");
20708        ipw.increaseIndent();
20709        Collection<PackageParser.Package> packages = null;
20710        if (packageName != null) {
20711            PackageParser.Package targetPackage = mPackages.get(packageName);
20712            if (targetPackage != null) {
20713                packages = Collections.singletonList(targetPackage);
20714            } else {
20715                ipw.println("Unable to find package: " + packageName);
20716                return;
20717            }
20718        } else {
20719            packages = mPackages.values();
20720        }
20721
20722        for (PackageParser.Package pkg : packages) {
20723            ipw.println("[" + pkg.packageName + "]");
20724            ipw.increaseIndent();
20725
20726            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20727            if (stats == null) {
20728                ipw.println("(No recorded stats)");
20729            } else {
20730                stats.dump(ipw);
20731            }
20732            ipw.decreaseIndent();
20733        }
20734    }
20735
20736    private String dumpDomainString(String packageName) {
20737        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20738                .getList();
20739        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20740
20741        ArraySet<String> result = new ArraySet<>();
20742        if (iviList.size() > 0) {
20743            for (IntentFilterVerificationInfo ivi : iviList) {
20744                for (String host : ivi.getDomains()) {
20745                    result.add(host);
20746                }
20747            }
20748        }
20749        if (filters != null && filters.size() > 0) {
20750            for (IntentFilter filter : filters) {
20751                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20752                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20753                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20754                    result.addAll(filter.getHostsList());
20755                }
20756            }
20757        }
20758
20759        StringBuilder sb = new StringBuilder(result.size() * 16);
20760        for (String domain : result) {
20761            if (sb.length() > 0) sb.append(" ");
20762            sb.append(domain);
20763        }
20764        return sb.toString();
20765    }
20766
20767    // ------- apps on sdcard specific code -------
20768    static final boolean DEBUG_SD_INSTALL = false;
20769
20770    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20771
20772    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20773
20774    private boolean mMediaMounted = false;
20775
20776    static String getEncryptKey() {
20777        try {
20778            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20779                    SD_ENCRYPTION_KEYSTORE_NAME);
20780            if (sdEncKey == null) {
20781                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20782                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20783                if (sdEncKey == null) {
20784                    Slog.e(TAG, "Failed to create encryption keys");
20785                    return null;
20786                }
20787            }
20788            return sdEncKey;
20789        } catch (NoSuchAlgorithmException nsae) {
20790            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20791            return null;
20792        } catch (IOException ioe) {
20793            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20794            return null;
20795        }
20796    }
20797
20798    /*
20799     * Update media status on PackageManager.
20800     */
20801    @Override
20802    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20803        int callingUid = Binder.getCallingUid();
20804        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20805            throw new SecurityException("Media status can only be updated by the system");
20806        }
20807        // reader; this apparently protects mMediaMounted, but should probably
20808        // be a different lock in that case.
20809        synchronized (mPackages) {
20810            Log.i(TAG, "Updating external media status from "
20811                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20812                    + (mediaStatus ? "mounted" : "unmounted"));
20813            if (DEBUG_SD_INSTALL)
20814                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20815                        + ", mMediaMounted=" + mMediaMounted);
20816            if (mediaStatus == mMediaMounted) {
20817                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20818                        : 0, -1);
20819                mHandler.sendMessage(msg);
20820                return;
20821            }
20822            mMediaMounted = mediaStatus;
20823        }
20824        // Queue up an async operation since the package installation may take a
20825        // little while.
20826        mHandler.post(new Runnable() {
20827            public void run() {
20828                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20829            }
20830        });
20831    }
20832
20833    /**
20834     * Called by StorageManagerService when the initial ASECs to scan are available.
20835     * Should block until all the ASEC containers are finished being scanned.
20836     */
20837    public void scanAvailableAsecs() {
20838        updateExternalMediaStatusInner(true, false, false);
20839    }
20840
20841    /*
20842     * Collect information of applications on external media, map them against
20843     * existing containers and update information based on current mount status.
20844     * Please note that we always have to report status if reportStatus has been
20845     * set to true especially when unloading packages.
20846     */
20847    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
20848            boolean externalStorage) {
20849        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
20850        int[] uidArr = EmptyArray.INT;
20851
20852        final String[] list = PackageHelper.getSecureContainerList();
20853        if (ArrayUtils.isEmpty(list)) {
20854            Log.i(TAG, "No secure containers found");
20855        } else {
20856            // Process list of secure containers and categorize them
20857            // as active or stale based on their package internal state.
20858
20859            // reader
20860            synchronized (mPackages) {
20861                for (String cid : list) {
20862                    // Leave stages untouched for now; installer service owns them
20863                    if (PackageInstallerService.isStageName(cid)) continue;
20864
20865                    if (DEBUG_SD_INSTALL)
20866                        Log.i(TAG, "Processing container " + cid);
20867                    String pkgName = getAsecPackageName(cid);
20868                    if (pkgName == null) {
20869                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
20870                        continue;
20871                    }
20872                    if (DEBUG_SD_INSTALL)
20873                        Log.i(TAG, "Looking for pkg : " + pkgName);
20874
20875                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
20876                    if (ps == null) {
20877                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
20878                        continue;
20879                    }
20880
20881                    /*
20882                     * Skip packages that are not external if we're unmounting
20883                     * external storage.
20884                     */
20885                    if (externalStorage && !isMounted && !isExternal(ps)) {
20886                        continue;
20887                    }
20888
20889                    final AsecInstallArgs args = new AsecInstallArgs(cid,
20890                            getAppDexInstructionSets(ps), ps.isForwardLocked());
20891                    // The package status is changed only if the code path
20892                    // matches between settings and the container id.
20893                    if (ps.codePathString != null
20894                            && ps.codePathString.startsWith(args.getCodePath())) {
20895                        if (DEBUG_SD_INSTALL) {
20896                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
20897                                    + " at code path: " + ps.codePathString);
20898                        }
20899
20900                        // We do have a valid package installed on sdcard
20901                        processCids.put(args, ps.codePathString);
20902                        final int uid = ps.appId;
20903                        if (uid != -1) {
20904                            uidArr = ArrayUtils.appendInt(uidArr, uid);
20905                        }
20906                    } else {
20907                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
20908                                + ps.codePathString);
20909                    }
20910                }
20911            }
20912
20913            Arrays.sort(uidArr);
20914        }
20915
20916        // Process packages with valid entries.
20917        if (isMounted) {
20918            if (DEBUG_SD_INSTALL)
20919                Log.i(TAG, "Loading packages");
20920            loadMediaPackages(processCids, uidArr, externalStorage);
20921            startCleaningPackages();
20922            mInstallerService.onSecureContainersAvailable();
20923        } else {
20924            if (DEBUG_SD_INSTALL)
20925                Log.i(TAG, "Unloading packages");
20926            unloadMediaPackages(processCids, uidArr, reportStatus);
20927        }
20928    }
20929
20930    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20931            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20932        final int size = infos.size();
20933        final String[] packageNames = new String[size];
20934        final int[] packageUids = new int[size];
20935        for (int i = 0; i < size; i++) {
20936            final ApplicationInfo info = infos.get(i);
20937            packageNames[i] = info.packageName;
20938            packageUids[i] = info.uid;
20939        }
20940        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20941                finishedReceiver);
20942    }
20943
20944    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20945            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20946        sendResourcesChangedBroadcast(mediaStatus, replacing,
20947                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20948    }
20949
20950    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20951            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20952        int size = pkgList.length;
20953        if (size > 0) {
20954            // Send broadcasts here
20955            Bundle extras = new Bundle();
20956            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20957            if (uidArr != null) {
20958                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20959            }
20960            if (replacing) {
20961                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20962            }
20963            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20964                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20965            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20966        }
20967    }
20968
20969   /*
20970     * Look at potentially valid container ids from processCids If package
20971     * information doesn't match the one on record or package scanning fails,
20972     * the cid is added to list of removeCids. We currently don't delete stale
20973     * containers.
20974     */
20975    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
20976            boolean externalStorage) {
20977        ArrayList<String> pkgList = new ArrayList<String>();
20978        Set<AsecInstallArgs> keys = processCids.keySet();
20979
20980        for (AsecInstallArgs args : keys) {
20981            String codePath = processCids.get(args);
20982            if (DEBUG_SD_INSTALL)
20983                Log.i(TAG, "Loading container : " + args.cid);
20984            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
20985            try {
20986                // Make sure there are no container errors first.
20987                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
20988                    Slog.e(TAG, "Failed to mount cid : " + args.cid
20989                            + " when installing from sdcard");
20990                    continue;
20991                }
20992                // Check code path here.
20993                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
20994                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
20995                            + " does not match one in settings " + codePath);
20996                    continue;
20997                }
20998                // Parse package
20999                int parseFlags = mDefParseFlags;
21000                if (args.isExternalAsec()) {
21001                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21002                }
21003                if (args.isFwdLocked()) {
21004                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21005                }
21006
21007                synchronized (mInstallLock) {
21008                    PackageParser.Package pkg = null;
21009                    try {
21010                        // Sadly we don't know the package name yet to freeze it
21011                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21012                                SCAN_IGNORE_FROZEN, 0, null);
21013                    } catch (PackageManagerException e) {
21014                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21015                    }
21016                    // Scan the package
21017                    if (pkg != null) {
21018                        /*
21019                         * TODO why is the lock being held? doPostInstall is
21020                         * called in other places without the lock. This needs
21021                         * to be straightened out.
21022                         */
21023                        // writer
21024                        synchronized (mPackages) {
21025                            retCode = PackageManager.INSTALL_SUCCEEDED;
21026                            pkgList.add(pkg.packageName);
21027                            // Post process args
21028                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21029                                    pkg.applicationInfo.uid);
21030                        }
21031                    } else {
21032                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21033                    }
21034                }
21035
21036            } finally {
21037                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21038                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21039                }
21040            }
21041        }
21042        // writer
21043        synchronized (mPackages) {
21044            // If the platform SDK has changed since the last time we booted,
21045            // we need to re-grant app permission to catch any new ones that
21046            // appear. This is really a hack, and means that apps can in some
21047            // cases get permissions that the user didn't initially explicitly
21048            // allow... it would be nice to have some better way to handle
21049            // this situation.
21050            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21051                    : mSettings.getInternalVersion();
21052            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21053                    : StorageManager.UUID_PRIVATE_INTERNAL;
21054
21055            int updateFlags = UPDATE_PERMISSIONS_ALL;
21056            if (ver.sdkVersion != mSdkVersion) {
21057                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21058                        + mSdkVersion + "; regranting permissions for external");
21059                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21060            }
21061            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21062
21063            // Yay, everything is now upgraded
21064            ver.forceCurrent();
21065
21066            // can downgrade to reader
21067            // Persist settings
21068            mSettings.writeLPr();
21069        }
21070        // Send a broadcast to let everyone know we are done processing
21071        if (pkgList.size() > 0) {
21072            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21073        }
21074    }
21075
21076   /*
21077     * Utility method to unload a list of specified containers
21078     */
21079    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21080        // Just unmount all valid containers.
21081        for (AsecInstallArgs arg : cidArgs) {
21082            synchronized (mInstallLock) {
21083                arg.doPostDeleteLI(false);
21084           }
21085       }
21086   }
21087
21088    /*
21089     * Unload packages mounted on external media. This involves deleting package
21090     * data from internal structures, sending broadcasts about disabled packages,
21091     * gc'ing to free up references, unmounting all secure containers
21092     * corresponding to packages on external media, and posting a
21093     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21094     * that we always have to post this message if status has been requested no
21095     * matter what.
21096     */
21097    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21098            final boolean reportStatus) {
21099        if (DEBUG_SD_INSTALL)
21100            Log.i(TAG, "unloading media packages");
21101        ArrayList<String> pkgList = new ArrayList<String>();
21102        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21103        final Set<AsecInstallArgs> keys = processCids.keySet();
21104        for (AsecInstallArgs args : keys) {
21105            String pkgName = args.getPackageName();
21106            if (DEBUG_SD_INSTALL)
21107                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21108            // Delete package internally
21109            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21110            synchronized (mInstallLock) {
21111                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21112                final boolean res;
21113                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21114                        "unloadMediaPackages")) {
21115                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21116                            null);
21117                }
21118                if (res) {
21119                    pkgList.add(pkgName);
21120                } else {
21121                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21122                    failedList.add(args);
21123                }
21124            }
21125        }
21126
21127        // reader
21128        synchronized (mPackages) {
21129            // We didn't update the settings after removing each package;
21130            // write them now for all packages.
21131            mSettings.writeLPr();
21132        }
21133
21134        // We have to absolutely send UPDATED_MEDIA_STATUS only
21135        // after confirming that all the receivers processed the ordered
21136        // broadcast when packages get disabled, force a gc to clean things up.
21137        // and unload all the containers.
21138        if (pkgList.size() > 0) {
21139            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21140                    new IIntentReceiver.Stub() {
21141                public void performReceive(Intent intent, int resultCode, String data,
21142                        Bundle extras, boolean ordered, boolean sticky,
21143                        int sendingUser) throws RemoteException {
21144                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21145                            reportStatus ? 1 : 0, 1, keys);
21146                    mHandler.sendMessage(msg);
21147                }
21148            });
21149        } else {
21150            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21151                    keys);
21152            mHandler.sendMessage(msg);
21153        }
21154    }
21155
21156    private void loadPrivatePackages(final VolumeInfo vol) {
21157        mHandler.post(new Runnable() {
21158            @Override
21159            public void run() {
21160                loadPrivatePackagesInner(vol);
21161            }
21162        });
21163    }
21164
21165    private void loadPrivatePackagesInner(VolumeInfo vol) {
21166        final String volumeUuid = vol.fsUuid;
21167        if (TextUtils.isEmpty(volumeUuid)) {
21168            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21169            return;
21170        }
21171
21172        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21173        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21174        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21175
21176        final VersionInfo ver;
21177        final List<PackageSetting> packages;
21178        synchronized (mPackages) {
21179            ver = mSettings.findOrCreateVersion(volumeUuid);
21180            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21181        }
21182
21183        for (PackageSetting ps : packages) {
21184            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21185            synchronized (mInstallLock) {
21186                final PackageParser.Package pkg;
21187                try {
21188                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21189                    loaded.add(pkg.applicationInfo);
21190
21191                } catch (PackageManagerException e) {
21192                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21193                }
21194
21195                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21196                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21197                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21198                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21199                }
21200            }
21201        }
21202
21203        // Reconcile app data for all started/unlocked users
21204        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21205        final UserManager um = mContext.getSystemService(UserManager.class);
21206        UserManagerInternal umInternal = getUserManagerInternal();
21207        for (UserInfo user : um.getUsers()) {
21208            final int flags;
21209            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21210                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21211            } else if (umInternal.isUserRunning(user.id)) {
21212                flags = StorageManager.FLAG_STORAGE_DE;
21213            } else {
21214                continue;
21215            }
21216
21217            try {
21218                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21219                synchronized (mInstallLock) {
21220                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21221                }
21222            } catch (IllegalStateException e) {
21223                // Device was probably ejected, and we'll process that event momentarily
21224                Slog.w(TAG, "Failed to prepare storage: " + e);
21225            }
21226        }
21227
21228        synchronized (mPackages) {
21229            int updateFlags = UPDATE_PERMISSIONS_ALL;
21230            if (ver.sdkVersion != mSdkVersion) {
21231                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21232                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21233                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21234            }
21235            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21236
21237            // Yay, everything is now upgraded
21238            ver.forceCurrent();
21239
21240            mSettings.writeLPr();
21241        }
21242
21243        for (PackageFreezer freezer : freezers) {
21244            freezer.close();
21245        }
21246
21247        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21248        sendResourcesChangedBroadcast(true, false, loaded, null);
21249    }
21250
21251    private void unloadPrivatePackages(final VolumeInfo vol) {
21252        mHandler.post(new Runnable() {
21253            @Override
21254            public void run() {
21255                unloadPrivatePackagesInner(vol);
21256            }
21257        });
21258    }
21259
21260    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21261        final String volumeUuid = vol.fsUuid;
21262        if (TextUtils.isEmpty(volumeUuid)) {
21263            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21264            return;
21265        }
21266
21267        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21268        synchronized (mInstallLock) {
21269        synchronized (mPackages) {
21270            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21271            for (PackageSetting ps : packages) {
21272                if (ps.pkg == null) continue;
21273
21274                final ApplicationInfo info = ps.pkg.applicationInfo;
21275                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21276                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21277
21278                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21279                        "unloadPrivatePackagesInner")) {
21280                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21281                            false, null)) {
21282                        unloaded.add(info);
21283                    } else {
21284                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21285                    }
21286                }
21287
21288                // Try very hard to release any references to this package
21289                // so we don't risk the system server being killed due to
21290                // open FDs
21291                AttributeCache.instance().removePackage(ps.name);
21292            }
21293
21294            mSettings.writeLPr();
21295        }
21296        }
21297
21298        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21299        sendResourcesChangedBroadcast(false, false, unloaded, null);
21300
21301        // Try very hard to release any references to this path so we don't risk
21302        // the system server being killed due to open FDs
21303        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21304
21305        for (int i = 0; i < 3; i++) {
21306            System.gc();
21307            System.runFinalization();
21308        }
21309    }
21310
21311    private void assertPackageKnown(String volumeUuid, String packageName)
21312            throws PackageManagerException {
21313        synchronized (mPackages) {
21314            // Normalize package name to handle renamed packages
21315            packageName = normalizePackageNameLPr(packageName);
21316
21317            final PackageSetting ps = mSettings.mPackages.get(packageName);
21318            if (ps == null) {
21319                throw new PackageManagerException("Package " + packageName + " is unknown");
21320            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21321                throw new PackageManagerException(
21322                        "Package " + packageName + " found on unknown volume " + volumeUuid
21323                                + "; expected volume " + ps.volumeUuid);
21324            }
21325        }
21326    }
21327
21328    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21329            throws PackageManagerException {
21330        synchronized (mPackages) {
21331            // Normalize package name to handle renamed packages
21332            packageName = normalizePackageNameLPr(packageName);
21333
21334            final PackageSetting ps = mSettings.mPackages.get(packageName);
21335            if (ps == null) {
21336                throw new PackageManagerException("Package " + packageName + " is unknown");
21337            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21338                throw new PackageManagerException(
21339                        "Package " + packageName + " found on unknown volume " + volumeUuid
21340                                + "; expected volume " + ps.volumeUuid);
21341            } else if (!ps.getInstalled(userId)) {
21342                throw new PackageManagerException(
21343                        "Package " + packageName + " not installed for user " + userId);
21344            }
21345        }
21346    }
21347
21348    private List<String> collectAbsoluteCodePaths() {
21349        synchronized (mPackages) {
21350            List<String> codePaths = new ArrayList<>();
21351            final int packageCount = mSettings.mPackages.size();
21352            for (int i = 0; i < packageCount; i++) {
21353                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21354                codePaths.add(ps.codePath.getAbsolutePath());
21355            }
21356            return codePaths;
21357        }
21358    }
21359
21360    /**
21361     * Examine all apps present on given mounted volume, and destroy apps that
21362     * aren't expected, either due to uninstallation or reinstallation on
21363     * another volume.
21364     */
21365    private void reconcileApps(String volumeUuid) {
21366        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21367        List<File> filesToDelete = null;
21368
21369        final File[] files = FileUtils.listFilesOrEmpty(
21370                Environment.getDataAppDirectory(volumeUuid));
21371        for (File file : files) {
21372            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21373                    && !PackageInstallerService.isStageName(file.getName());
21374            if (!isPackage) {
21375                // Ignore entries which are not packages
21376                continue;
21377            }
21378
21379            String absolutePath = file.getAbsolutePath();
21380
21381            boolean pathValid = false;
21382            final int absoluteCodePathCount = absoluteCodePaths.size();
21383            for (int i = 0; i < absoluteCodePathCount; i++) {
21384                String absoluteCodePath = absoluteCodePaths.get(i);
21385                if (absolutePath.startsWith(absoluteCodePath)) {
21386                    pathValid = true;
21387                    break;
21388                }
21389            }
21390
21391            if (!pathValid) {
21392                if (filesToDelete == null) {
21393                    filesToDelete = new ArrayList<>();
21394                }
21395                filesToDelete.add(file);
21396            }
21397        }
21398
21399        if (filesToDelete != null) {
21400            final int fileToDeleteCount = filesToDelete.size();
21401            for (int i = 0; i < fileToDeleteCount; i++) {
21402                File fileToDelete = filesToDelete.get(i);
21403                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21404                synchronized (mInstallLock) {
21405                    removeCodePathLI(fileToDelete);
21406                }
21407            }
21408        }
21409    }
21410
21411    /**
21412     * Reconcile all app data for the given user.
21413     * <p>
21414     * Verifies that directories exist and that ownership and labeling is
21415     * correct for all installed apps on all mounted volumes.
21416     */
21417    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21418        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21419        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21420            final String volumeUuid = vol.getFsUuid();
21421            synchronized (mInstallLock) {
21422                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21423            }
21424        }
21425    }
21426
21427    /**
21428     * Reconcile all app data on given mounted volume.
21429     * <p>
21430     * Destroys app data that isn't expected, either due to uninstallation or
21431     * reinstallation on another volume.
21432     * <p>
21433     * Verifies that directories exist and that ownership and labeling is
21434     * correct for all installed apps.
21435     */
21436    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21437            boolean migrateAppData) {
21438        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21439                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21440
21441        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21442        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21443
21444        // First look for stale data that doesn't belong, and check if things
21445        // have changed since we did our last restorecon
21446        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21447            if (StorageManager.isFileEncryptedNativeOrEmulated()
21448                    && !StorageManager.isUserKeyUnlocked(userId)) {
21449                throw new RuntimeException(
21450                        "Yikes, someone asked us to reconcile CE storage while " + userId
21451                                + " was still locked; this would have caused massive data loss!");
21452            }
21453
21454            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21455            for (File file : files) {
21456                final String packageName = file.getName();
21457                try {
21458                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21459                } catch (PackageManagerException e) {
21460                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21461                    try {
21462                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21463                                StorageManager.FLAG_STORAGE_CE, 0);
21464                    } catch (InstallerException e2) {
21465                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21466                    }
21467                }
21468            }
21469        }
21470        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21471            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21472            for (File file : files) {
21473                final String packageName = file.getName();
21474                try {
21475                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21476                } catch (PackageManagerException e) {
21477                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21478                    try {
21479                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21480                                StorageManager.FLAG_STORAGE_DE, 0);
21481                    } catch (InstallerException e2) {
21482                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21483                    }
21484                }
21485            }
21486        }
21487
21488        // Ensure that data directories are ready to roll for all packages
21489        // installed for this volume and user
21490        final List<PackageSetting> packages;
21491        synchronized (mPackages) {
21492            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21493        }
21494        int preparedCount = 0;
21495        for (PackageSetting ps : packages) {
21496            final String packageName = ps.name;
21497            if (ps.pkg == null) {
21498                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21499                // TODO: might be due to legacy ASEC apps; we should circle back
21500                // and reconcile again once they're scanned
21501                continue;
21502            }
21503
21504            if (ps.getInstalled(userId)) {
21505                prepareAppDataLIF(ps.pkg, userId, flags);
21506
21507                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21508                    // We may have just shuffled around app data directories, so
21509                    // prepare them one more time
21510                    prepareAppDataLIF(ps.pkg, userId, flags);
21511                }
21512
21513                preparedCount++;
21514            }
21515        }
21516
21517        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21518    }
21519
21520    /**
21521     * Prepare app data for the given app just after it was installed or
21522     * upgraded. This method carefully only touches users that it's installed
21523     * for, and it forces a restorecon to handle any seinfo changes.
21524     * <p>
21525     * Verifies that directories exist and that ownership and labeling is
21526     * correct for all installed apps. If there is an ownership mismatch, it
21527     * will try recovering system apps by wiping data; third-party app data is
21528     * left intact.
21529     * <p>
21530     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21531     */
21532    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21533        final PackageSetting ps;
21534        synchronized (mPackages) {
21535            ps = mSettings.mPackages.get(pkg.packageName);
21536            mSettings.writeKernelMappingLPr(ps);
21537        }
21538
21539        final UserManager um = mContext.getSystemService(UserManager.class);
21540        UserManagerInternal umInternal = getUserManagerInternal();
21541        for (UserInfo user : um.getUsers()) {
21542            final int flags;
21543            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21544                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21545            } else if (umInternal.isUserRunning(user.id)) {
21546                flags = StorageManager.FLAG_STORAGE_DE;
21547            } else {
21548                continue;
21549            }
21550
21551            if (ps.getInstalled(user.id)) {
21552                // TODO: when user data is locked, mark that we're still dirty
21553                prepareAppDataLIF(pkg, user.id, flags);
21554            }
21555        }
21556    }
21557
21558    /**
21559     * Prepare app data for the given app.
21560     * <p>
21561     * Verifies that directories exist and that ownership and labeling is
21562     * correct for all installed apps. If there is an ownership mismatch, this
21563     * will try recovering system apps by wiping data; third-party app data is
21564     * left intact.
21565     */
21566    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21567        if (pkg == null) {
21568            Slog.wtf(TAG, "Package was null!", new Throwable());
21569            return;
21570        }
21571        prepareAppDataLeafLIF(pkg, userId, flags);
21572        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21573        for (int i = 0; i < childCount; i++) {
21574            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21575        }
21576    }
21577
21578    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21579        if (DEBUG_APP_DATA) {
21580            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21581                    + Integer.toHexString(flags));
21582        }
21583
21584        final String volumeUuid = pkg.volumeUuid;
21585        final String packageName = pkg.packageName;
21586        final ApplicationInfo app = pkg.applicationInfo;
21587        final int appId = UserHandle.getAppId(app.uid);
21588
21589        Preconditions.checkNotNull(app.seinfo);
21590
21591        long ceDataInode = -1;
21592        try {
21593            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21594                    appId, app.seinfo, app.targetSdkVersion);
21595        } catch (InstallerException e) {
21596            if (app.isSystemApp()) {
21597                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21598                        + ", but trying to recover: " + e);
21599                destroyAppDataLeafLIF(pkg, userId, flags);
21600                try {
21601                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21602                            appId, app.seinfo, app.targetSdkVersion);
21603                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21604                } catch (InstallerException e2) {
21605                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21606                }
21607            } else {
21608                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21609            }
21610        }
21611
21612        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21613            // TODO: mark this structure as dirty so we persist it!
21614            synchronized (mPackages) {
21615                final PackageSetting ps = mSettings.mPackages.get(packageName);
21616                if (ps != null) {
21617                    ps.setCeDataInode(ceDataInode, userId);
21618                }
21619            }
21620        }
21621
21622        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21623    }
21624
21625    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21626        if (pkg == null) {
21627            Slog.wtf(TAG, "Package was null!", new Throwable());
21628            return;
21629        }
21630        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21631        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21632        for (int i = 0; i < childCount; i++) {
21633            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21634        }
21635    }
21636
21637    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21638        final String volumeUuid = pkg.volumeUuid;
21639        final String packageName = pkg.packageName;
21640        final ApplicationInfo app = pkg.applicationInfo;
21641
21642        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21643            // Create a native library symlink only if we have native libraries
21644            // and if the native libraries are 32 bit libraries. We do not provide
21645            // this symlink for 64 bit libraries.
21646            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21647                final String nativeLibPath = app.nativeLibraryDir;
21648                try {
21649                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21650                            nativeLibPath, userId);
21651                } catch (InstallerException e) {
21652                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21653                }
21654            }
21655        }
21656    }
21657
21658    /**
21659     * For system apps on non-FBE devices, this method migrates any existing
21660     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21661     * requested by the app.
21662     */
21663    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21664        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21665                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21666            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21667                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21668            try {
21669                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21670                        storageTarget);
21671            } catch (InstallerException e) {
21672                logCriticalInfo(Log.WARN,
21673                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21674            }
21675            return true;
21676        } else {
21677            return false;
21678        }
21679    }
21680
21681    public PackageFreezer freezePackage(String packageName, String killReason) {
21682        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21683    }
21684
21685    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21686        return new PackageFreezer(packageName, userId, killReason);
21687    }
21688
21689    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21690            String killReason) {
21691        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21692    }
21693
21694    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21695            String killReason) {
21696        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21697            return new PackageFreezer();
21698        } else {
21699            return freezePackage(packageName, userId, killReason);
21700        }
21701    }
21702
21703    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21704            String killReason) {
21705        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21706    }
21707
21708    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21709            String killReason) {
21710        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21711            return new PackageFreezer();
21712        } else {
21713            return freezePackage(packageName, userId, killReason);
21714        }
21715    }
21716
21717    /**
21718     * Class that freezes and kills the given package upon creation, and
21719     * unfreezes it upon closing. This is typically used when doing surgery on
21720     * app code/data to prevent the app from running while you're working.
21721     */
21722    private class PackageFreezer implements AutoCloseable {
21723        private final String mPackageName;
21724        private final PackageFreezer[] mChildren;
21725
21726        private final boolean mWeFroze;
21727
21728        private final AtomicBoolean mClosed = new AtomicBoolean();
21729        private final CloseGuard mCloseGuard = CloseGuard.get();
21730
21731        /**
21732         * Create and return a stub freezer that doesn't actually do anything,
21733         * typically used when someone requested
21734         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21735         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21736         */
21737        public PackageFreezer() {
21738            mPackageName = null;
21739            mChildren = null;
21740            mWeFroze = false;
21741            mCloseGuard.open("close");
21742        }
21743
21744        public PackageFreezer(String packageName, int userId, String killReason) {
21745            synchronized (mPackages) {
21746                mPackageName = packageName;
21747                mWeFroze = mFrozenPackages.add(mPackageName);
21748
21749                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21750                if (ps != null) {
21751                    killApplication(ps.name, ps.appId, userId, killReason);
21752                }
21753
21754                final PackageParser.Package p = mPackages.get(packageName);
21755                if (p != null && p.childPackages != null) {
21756                    final int N = p.childPackages.size();
21757                    mChildren = new PackageFreezer[N];
21758                    for (int i = 0; i < N; i++) {
21759                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21760                                userId, killReason);
21761                    }
21762                } else {
21763                    mChildren = null;
21764                }
21765            }
21766            mCloseGuard.open("close");
21767        }
21768
21769        @Override
21770        protected void finalize() throws Throwable {
21771            try {
21772                mCloseGuard.warnIfOpen();
21773                close();
21774            } finally {
21775                super.finalize();
21776            }
21777        }
21778
21779        @Override
21780        public void close() {
21781            mCloseGuard.close();
21782            if (mClosed.compareAndSet(false, true)) {
21783                synchronized (mPackages) {
21784                    if (mWeFroze) {
21785                        mFrozenPackages.remove(mPackageName);
21786                    }
21787
21788                    if (mChildren != null) {
21789                        for (PackageFreezer freezer : mChildren) {
21790                            freezer.close();
21791                        }
21792                    }
21793                }
21794            }
21795        }
21796    }
21797
21798    /**
21799     * Verify that given package is currently frozen.
21800     */
21801    private void checkPackageFrozen(String packageName) {
21802        synchronized (mPackages) {
21803            if (!mFrozenPackages.contains(packageName)) {
21804                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21805            }
21806        }
21807    }
21808
21809    @Override
21810    public int movePackage(final String packageName, final String volumeUuid) {
21811        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21812
21813        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21814        final int moveId = mNextMoveId.getAndIncrement();
21815        mHandler.post(new Runnable() {
21816            @Override
21817            public void run() {
21818                try {
21819                    movePackageInternal(packageName, volumeUuid, moveId, user);
21820                } catch (PackageManagerException e) {
21821                    Slog.w(TAG, "Failed to move " + packageName, e);
21822                    mMoveCallbacks.notifyStatusChanged(moveId,
21823                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21824                }
21825            }
21826        });
21827        return moveId;
21828    }
21829
21830    private void movePackageInternal(final String packageName, final String volumeUuid,
21831            final int moveId, UserHandle user) throws PackageManagerException {
21832        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21833        final PackageManager pm = mContext.getPackageManager();
21834
21835        final boolean currentAsec;
21836        final String currentVolumeUuid;
21837        final File codeFile;
21838        final String installerPackageName;
21839        final String packageAbiOverride;
21840        final int appId;
21841        final String seinfo;
21842        final String label;
21843        final int targetSdkVersion;
21844        final PackageFreezer freezer;
21845        final int[] installedUserIds;
21846
21847        // reader
21848        synchronized (mPackages) {
21849            final PackageParser.Package pkg = mPackages.get(packageName);
21850            final PackageSetting ps = mSettings.mPackages.get(packageName);
21851            if (pkg == null || ps == null) {
21852                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21853            }
21854
21855            if (pkg.applicationInfo.isSystemApp()) {
21856                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21857                        "Cannot move system application");
21858            }
21859
21860            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21861            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21862                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21863            if (isInternalStorage && !allow3rdPartyOnInternal) {
21864                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21865                        "3rd party apps are not allowed on internal storage");
21866            }
21867
21868            if (pkg.applicationInfo.isExternalAsec()) {
21869                currentAsec = true;
21870                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21871            } else if (pkg.applicationInfo.isForwardLocked()) {
21872                currentAsec = true;
21873                currentVolumeUuid = "forward_locked";
21874            } else {
21875                currentAsec = false;
21876                currentVolumeUuid = ps.volumeUuid;
21877
21878                final File probe = new File(pkg.codePath);
21879                final File probeOat = new File(probe, "oat");
21880                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21881                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21882                            "Move only supported for modern cluster style installs");
21883                }
21884            }
21885
21886            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21887                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21888                        "Package already moved to " + volumeUuid);
21889            }
21890            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21891                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21892                        "Device admin cannot be moved");
21893            }
21894
21895            if (mFrozenPackages.contains(packageName)) {
21896                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21897                        "Failed to move already frozen package");
21898            }
21899
21900            codeFile = new File(pkg.codePath);
21901            installerPackageName = ps.installerPackageName;
21902            packageAbiOverride = ps.cpuAbiOverrideString;
21903            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21904            seinfo = pkg.applicationInfo.seinfo;
21905            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21906            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21907            freezer = freezePackage(packageName, "movePackageInternal");
21908            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21909        }
21910
21911        final Bundle extras = new Bundle();
21912        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21913        extras.putString(Intent.EXTRA_TITLE, label);
21914        mMoveCallbacks.notifyCreated(moveId, extras);
21915
21916        int installFlags;
21917        final boolean moveCompleteApp;
21918        final File measurePath;
21919
21920        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21921            installFlags = INSTALL_INTERNAL;
21922            moveCompleteApp = !currentAsec;
21923            measurePath = Environment.getDataAppDirectory(volumeUuid);
21924        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21925            installFlags = INSTALL_EXTERNAL;
21926            moveCompleteApp = false;
21927            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21928        } else {
21929            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21930            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21931                    || !volume.isMountedWritable()) {
21932                freezer.close();
21933                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21934                        "Move location not mounted private volume");
21935            }
21936
21937            Preconditions.checkState(!currentAsec);
21938
21939            installFlags = INSTALL_INTERNAL;
21940            moveCompleteApp = true;
21941            measurePath = Environment.getDataAppDirectory(volumeUuid);
21942        }
21943
21944        final PackageStats stats = new PackageStats(null, -1);
21945        synchronized (mInstaller) {
21946            for (int userId : installedUserIds) {
21947                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21948                    freezer.close();
21949                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21950                            "Failed to measure package size");
21951                }
21952            }
21953        }
21954
21955        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21956                + stats.dataSize);
21957
21958        final long startFreeBytes = measurePath.getFreeSpace();
21959        final long sizeBytes;
21960        if (moveCompleteApp) {
21961            sizeBytes = stats.codeSize + stats.dataSize;
21962        } else {
21963            sizeBytes = stats.codeSize;
21964        }
21965
21966        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21967            freezer.close();
21968            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21969                    "Not enough free space to move");
21970        }
21971
21972        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21973
21974        final CountDownLatch installedLatch = new CountDownLatch(1);
21975        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21976            @Override
21977            public void onUserActionRequired(Intent intent) throws RemoteException {
21978                throw new IllegalStateException();
21979            }
21980
21981            @Override
21982            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21983                    Bundle extras) throws RemoteException {
21984                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21985                        + PackageManager.installStatusToString(returnCode, msg));
21986
21987                installedLatch.countDown();
21988                freezer.close();
21989
21990                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21991                switch (status) {
21992                    case PackageInstaller.STATUS_SUCCESS:
21993                        mMoveCallbacks.notifyStatusChanged(moveId,
21994                                PackageManager.MOVE_SUCCEEDED);
21995                        break;
21996                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21997                        mMoveCallbacks.notifyStatusChanged(moveId,
21998                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21999                        break;
22000                    default:
22001                        mMoveCallbacks.notifyStatusChanged(moveId,
22002                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22003                        break;
22004                }
22005            }
22006        };
22007
22008        final MoveInfo move;
22009        if (moveCompleteApp) {
22010            // Kick off a thread to report progress estimates
22011            new Thread() {
22012                @Override
22013                public void run() {
22014                    while (true) {
22015                        try {
22016                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22017                                break;
22018                            }
22019                        } catch (InterruptedException ignored) {
22020                        }
22021
22022                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22023                        final int progress = 10 + (int) MathUtils.constrain(
22024                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22025                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22026                    }
22027                }
22028            }.start();
22029
22030            final String dataAppName = codeFile.getName();
22031            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22032                    dataAppName, appId, seinfo, targetSdkVersion);
22033        } else {
22034            move = null;
22035        }
22036
22037        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22038
22039        final Message msg = mHandler.obtainMessage(INIT_COPY);
22040        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22041        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22042                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22043                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22044                PackageManager.INSTALL_REASON_UNKNOWN);
22045        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22046        msg.obj = params;
22047
22048        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22049                System.identityHashCode(msg.obj));
22050        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22051                System.identityHashCode(msg.obj));
22052
22053        mHandler.sendMessage(msg);
22054    }
22055
22056    @Override
22057    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22058        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22059
22060        final int realMoveId = mNextMoveId.getAndIncrement();
22061        final Bundle extras = new Bundle();
22062        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22063        mMoveCallbacks.notifyCreated(realMoveId, extras);
22064
22065        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22066            @Override
22067            public void onCreated(int moveId, Bundle extras) {
22068                // Ignored
22069            }
22070
22071            @Override
22072            public void onStatusChanged(int moveId, int status, long estMillis) {
22073                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22074            }
22075        };
22076
22077        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22078        storage.setPrimaryStorageUuid(volumeUuid, callback);
22079        return realMoveId;
22080    }
22081
22082    @Override
22083    public int getMoveStatus(int moveId) {
22084        mContext.enforceCallingOrSelfPermission(
22085                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22086        return mMoveCallbacks.mLastStatus.get(moveId);
22087    }
22088
22089    @Override
22090    public void registerMoveCallback(IPackageMoveObserver callback) {
22091        mContext.enforceCallingOrSelfPermission(
22092                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22093        mMoveCallbacks.register(callback);
22094    }
22095
22096    @Override
22097    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22098        mContext.enforceCallingOrSelfPermission(
22099                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22100        mMoveCallbacks.unregister(callback);
22101    }
22102
22103    @Override
22104    public boolean setInstallLocation(int loc) {
22105        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22106                null);
22107        if (getInstallLocation() == loc) {
22108            return true;
22109        }
22110        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22111                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22112            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22113                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22114            return true;
22115        }
22116        return false;
22117   }
22118
22119    @Override
22120    public int getInstallLocation() {
22121        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22122                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22123                PackageHelper.APP_INSTALL_AUTO);
22124    }
22125
22126    /** Called by UserManagerService */
22127    void cleanUpUser(UserManagerService userManager, int userHandle) {
22128        synchronized (mPackages) {
22129            mDirtyUsers.remove(userHandle);
22130            mUserNeedsBadging.delete(userHandle);
22131            mSettings.removeUserLPw(userHandle);
22132            mPendingBroadcasts.remove(userHandle);
22133            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22134            removeUnusedPackagesLPw(userManager, userHandle);
22135        }
22136    }
22137
22138    /**
22139     * We're removing userHandle and would like to remove any downloaded packages
22140     * that are no longer in use by any other user.
22141     * @param userHandle the user being removed
22142     */
22143    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22144        final boolean DEBUG_CLEAN_APKS = false;
22145        int [] users = userManager.getUserIds();
22146        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22147        while (psit.hasNext()) {
22148            PackageSetting ps = psit.next();
22149            if (ps.pkg == null) {
22150                continue;
22151            }
22152            final String packageName = ps.pkg.packageName;
22153            // Skip over if system app
22154            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22155                continue;
22156            }
22157            if (DEBUG_CLEAN_APKS) {
22158                Slog.i(TAG, "Checking package " + packageName);
22159            }
22160            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22161            if (keep) {
22162                if (DEBUG_CLEAN_APKS) {
22163                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22164                }
22165            } else {
22166                for (int i = 0; i < users.length; i++) {
22167                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22168                        keep = true;
22169                        if (DEBUG_CLEAN_APKS) {
22170                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22171                                    + users[i]);
22172                        }
22173                        break;
22174                    }
22175                }
22176            }
22177            if (!keep) {
22178                if (DEBUG_CLEAN_APKS) {
22179                    Slog.i(TAG, "  Removing package " + packageName);
22180                }
22181                mHandler.post(new Runnable() {
22182                    public void run() {
22183                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22184                                userHandle, 0);
22185                    } //end run
22186                });
22187            }
22188        }
22189    }
22190
22191    /** Called by UserManagerService */
22192    void createNewUser(int userId, String[] disallowedPackages) {
22193        synchronized (mInstallLock) {
22194            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22195        }
22196        synchronized (mPackages) {
22197            scheduleWritePackageRestrictionsLocked(userId);
22198            scheduleWritePackageListLocked(userId);
22199            applyFactoryDefaultBrowserLPw(userId);
22200            primeDomainVerificationsLPw(userId);
22201        }
22202    }
22203
22204    void onNewUserCreated(final int userId) {
22205        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22206        // If permission review for legacy apps is required, we represent
22207        // dagerous permissions for such apps as always granted runtime
22208        // permissions to keep per user flag state whether review is needed.
22209        // Hence, if a new user is added we have to propagate dangerous
22210        // permission grants for these legacy apps.
22211        if (mPermissionReviewRequired) {
22212            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22213                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22214        }
22215    }
22216
22217    @Override
22218    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22219        mContext.enforceCallingOrSelfPermission(
22220                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22221                "Only package verification agents can read the verifier device identity");
22222
22223        synchronized (mPackages) {
22224            return mSettings.getVerifierDeviceIdentityLPw();
22225        }
22226    }
22227
22228    @Override
22229    public void setPermissionEnforced(String permission, boolean enforced) {
22230        // TODO: Now that we no longer change GID for storage, this should to away.
22231        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22232                "setPermissionEnforced");
22233        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22234            synchronized (mPackages) {
22235                if (mSettings.mReadExternalStorageEnforced == null
22236                        || mSettings.mReadExternalStorageEnforced != enforced) {
22237                    mSettings.mReadExternalStorageEnforced = enforced;
22238                    mSettings.writeLPr();
22239                }
22240            }
22241            // kill any non-foreground processes so we restart them and
22242            // grant/revoke the GID.
22243            final IActivityManager am = ActivityManager.getService();
22244            if (am != null) {
22245                final long token = Binder.clearCallingIdentity();
22246                try {
22247                    am.killProcessesBelowForeground("setPermissionEnforcement");
22248                } catch (RemoteException e) {
22249                } finally {
22250                    Binder.restoreCallingIdentity(token);
22251                }
22252            }
22253        } else {
22254            throw new IllegalArgumentException("No selective enforcement for " + permission);
22255        }
22256    }
22257
22258    @Override
22259    @Deprecated
22260    public boolean isPermissionEnforced(String permission) {
22261        return true;
22262    }
22263
22264    @Override
22265    public boolean isStorageLow() {
22266        final long token = Binder.clearCallingIdentity();
22267        try {
22268            final DeviceStorageMonitorInternal
22269                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22270            if (dsm != null) {
22271                return dsm.isMemoryLow();
22272            } else {
22273                return false;
22274            }
22275        } finally {
22276            Binder.restoreCallingIdentity(token);
22277        }
22278    }
22279
22280    @Override
22281    public IPackageInstaller getPackageInstaller() {
22282        return mInstallerService;
22283    }
22284
22285    private boolean userNeedsBadging(int userId) {
22286        int index = mUserNeedsBadging.indexOfKey(userId);
22287        if (index < 0) {
22288            final UserInfo userInfo;
22289            final long token = Binder.clearCallingIdentity();
22290            try {
22291                userInfo = sUserManager.getUserInfo(userId);
22292            } finally {
22293                Binder.restoreCallingIdentity(token);
22294            }
22295            final boolean b;
22296            if (userInfo != null && userInfo.isManagedProfile()) {
22297                b = true;
22298            } else {
22299                b = false;
22300            }
22301            mUserNeedsBadging.put(userId, b);
22302            return b;
22303        }
22304        return mUserNeedsBadging.valueAt(index);
22305    }
22306
22307    @Override
22308    public KeySet getKeySetByAlias(String packageName, String alias) {
22309        if (packageName == null || alias == null) {
22310            return null;
22311        }
22312        synchronized(mPackages) {
22313            final PackageParser.Package pkg = mPackages.get(packageName);
22314            if (pkg == null) {
22315                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22316                throw new IllegalArgumentException("Unknown package: " + packageName);
22317            }
22318            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22319            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22320        }
22321    }
22322
22323    @Override
22324    public KeySet getSigningKeySet(String packageName) {
22325        if (packageName == null) {
22326            return null;
22327        }
22328        synchronized(mPackages) {
22329            final PackageParser.Package pkg = mPackages.get(packageName);
22330            if (pkg == null) {
22331                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22332                throw new IllegalArgumentException("Unknown package: " + packageName);
22333            }
22334            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22335                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22336                throw new SecurityException("May not access signing KeySet of other apps.");
22337            }
22338            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22339            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22340        }
22341    }
22342
22343    @Override
22344    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22345        if (packageName == null || ks == null) {
22346            return false;
22347        }
22348        synchronized(mPackages) {
22349            final PackageParser.Package pkg = mPackages.get(packageName);
22350            if (pkg == null) {
22351                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22352                throw new IllegalArgumentException("Unknown package: " + packageName);
22353            }
22354            IBinder ksh = ks.getToken();
22355            if (ksh instanceof KeySetHandle) {
22356                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22357                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22358            }
22359            return false;
22360        }
22361    }
22362
22363    @Override
22364    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22365        if (packageName == null || ks == null) {
22366            return false;
22367        }
22368        synchronized(mPackages) {
22369            final PackageParser.Package pkg = mPackages.get(packageName);
22370            if (pkg == null) {
22371                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22372                throw new IllegalArgumentException("Unknown package: " + packageName);
22373            }
22374            IBinder ksh = ks.getToken();
22375            if (ksh instanceof KeySetHandle) {
22376                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22377                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22378            }
22379            return false;
22380        }
22381    }
22382
22383    private void deletePackageIfUnusedLPr(final String packageName) {
22384        PackageSetting ps = mSettings.mPackages.get(packageName);
22385        if (ps == null) {
22386            return;
22387        }
22388        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22389            // TODO Implement atomic delete if package is unused
22390            // It is currently possible that the package will be deleted even if it is installed
22391            // after this method returns.
22392            mHandler.post(new Runnable() {
22393                public void run() {
22394                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22395                            0, PackageManager.DELETE_ALL_USERS);
22396                }
22397            });
22398        }
22399    }
22400
22401    /**
22402     * Check and throw if the given before/after packages would be considered a
22403     * downgrade.
22404     */
22405    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22406            throws PackageManagerException {
22407        if (after.versionCode < before.mVersionCode) {
22408            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22409                    "Update version code " + after.versionCode + " is older than current "
22410                    + before.mVersionCode);
22411        } else if (after.versionCode == before.mVersionCode) {
22412            if (after.baseRevisionCode < before.baseRevisionCode) {
22413                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22414                        "Update base revision code " + after.baseRevisionCode
22415                        + " is older than current " + before.baseRevisionCode);
22416            }
22417
22418            if (!ArrayUtils.isEmpty(after.splitNames)) {
22419                for (int i = 0; i < after.splitNames.length; i++) {
22420                    final String splitName = after.splitNames[i];
22421                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22422                    if (j != -1) {
22423                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22424                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22425                                    "Update split " + splitName + " revision code "
22426                                    + after.splitRevisionCodes[i] + " is older than current "
22427                                    + before.splitRevisionCodes[j]);
22428                        }
22429                    }
22430                }
22431            }
22432        }
22433    }
22434
22435    private static class MoveCallbacks extends Handler {
22436        private static final int MSG_CREATED = 1;
22437        private static final int MSG_STATUS_CHANGED = 2;
22438
22439        private final RemoteCallbackList<IPackageMoveObserver>
22440                mCallbacks = new RemoteCallbackList<>();
22441
22442        private final SparseIntArray mLastStatus = new SparseIntArray();
22443
22444        public MoveCallbacks(Looper looper) {
22445            super(looper);
22446        }
22447
22448        public void register(IPackageMoveObserver callback) {
22449            mCallbacks.register(callback);
22450        }
22451
22452        public void unregister(IPackageMoveObserver callback) {
22453            mCallbacks.unregister(callback);
22454        }
22455
22456        @Override
22457        public void handleMessage(Message msg) {
22458            final SomeArgs args = (SomeArgs) msg.obj;
22459            final int n = mCallbacks.beginBroadcast();
22460            for (int i = 0; i < n; i++) {
22461                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22462                try {
22463                    invokeCallback(callback, msg.what, args);
22464                } catch (RemoteException ignored) {
22465                }
22466            }
22467            mCallbacks.finishBroadcast();
22468            args.recycle();
22469        }
22470
22471        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22472                throws RemoteException {
22473            switch (what) {
22474                case MSG_CREATED: {
22475                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22476                    break;
22477                }
22478                case MSG_STATUS_CHANGED: {
22479                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22480                    break;
22481                }
22482            }
22483        }
22484
22485        private void notifyCreated(int moveId, Bundle extras) {
22486            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22487
22488            final SomeArgs args = SomeArgs.obtain();
22489            args.argi1 = moveId;
22490            args.arg2 = extras;
22491            obtainMessage(MSG_CREATED, args).sendToTarget();
22492        }
22493
22494        private void notifyStatusChanged(int moveId, int status) {
22495            notifyStatusChanged(moveId, status, -1);
22496        }
22497
22498        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22499            Slog.v(TAG, "Move " + moveId + " status " + status);
22500
22501            final SomeArgs args = SomeArgs.obtain();
22502            args.argi1 = moveId;
22503            args.argi2 = status;
22504            args.arg3 = estMillis;
22505            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22506
22507            synchronized (mLastStatus) {
22508                mLastStatus.put(moveId, status);
22509            }
22510        }
22511    }
22512
22513    private final static class OnPermissionChangeListeners extends Handler {
22514        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22515
22516        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22517                new RemoteCallbackList<>();
22518
22519        public OnPermissionChangeListeners(Looper looper) {
22520            super(looper);
22521        }
22522
22523        @Override
22524        public void handleMessage(Message msg) {
22525            switch (msg.what) {
22526                case MSG_ON_PERMISSIONS_CHANGED: {
22527                    final int uid = msg.arg1;
22528                    handleOnPermissionsChanged(uid);
22529                } break;
22530            }
22531        }
22532
22533        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22534            mPermissionListeners.register(listener);
22535
22536        }
22537
22538        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22539            mPermissionListeners.unregister(listener);
22540        }
22541
22542        public void onPermissionsChanged(int uid) {
22543            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22544                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22545            }
22546        }
22547
22548        private void handleOnPermissionsChanged(int uid) {
22549            final int count = mPermissionListeners.beginBroadcast();
22550            try {
22551                for (int i = 0; i < count; i++) {
22552                    IOnPermissionsChangeListener callback = mPermissionListeners
22553                            .getBroadcastItem(i);
22554                    try {
22555                        callback.onPermissionsChanged(uid);
22556                    } catch (RemoteException e) {
22557                        Log.e(TAG, "Permission listener is dead", e);
22558                    }
22559                }
22560            } finally {
22561                mPermissionListeners.finishBroadcast();
22562            }
22563        }
22564    }
22565
22566    private class PackageManagerInternalImpl extends PackageManagerInternal {
22567        @Override
22568        public void setLocationPackagesProvider(PackagesProvider provider) {
22569            synchronized (mPackages) {
22570                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22571            }
22572        }
22573
22574        @Override
22575        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22576            synchronized (mPackages) {
22577                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22578            }
22579        }
22580
22581        @Override
22582        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22583            synchronized (mPackages) {
22584                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22585            }
22586        }
22587
22588        @Override
22589        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22590            synchronized (mPackages) {
22591                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22592            }
22593        }
22594
22595        @Override
22596        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22597            synchronized (mPackages) {
22598                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22599            }
22600        }
22601
22602        @Override
22603        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22604            synchronized (mPackages) {
22605                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22606            }
22607        }
22608
22609        @Override
22610        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22611            synchronized (mPackages) {
22612                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22613                        packageName, userId);
22614            }
22615        }
22616
22617        @Override
22618        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22619            synchronized (mPackages) {
22620                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22621                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22622                        packageName, userId);
22623            }
22624        }
22625
22626        @Override
22627        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22628            synchronized (mPackages) {
22629                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22630                        packageName, userId);
22631            }
22632        }
22633
22634        @Override
22635        public void setKeepUninstalledPackages(final List<String> packageList) {
22636            Preconditions.checkNotNull(packageList);
22637            List<String> removedFromList = null;
22638            synchronized (mPackages) {
22639                if (mKeepUninstalledPackages != null) {
22640                    final int packagesCount = mKeepUninstalledPackages.size();
22641                    for (int i = 0; i < packagesCount; i++) {
22642                        String oldPackage = mKeepUninstalledPackages.get(i);
22643                        if (packageList != null && packageList.contains(oldPackage)) {
22644                            continue;
22645                        }
22646                        if (removedFromList == null) {
22647                            removedFromList = new ArrayList<>();
22648                        }
22649                        removedFromList.add(oldPackage);
22650                    }
22651                }
22652                mKeepUninstalledPackages = new ArrayList<>(packageList);
22653                if (removedFromList != null) {
22654                    final int removedCount = removedFromList.size();
22655                    for (int i = 0; i < removedCount; i++) {
22656                        deletePackageIfUnusedLPr(removedFromList.get(i));
22657                    }
22658                }
22659            }
22660        }
22661
22662        @Override
22663        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22664            synchronized (mPackages) {
22665                // If we do not support permission review, done.
22666                if (!mPermissionReviewRequired) {
22667                    return false;
22668                }
22669
22670                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22671                if (packageSetting == null) {
22672                    return false;
22673                }
22674
22675                // Permission review applies only to apps not supporting the new permission model.
22676                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22677                    return false;
22678                }
22679
22680                // Legacy apps have the permission and get user consent on launch.
22681                PermissionsState permissionsState = packageSetting.getPermissionsState();
22682                return permissionsState.isPermissionReviewRequired(userId);
22683            }
22684        }
22685
22686        @Override
22687        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22688            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22689        }
22690
22691        @Override
22692        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22693                int userId) {
22694            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22695        }
22696
22697        @Override
22698        public void setDeviceAndProfileOwnerPackages(
22699                int deviceOwnerUserId, String deviceOwnerPackage,
22700                SparseArray<String> profileOwnerPackages) {
22701            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22702                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22703        }
22704
22705        @Override
22706        public boolean isPackageDataProtected(int userId, String packageName) {
22707            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22708        }
22709
22710        @Override
22711        public boolean isPackageEphemeral(int userId, String packageName) {
22712            synchronized (mPackages) {
22713                PackageParser.Package p = mPackages.get(packageName);
22714                return p != null ? p.applicationInfo.isInstantApp() : false;
22715            }
22716        }
22717
22718        @Override
22719        public boolean wasPackageEverLaunched(String packageName, int userId) {
22720            synchronized (mPackages) {
22721                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22722            }
22723        }
22724
22725        @Override
22726        public void grantRuntimePermission(String packageName, String name, int userId,
22727                boolean overridePolicy) {
22728            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22729                    overridePolicy);
22730        }
22731
22732        @Override
22733        public void revokeRuntimePermission(String packageName, String name, int userId,
22734                boolean overridePolicy) {
22735            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22736                    overridePolicy);
22737        }
22738
22739        @Override
22740        public String getNameForUid(int uid) {
22741            return PackageManagerService.this.getNameForUid(uid);
22742        }
22743
22744        @Override
22745        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22746                Intent origIntent, String resolvedType, Intent launchIntent,
22747                String callingPackage, int userId) {
22748            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22749                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22750        }
22751
22752        @Override
22753        public void grantEphemeralAccess(int userId, Intent intent,
22754                int targetAppId, int ephemeralAppId) {
22755            synchronized (mPackages) {
22756                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22757                        targetAppId, ephemeralAppId);
22758            }
22759        }
22760
22761        @Override
22762        public void pruneInstantApps() {
22763            synchronized (mPackages) {
22764                mInstantAppRegistry.pruneInstantAppsLPw();
22765            }
22766        }
22767
22768        @Override
22769        public String getSetupWizardPackageName() {
22770            return mSetupWizardPackage;
22771        }
22772
22773        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22774            if (policy != null) {
22775                mExternalSourcesPolicy = policy;
22776            }
22777        }
22778
22779        @Override
22780        public List<PackageInfo> getOverlayPackages(int userId) {
22781            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22782            synchronized (mPackages) {
22783                for (PackageParser.Package p : mPackages.values()) {
22784                    if (p.mOverlayTarget != null) {
22785                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22786                        if (pkg != null) {
22787                            overlayPackages.add(pkg);
22788                        }
22789                    }
22790                }
22791            }
22792            return overlayPackages;
22793        }
22794
22795        @Override
22796        public List<String> getTargetPackageNames(int userId) {
22797            List<String> targetPackages = new ArrayList<>();
22798            synchronized (mPackages) {
22799                for (PackageParser.Package p : mPackages.values()) {
22800                    if (p.mOverlayTarget == null) {
22801                        targetPackages.add(p.packageName);
22802                    }
22803                }
22804            }
22805            return targetPackages;
22806        }
22807
22808
22809        @Override
22810        public boolean setEnabledOverlayPackages(int userId, String targetPackageName,
22811                List<String> overlayPackageNames) {
22812            // TODO: implement when we integrate OMS properly
22813            return false;
22814        }
22815    }
22816
22817    @Override
22818    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22819        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22820        synchronized (mPackages) {
22821            final long identity = Binder.clearCallingIdentity();
22822            try {
22823                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
22824                        packageNames, userId);
22825            } finally {
22826                Binder.restoreCallingIdentity(identity);
22827            }
22828        }
22829    }
22830
22831    @Override
22832    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
22833        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
22834        synchronized (mPackages) {
22835            final long identity = Binder.clearCallingIdentity();
22836            try {
22837                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
22838                        packageNames, userId);
22839            } finally {
22840                Binder.restoreCallingIdentity(identity);
22841            }
22842        }
22843    }
22844
22845    private static void enforceSystemOrPhoneCaller(String tag) {
22846        int callingUid = Binder.getCallingUid();
22847        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22848            throw new SecurityException(
22849                    "Cannot call " + tag + " from UID " + callingUid);
22850        }
22851    }
22852
22853    boolean isHistoricalPackageUsageAvailable() {
22854        return mPackageUsage.isHistoricalPackageUsageAvailable();
22855    }
22856
22857    /**
22858     * Return a <b>copy</b> of the collection of packages known to the package manager.
22859     * @return A copy of the values of mPackages.
22860     */
22861    Collection<PackageParser.Package> getPackages() {
22862        synchronized (mPackages) {
22863            return new ArrayList<>(mPackages.values());
22864        }
22865    }
22866
22867    /**
22868     * Logs process start information (including base APK hash) to the security log.
22869     * @hide
22870     */
22871    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22872            String apkFile, int pid) {
22873        if (!SecurityLog.isLoggingEnabled()) {
22874            return;
22875        }
22876        Bundle data = new Bundle();
22877        data.putLong("startTimestamp", System.currentTimeMillis());
22878        data.putString("processName", processName);
22879        data.putInt("uid", uid);
22880        data.putString("seinfo", seinfo);
22881        data.putString("apkFile", apkFile);
22882        data.putInt("pid", pid);
22883        Message msg = mProcessLoggingHandler.obtainMessage(
22884                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22885        msg.setData(data);
22886        mProcessLoggingHandler.sendMessage(msg);
22887    }
22888
22889    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22890        return mCompilerStats.getPackageStats(pkgName);
22891    }
22892
22893    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22894        return getOrCreateCompilerPackageStats(pkg.packageName);
22895    }
22896
22897    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22898        return mCompilerStats.getOrCreatePackageStats(pkgName);
22899    }
22900
22901    public void deleteCompilerPackageStats(String pkgName) {
22902        mCompilerStats.deletePackageStats(pkgName);
22903    }
22904
22905    @Override
22906    public int getInstallReason(String packageName, int userId) {
22907        enforceCrossUserPermission(Binder.getCallingUid(), userId,
22908                true /* requireFullPermission */, false /* checkShell */,
22909                "get install reason");
22910        synchronized (mPackages) {
22911            final PackageSetting ps = mSettings.mPackages.get(packageName);
22912            if (ps != null) {
22913                return ps.getInstallReason(userId);
22914            }
22915        }
22916        return PackageManager.INSTALL_REASON_UNKNOWN;
22917    }
22918
22919    @Override
22920    public boolean canRequestPackageInstalls(String packageName, int userId) {
22921        int callingUid = Binder.getCallingUid();
22922        int uid = getPackageUid(packageName, 0, userId);
22923        if (callingUid != uid && callingUid != Process.ROOT_UID
22924                && callingUid != Process.SYSTEM_UID) {
22925            throw new SecurityException(
22926                    "Caller uid " + callingUid + " does not own package " + packageName);
22927        }
22928        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
22929        if (info == null) {
22930            return false;
22931        }
22932        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
22933            throw new UnsupportedOperationException(
22934                    "Operation only supported on apps targeting Android O or higher");
22935        }
22936        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
22937        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
22938        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
22939            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
22940        }
22941        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
22942            return false;
22943        }
22944        if (mExternalSourcesPolicy != null) {
22945            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
22946            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
22947                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
22948            }
22949        }
22950        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
22951    }
22952}
22953